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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ condition_variable用法

發布時間:2024/1/18 c/c++ 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ condition_variable用法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

概述

condition_variable類似于信號量機制,實現了線程的等待和喚醒。

函數接口:
wait() :阻塞等待的同時釋放鎖(原子操作),還可以添加阻塞判斷函數,詳見代碼

notify_all() : 喚醒所有阻塞等待的線程

notify_one(): 喚醒某一個等待的線程

代碼

#include<iostream> #include<thread> #include<mutex> #include<condition_variable> #include<chrono> using namespace std; mutex m; condition_variable cond; int LOOP = 10; int flag = 0;void fun(int id) {for (int i = 0; i < LOOP; i++) {unique_lock<mutex> lk(m); //加鎖//寫法1,while循環比較,多次喚醒時,只要不滿足條件就阻塞,if只判斷一次會出錯/*while (id != flag)cond.wait(lk);*///寫法2,實現原理和上面一樣 ,id != flag時會阻塞,喚醒時繼續判斷,id == flag才會喚醒成功cond.wait(lk, [=]() {return id == flag;});cout << (char)('A' + id) << " ";flag = (flag + 1) % 3;cond.notify_all();} } int main() {thread A(fun, 0);thread B(fun, 1);thread C(fun, 2);A.join();B.join();C.join();cout << endl;cout << "main end" << endl;return 0; }

測試結果:

semaphore源碼

#pragma once #include<mutex> #include<condition_variable> class semaphore { public:semaphore(long count = 0) :count(count) {}void wait() {std::unique_lock<std::mutex>lock(mx);cond.wait(lock, [&]() {return count > 0; });--count;}void signal() {std::unique_lock<std::mutex>lock(mx);++count;cond.notify_one();}private:std::mutex mx;std::condition_variable cond;long count; };

總結

以上是生活随笔為你收集整理的C++ condition_variable用法的全部內容,希望文章能夠幫你解決所遇到的問題。

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