Reputation: 139
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?
Upvotes: 2
Views: 343
Reputation: 16193
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.
Upvotes: 1
Reputation: 206528
If you want that your main thread waits until all the child threads complete their job then You can use:
Edit:
Ah it is windows platform(I failed to notice that before), So you need to use,
Upvotes: 0
Reputation: 5425
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. :-)
Upvotes: 0
Reputation: 36402
Use WaitForMultipleObjects
with the bWaitAll
flag set, on all of your thread handles. The function will return once all threads exit.
Upvotes: 7