std::condition_variable - Wait for several threads to notify observer

后端 未结 1 929
迷失自我
迷失自我 2020-12-22 11:06

my problem looks like this:

I\'ve got a observer which holds a std::condition_variable and a std::mutex, my worker thread objects have a pointer to the observer. Eac

1条回答
  •  北海茫月
    2020-12-22 11:31

    You try to use condition variables in a way they are not meant to be used - in this case, you assume that you can count notifications. You can't. You may lose notifications by that, and you are counting spurious wake-ups that are allowed by the standard.

    Instead, you should use a counter incremented under a mutex and signalling the condition variable only when the counter reached the number of workers. (Do this in each worker at the end). The main thread keeps sleeping on the condition variable until the counter reaches the expected value. (Of course, verification of the counter has to be done holding the mutex you use for incrementing, too). As far as I can see, replacing the mutexed counter by an atomic (without mutexing it) seems impossible, as you can't atomically check the counter and sleep on the condvar, so you will get a race condition without mutexing the counter.

    Another synchronization primitive known from boost threads is the barrier, which did not get into C++11. You construct a barrier, and pass it the number of worker threads plus one as constructor argument. All worker threads should wait for the condition variable at their end and the main thread should wait after constructing the workers. All threads will block on that barrier, until all worker threads and the main thread are blocking, and will be released at that moment. So if the main thread is released, you know that all workers finished. This has one problem though: No worker thread is finished (and freeing associated management resources) until all worker threads are finshed, which may or may not be a problem for you. This question presents an implementation of boost::barrier using C++11 threading facilities.

    0 讨论(0)
提交回复
热议问题