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

前端 未结 2 454
孤城傲影
孤城傲影 2021-02-02 07:21

I am trying to understand the basic multithreading mechanisms in the new C++ 11 standard. The most basic example I can think of is the following:

  • A producer and a
2条回答
  •  遥遥无期
    2021-02-02 07:53

    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.

提交回复
热议问题