Stopping C++ 11 std::threads waiting on a std::condition_variable Stopping C++ 11 std::threads waiting on a std::condition_variable multithreading multithreading

Stopping C++ 11 std::threads waiting on a std::condition_variable


No, there's nothing wrong with your design, and it's the normal approach taken for this sort of problem.

It's perfectly valid for you to have multiple conditions (eg anything on queue or program stopping) attached to a condition variable. The key thing is that the bits in the condition are checked for when the wait returns.

Instead of having a flag in Queue to indicate that the program is stopping you should think of the flag as "can I accept". This is a better overall paradigm and works better in a multi-threaded environment.

Also, instead of having pop throw an exception if someone calls it and stop has been called you could replace the method with bool try_pop(int &value) which will return true if a value was returned, otherwise false. This way the caller can check on failure to see if the queue has been stopped (add a bool is_stopped() const method). Although exception handling works here it's a bit heavy handed and isn't really an exceptional case in a multi-threaded program.


wait can be called with a timeout. Control is returned to the thread and stop could be checked. Depending on that value it can wait on more items to be consumed or finish execution. A good introduction to multithreading with c++ is C++11 Concurrency .