I would like some help on achieving synchronization between multiple threads running a for loop.
In more detail I would like each thread to be in the same iteration with each other thread, meaning no thread would be in the fifth iteration when another is in the second or in the first...
So the results would go
Thread1 = iteration 1
Thread2 = iteration 1
Thread3 = iteration 1
Thread4 = iteration 1
Thread1 = iteration 2
Thread2 = iteration 2
Thread3 = iteration 2
Thread4 = iteration 2...
And not
Thread1 = iteration 2
Thread2 = iteration 2
Thread3 = iteration 1
Thread4 = iteration 1
Thread1 = iteration 3
Thread2 = iteration 2
Thread3 = iteration 1
Thread4 = iteration 1...
Here is some code I wrote:
Expand|Select|Wrap|Line Numbers
- public class Alpha
- {
- public int index;
- public static int threadsDone = 4; //static so that it can be changed by all threads
- private ManualResetEvent waitHandle;
- public Alpha(int index)
- {
- this.index = index;
- waitHandle = new ManualResetEvent(false);
- }
- public void DoWork()
- {
- for (int i = 0; i < 4; i++)
- {
- lock(this)
- {
- Console.WriteLine("Thread " + Thread.CurrentThread.Name + " is in iteration " + i);
- //if the thread is the final thread then notify all threads to exit wait mode
- if (threadsDone-- == 1)
- {
- threadsDone = 4;
- waitHandle.Set();//notify all threads to exit wait !!NOT WORKING!! it notifies only the current thread
- }
- else
- {
- waitHandle.WaitOne();
- }
- }
- }
- }
- static void Main(string[] args)
- {
- List<Alpha> alphas = new List<Alpha>();
- for (int i = 0; i < 4; i++)
- {
- Alpha alpha = new Alpha(i);
- alphas.Add(alpha);
- }
- foreach (Alpha alpha in alphas)
- {
- Thread thread = new Thread(new ThreadStart(alpha.DoWork));
- thread.Name = alpha.index.ToString();
- thread.Start();
- }
- Console.Read();
- }
- }
Can anyone please spot an error in the code, or provide code or tutorials which could be helpful to achieving this?
Thanks in advance