What is the best way to wait on multiple condition variables in C++11?

前端 未结 3 620
夕颜
夕颜 2020-12-08 19:46

First a little context: I\'m in the process of learning about threading in C++11 and for this purpose, I\'m trying to build a small actor class

3条回答
  •  猫巷女王i
    2020-12-08 20:11

    You ask,

    What is the best way to wait on multiple condition variables in C++11?

    You can't, and must redesign. One thread may wait on only one condition variable (and its associated mutex) at a time. In this regard the Windows facilities for synchronization are rather richer than those of the "POSIX-style" family of synchronization primitives.

    The typical approach with thread-safe queues is to enqueue a special "all done!" message, or to design a "breakable" (or "shutdown-able") queue. In the latter case, the queue's internal condition variable then protects a complex predicate: either an item is available or the queue has been broken.

    In a comment you observe that

    a notify_all() will have no effect if there is no one waiting

    That's true but probably not relevant. wait()ing on a condition variable also implies checking a predicate, and checking it before actually blocking for a notification. So, a worker thread busy processing a queue item that "misses" a notify_all() will see, the next time it inspects the queue condition, that the predicate (a new item is available, or, the queue is all done) has changed.

提交回复
热议问题