Click here to Skip to main content
14,387,819 members
Rate this:
Please Sign up or sign in to 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
Rate this:
Please Sign up or sign in to vote.

Solution 1

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.../// 
   
Comments
   
Correct, my 5.
Please see my answer where I explain what happens here.
--SA
Rate this:
Please Sign up or sign in to vote.

Solution 2

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
   
Comments
CS2011 20-May-11 1:09am
   
Well Explained.
   
Thank you.
--SA

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100