簡體   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