473,387 Members | 1,453 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Synchronizing multithreaded loops in C#

Greetings
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
  1. public class Alpha
  2.     {
  3.         public int index;
  4.  
  5.         public static int threadsDone = 4; //static so that it can be changed by all threads
  6.         private ManualResetEvent waitHandle;        
  7.  
  8.         public Alpha(int index)
  9.         {
  10.             this.index = index;
  11.             waitHandle = new ManualResetEvent(false);
  12.         }
  13.  
  14.         public void DoWork()
  15.         {
  16.  
  17.             for (int i = 0; i < 4; i++)
  18.             {
  19.                 lock(this)
  20.                 {
  21.                     Console.WriteLine("Thread " + Thread.CurrentThread.Name + " is in iteration " + i);
  22.                     //if the thread is the final thread then notify all threads to exit wait mode
  23.                     if (threadsDone-- == 1)
  24.                     {
  25.                         threadsDone = 4;
  26.                         waitHandle.Set();//notify all threads to exit wait !!NOT WORKING!! it notifies only the current thread
  27.                     }
  28.                     else
  29.                     {
  30.                         waitHandle.WaitOne();
  31.                     }
  32.                 }
  33.             }
  34.  
  35.         }
  36.  
  37.         static void Main(string[] args)
  38.         {
  39.             List<Alpha> alphas = new List<Alpha>();
  40.  
  41.  
  42.             for (int i = 0; i < 4; i++)
  43.             {
  44.                 Alpha alpha = new Alpha(i);
  45.                 alphas.Add(alpha);
  46.             }
  47.  
  48.             foreach (Alpha alpha in alphas)
  49.             {
  50.                 Thread thread = new Thread(new ThreadStart(alpha.DoWork));
  51.                 thread.Name = alpha.index.ToString();
  52.                 thread.Start();
  53.             }
  54.             Console.Read();
  55.         }
  56.     }
  57.  
The problem is 1) the four threads in the first iteration enter the wait mode successfully but when the last thread cals set none of the threads exit the wait mode. 2) the fourth and last thread which calls set to notify the other threads never enters the wait mode again.

Can anyone please spot an error in the code, or provide code or tutorials which could be helpful to achieving this?

Thanks in advance
Jul 24 '07 #1
0 952

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: vincent delft | last post by:
What will be the result if I have several threads that print to different buffers ? I have several threads, each one execute different python code. Just before the "exec" of this small python...
1
by: Elbert Lev | last post by:
I started with Python two weeks ago and already saved some time and efforts while writing 2 programs: 1. database extraction and backup tool, which runs once a month and creates a snapshot of...
3
by: Keith Veleba | last post by:
Hello to all fellow c.l.p'ers! Long-time listener, first-time caller. Background: I'm working on a project where I have to do some serious multithreading. I've worked up a decorator in Python...
2
by: pradyumna | last post by:
In Project settins - C/C++ - Code Generation, what is the difference between the option "Multithreaded" and "Multithreaded DLL". I understand that on selecting multithreaded option, single and...
2
by: Christopher D. Wiederspan | last post by:
We are getting ready to move an ASP.NET application off of a single development machine and onto a "webfarm". Basically our webfarm is a bunch of identical servers with the load-balancing provided...
3
by: groups | last post by:
Hi all, I've recently ported a rather large C application to run multithreaded. A few functions have seriously deteriorated in performance, in particular when accessing a rather large global...
4
by: Thirsty Traveler | last post by:
I have a need to implement a webservice where speed is of the essence. This web service will process product orders in a B2B Extranet scenario where SLA's are critical, as well as collect metrics...
3
by: | last post by:
Is it possible to have just a multithreaded sub procedure? What I need is a timer time_elapsed event (2 sec interval) send params to a sub that is multithreaded. I have a COM component used to...
3
by: Jake K | last post by:
I have a multithreaded application that I now want to convert into a Windows Service. Does application.run work in a windows service? Are there things to take into consideration when creating a...
8
by: colin | last post by:
Hi, this probaly isnt the most relevant place to ask this, but Im using a windows forms in c# timer to process user input and invalidate a window if its changed. Im having problems in that the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.