1

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.

Swiss Frank
  • 1,985
  • 15
  • 33
  • 1
    Check out some of the C++ 11 Semaphore implementations in this SO post: [C++0x has no semaphores? How to synchronize threads?](https://stackoverflow.com/q/4792449/6610379). You would provide the (initially 0-count, i.e., locked) Semaphore to each thread, then call `notify`() for each thread to release them when it was time for them to proceed. – Phil Brubaker May 07 '20 at 07:47
  • 2
    The terms you are looking for are "latch" and "barrier". C++20 provides [`std::latch`](https://en.cppreference.com/w/cpp/thread/latch) and [`std::barrier`](https://en.cppreference.com/w/cpp/thread/barrier). Pre-C++20, you could use [`boost::latch`](https://www.boost.org/doc/libs/1_73_0/doc/html/thread/synchronization.html#thread.synchronization.latches) or [`boost::barrier`](https://www.boost.org/doc/libs/1_73_0/doc/html/thread/synchronization.html#thread.synchronization.barriers), or at least see how they are implemented. – Igor Tandetnik May 09 '20 at 14:23

0 Answers0