Click here to Skip to main content
15,889,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If the application, threads are created using AfxBeginthread and for synchronization CSemephore is used then if the no. of worker threads is not fixed (i.e dependends in runtime).
How the main thread waits for all the worker thread to finish there execution first before terminate itself?
Posted
Updated 26-Apr-10 23:14pm
v2

1 solution

You could do the operations below:


  1. add the CREATE_SUSPENDED flag to any call to AfxBeginThread
  2. call DuplicateHandle to get a copy of the m_hThread of each CWinThread object returned by the previous call to AfxBeginThread
  3. call ResumeThread on each CWinThread object returned by the previous call to AfxBeginThread


This will ensure that you get an handle to each thread you create (you should create each thread suspended because CWinThread will auto-delete on thread termination, and you need that the thread doesn't terminate before that you have completed your initialization steps).

When you are about to terminate your main thread, do the following:


  1. make a call to WaitForMultipleObject passing it an array with all the handles of the threads you have created
  2. call CloseHandle fore each handle that you have previously duplicated
 
Share this answer
 

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