Click here to Skip to main content
15,860,972 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I have a main thread , 4 child thread work is assigned to all main and child threads, the problem is that main thread finishes the work fast, but child threads cannot.If main thread finishes fast before child thread the program hangs-on. I need to run the main thread until the child threads finish the work.
Posted

There is many ways to do this and as per me the simplest way is to use join.

Sample Code

for(int i = 0 ;i < childThreadList.Count; i++) 
{     
      childThreadList[i].Join(); 
} 
///...The following code will execute when all threads in the list have been terminated.../// 
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 20-May-11 1:05am    
Correct, my 5.
Please see my answer where I explain what happens here.
--SA
First, there is no such notion as child and parent threads. I understand the problems though. There are many way to synchronize threads, but your case is nearly the simplest: one thread can get into a wait state until some other thread finished via System.Windows.Thread.Join. For example, is a thread th1 calls th2.Join (where th2 is another currently active thread), the thread th1 will enter the wait state: it's switched off by OS and does not scheduled back to execution (thus spending exactly zero CPU time) until OS awakes is on certain condition. In this case, the thread th1 will be waken up when th2 finished. Another conditions include th1.Abort, th1.Interrupt or timeout on the previously called th2.Join (it it was called with timeout parameter).

This is exactly what you need in this case. You start-up thread should call Thread.Join four times for other four threads, sequentially; the order of calls does not matter: if a thread is already finished, Thread.Join will simply return immediately. If you think about the order of these operations you will see it always works… provided you somehow guarantee that each of four thread will certainly finish.

Problem solved.

—SA
 
Share this answer
 
Comments
CS2011 20-May-11 1:09am    
Well Explained.
Sergey Alexandrovich Kryukov 20-May-11 1:21am    
Thank you.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900