I launch many child threads and they all do their first task. I want them all to wait before continuing with their second task.
My idea was some code like:
some_lock_type lock;
atomic<int> iThreadsDoneStep1;
void Thread() {
// Step 1.
:
:
// Now wait for the rest to finish step 1, or if I am the last to finish, wake up the others.
if ( ++iThreadsDoneStep1 == iThreadCount )
lock.notify_all();
else
lock.wait();
// Step 2.
:
:
}
Of course it turns out condition variables don't work like that. I'm trying to figure out if they're even useful for this problem, or whether I need futures, or what.
The best idea I have is to use the C++17 shared_mutex. The main thread would acquire the exclusive lock with lock()
, and notify_all()
in the above example would in fact be unlock()
while wait()
would be lock_shared()
. Once the exclusive lock is freed, all the non-exclusive lockseekers would succeed and continue. However it seems to be utterly different than the spirit of the lock class, and I'd prefer not to go past C++11.