Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.Threading;
- namespace SRV2
- {
- public partial class Form1 : Form
- {
- List<int> myBuf;
- List<int> myWorked;
- Thread Generator;
- Thread Checker;
- Thread[] myPool;
- Boolean[] IRun;
- Mutex myMutex;
- int Semaphore;
- int PoolCount;
- public Form1()
- {
- InitializeComponent();
- timer1.Interval = 100;
- timer1.Enabled = true;
- Semaphore = 0;
- PoolCount = 2;
- myBuf = new List<int>();
- myWorked = new List<int>();
- myPool = new Thread[PoolCount];
- IRun = new Boolean[PoolCount];
- for (int i = 0; i < PoolCount; i++)
- {
- myPool[i] = new Thread(delegate ()
- {
- doSomething(i);
- });
- IRun[i] = false;
- }
- Generator = new Thread(delegate ()
- {
- while (true)
- {
- int N = new Random().Next(1, 10);
- for (int i = 0; i < N; i++)
- {
- GenerateNumber();
- Semaphore++;
- }
- Thread.Sleep(1500);
- }
- });
- Checker = new Thread(delegate ()
- {
- while (true)
- {
- Thread.Sleep(2000);
- if (Semaphore > 0)
- {
- this.doSomethingParallel();
- }
- }
- });
- Generator.Start();
- Checker.Start();
- }
- public void GenerateNumber()
- {
- myBuf.Add(new Random().Next(100));
- }
- public void doSomethingParallel()
- {
- Random myRand = new Random();
- while(Semaphore>0)
- {
- while(true)
- {
- int numb = myRand.Next(myPool.Count()-1);
- Boolean tmp = myPool[numb].ThreadState != ThreadState.Running;
- // MessageBox.Show(tmp.ToString());
- if (!IRun[numb])
- {
- myPool[numb] = new Thread(delegate () { doSomething(numb); });
- myPool[numb].Start();
- Semaphore--;
- break;
- }
- }
- }
- }
- public void doSomething(int numb)
- {
- IRun[numb] = true;
- int i = myBuf[0];
- Thread.Sleep(1000);
- myBuf.RemoveAt(0);
- myWorked.Add(i);
- IRun[numb] = false;
- // MessageBox.Show(myBuf[0].ToString());
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- }
- private void timer1_Tick(object sender, EventArgs e)
- {
- try
- {
- String BufText = "";
- String WorkedText = "";
- foreach (int i in myBuf)
- {
- BufText += i.ToString() + ", ";
- }
- foreach (int i in myWorked)
- {
- WorkedText += i.ToString() + ", ";
- }
- textBox1.Text = BufText;
- textBox2.Text = WorkedText;
- textBox1.Invalidate();
- textBox2.Invalidate();
- label1.Text = Semaphore.ToString();
- }
- catch
- {
- ;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement