了解std :: condition_variable

时间:2017-11-22 16:50:31

标签: c++

我在这里引用接受的答案:Using std::conditional_variable to wait on a condition,特别是代码(复制):

struct gate {
  bool gate_open = false;
  mutable std::condition_variable cv;
  mutable std::mutex m;

  void open_gate() {
    std::unique_lock<std::mutex> lock(m);
    gate_open=true;
    cv.notify_all();
  }
  void wait_at_gate() const {
    std::unique_lock<std::mutex> lock(m);
    cv.wait( lock, [this]{ return gate_open; } );
  }
};

我不明白这是如何作为一个事件类。如果某些内容已经通过open_gate函数等待,wait_at_gate中的互斥锁内的代码究竟是如何执行的。我猜它与std::condition_variable有关。

1 个答案:

答案 0 :(得分:0)

好的,因为没有人要发帖,这里是我的答案,在评论和以下链接的帮助下(引用文本来自哪个,为了便于阅读而略有修改):

http://en.cppreference.com/w/cpp/thread/condition_variablehttp://en.cppreference.com/w/cpp/thread/condition_variable/waithttp://en.cppreference.com/w/cpp/thread/condition_variable/notify_all

它假定有两个线程,一个名为OG,名为open_gate(),另一个名为WG,名为wait_at_gate()

1)这两个函数都受到锁的保护,这是一个要求&#34;任何打算等待std::condition_variable&#34;获取&#34; a std::unique_lock<std::mutex>,使用与保护共享变量相同的互斥锁&#34;。

2)如果OG首先获得锁定,那么它将在释放锁之前打开门。 WG然后锁定,门已经打开。对于这种情况,因为(来自链接参考):

while (!pred()) {
    wait(lock);
} 

然后没有等待。

3)如果WG首先获得锁定,则调用cv.wait&#34;原子地释放互斥锁并暂停执行该线程。&#34;

4)这允许OG继续,然后设置共享标志。 WG&#34;然后会在执行notify_all()时取消阻止&#34; OG