简体   繁体   中英

Waiting for threads

I'm using CreateThread() for my 4 threads.
I would like to run all my threads simultaneously, but wait for all 4 to finish before continuing with the main thread.

I used an int and increased it at the start of the thread, then decreased it at the end, then in my main thread I used a while loop to hold while the number is over a certain value... however this didn't seem to work correctly.

Is this possible?

Use WaitForMultipleObjects with the bWaitAll flag set, on all of your thread handles. The function will return once all threads exit.

You can use the mechanism of signaled states and the WaitForMultipleObjects function to wait for the events or threads themselves (pointed to by their handles) to reach a signalled state.

By simply sharing a single variable among those threads you're probably running into synchronization problems, especially when they are spread among your CPU's cores.

If you want to modify a shared value atomically without using synchronization mechanisms, use the "Interlocked*" functions like InterlockedIncrement , although that doesn't completely guarantee that there will be no problems. Don't use that method as a synchronization mechanism anyway.

If you want that your main thread waits until all the child threads complete their job then You can use:

pthread_join

Edit:

Ah it is windows platform(I failed to notice that before), So you need to use,

WaitForMultipleObjects

What you will likely want to do is create the four threads and then call WaitForSingleObject on the four handles returned, in order. Just make sure the four threads exit with a call to ExitThread .

EDIT:

Or, as pointed out in Hasturkun's answer, use WaitForMultipleObjects ... that would be smart. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM