Notifying main thread when all worker threads are complete

My main thread spawns a number of worker threads to process records in a file. The number of threads is controlled by the user, based on his or her available hardware, and the number of records in the file is unknown.

I need to know when *all* my worker threads are complete, so I can then close the file and perform other finalise processing. I'm creating my own threads rather than using the threadpool, as I figured this would be more appropriate, but maybe that's wrong?

The basic structure of my code so far is listed below. What I need to know is what would be the best way to check that all worker threads have completed, and where I need to check that. I've tried keeping a counter of the threads as they start and finish processing, but that suffered from race conditions. I'm assuming I can't Join the worker threads, as the moment I join the first one, I won't be able to join any others until the first one ends. Basically, I'm stuck :)

Many thanks
Gerry

public void Process()
{
      private int m_cpuThreads;

      for (int t = 0; t < m_cpuThreads; t++)
      {
            ThreadStart threadStart = new ThreadStart(this.ProcessRecords);
            Thread workerThread = new Thread(threadStart);
            workerThread.Start();
      }
}

private void ProcessRecords()
{
      try
      {
            while (true)
            {
                  ThreadControl threadCtrl = ReadFile();  //Threadsafe method to read records from file and check if EOF reached.

                  if (threadCtrl.RecordsRead == 0)
                  {
                        //No more records left to process, so quit loop
                        break;
                  }
                  
                  ....code to process file records
      }
      catch (System.Exception e)
      {
            Trace.WriteLine(e.Message);
      }
}
LVL 4
gamesmeisterAsked:
Who is Participating?
 
AlexFMCommented:
You can assosiate ManualResetEvent instance with every worker thread. Thread signals it's event before exit. To wait for all threads use WaitHandle.WaitAll Method passing array of these events to it.
0
 
mcv22Commented:
One way is by the IsAlive property.

do
{

  //code

} while (thread1.IsAlive);
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.