繁体   English   中英

了解std :: condition_variable

[英]Understanding std::condition_variable

我在这里参考已接受的答案: 使用std :: conditional_variable等待条件 ,尤其是代码(已复制):

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

好的,因为没有人要发表,这是我的答案,这取决于评论和以下链接(引用文字来自何处,对可读性进行了一些修改):

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

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

1)这两个函数都用锁保护,要求“打算在std::condition_variable上等待的任何线程”都在与保护该对象相同的互斥std::unique_lock<std::mutex>获取“ std::unique_lock<std::mutex> ”。共享变量”。

2)如果OG首先获得锁,那么它将在释放锁之前打开门。 WG随后将其锁上,门已经打开。 对于这种情况,由于(来自链接的引用):

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

那就不用等待了。

3)如果WG首先获得其锁,则其对cv.wait调用“以原子方式释放互斥并中止线程的执行”。

4)这允许OG继续,然后设置共享标志。 WG “那么将当畅通notify_all()通过执行” OG

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM