Notifying main thread when all worker threads are complete
Posted on 2005-05-09
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 :)
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);
private void ProcessRecords()
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
....code to process file records
catch (System.Exception e)