日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

标准化条件变量 -- condition_variable

發布時間:2024/4/18 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 标准化条件变量 -- condition_variable 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

std::condition_variable是條件變。Linux下使用 Pthread庫中的 pthread_cond_*()?函數提供了與條件變量相關的功能。和pthread_cond_*()一樣,我們可以使用條件變量(condition_variable)實現多個線程間的同步操作;當條件不滿足時,相關線程被一直阻塞,直到某種條件出現,這些線程才會被喚醒。C++11通過std::condition_variable,對于條件變量進行了統一化,標準化。

condition_variable 的用法很簡單,這里就不一一介紹了。關鍵用法如下圖所示:

我們來看看官方的解釋:

condition_variable 類是同步原語,能用于阻塞一個線程,或同時阻塞多個線程,直至另一線程修改共享變量(條件)并通知 condition_variable 。

有意修改變量的線程必須:

  • 獲得?std::mutex?(常通過?std::lock_guard?)

  • 在保有鎖時進行修改

  • 在?std::condition_variable?上執行?notify_one?或?notify_all?(不需要為通知保有鎖)

  • 即使共享變量是原子的,也必須在互斥下修改它,以正確地發布修改到等待的線程。

    任何有意在 std::condition_variable 上等待的線程必須:

  • 在與用于保護共享變量者相同的互斥上獲得?std::unique_lock<std::mutex>

  • 執行下列之一:

  • 檢查條件,是否為已更新或提醒它的情況

  • 執行 wait 、 wait_for 或 wait_until ,等待操作自動釋放互斥,并懸掛線程的執行。

  • condition_variable 被通知時,時限消失或虛假喚醒發生,線程被喚醒,且自動重新獲得互斥。之后線程應檢查條件,若喚醒是虛假的,則繼續等待。

      • 或者

    • 使用?wait?、?wait_for?及?wait_until?的有謂詞重載,它們包攬以上三個步驟

    std::condition_variable 只可與 std::unique_lock<std::mutex>?一同使用;此限制在一些平臺上允許最大效率。std::condition_variable_any 提供可與任何基本可鎖定?(BasicLockable)?對象,例如 std::shared_lock 一同使用的條件變量。

    condition_variable容許:

    ?wait 、 wait_for 、 wait_until 、 notify_one 及 notify_all 成員函數的同時調用。

    類 std::condition_variable 是標準布局類型?(StandardLayoutType)?。它非可復制構造?(CopyConstructible)?、可移動構造?(MoveConstructible)?、可復制賦值?(CopyAssignable)?或可移動賦值?(MoveAssignable)?。

    下面看一下官網的例子:

    #include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variablestd::mutex mtx; std::condition_variable cv; bool ready = false;void print_id (int id) {std::unique_lock<std::mutex> lck(mtx);while (!ready) cv.wait(lck);// ...std::cout << "thread " << id << '\n'; }void go() {std::unique_lock<std::mutex> lck(mtx);ready = true;cv.notify_all(); }int main () {std::thread threads[10];// spawn 10 threads:for (int i=0; i<10; ++i)threads[i] = std::thread(print_id,i);std::cout << "10 threads ready to race...\n";go(); // go!for (auto& th : threads) th.join();return 0; } Output:10 threads ready to race...thread 2thread 0thread 9thread 4thread 6thread 8thread 7thread 5thread 3thread 1

    總結

    以上是生活随笔為你收集整理的标准化条件变量 -- condition_variable的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。