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

ε祈祈猫儿з 提交于 2019-12-02 20:16:54

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 .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!