转自:https://www.cnblogs.com/fenghualong/p/13855360.html
1.介绍
condition_variable类似于信号量机制,实现了线程的等待和唤醒。
- wait() :阻塞等待的同时释放锁(原子操作),还可以添加阻塞判断函数,详见代码
- notify_all() : 唤醒所有阻塞等待的线程
- notify_one(): 唤醒某一个等待的线程
2.例子
锁+条件变量 实现等待唤醒。
#include <condition_variable> #include <mutex> #include <thread> std::mutex mylock; std::condition_variable condVar; bool dataReady{false}; void waitingForWork() { std::cout << "Waiting ..." << std::endl; std::unique_lock<std::mutex> l(mylock); // 加了unique_lock锁 condVar.wait(l, []{return dataReady;}); // (4) std::cout << "Running ..." << std::endl; } void setDataReady() { { std::lock_guard<std::mutex> l{mylock}; // 加了lock_guard锁 dataReady = true; } std::cout << "Data prepared, notify one" << std::endl; condVar.notify_one(); // (3) } int main(int argc, char const *argv[]) { std::cout << "==========Begin==========" << std::endl; std::thread t1(waitingForWork); // (1) std::thread t2(setDataReady); // (2) t1.join(); t2.join(); std::cout << "===========End===========" << std::endl; cout<<endl; return 0; } // 运行结果 -> % ./main ==========Begin========== Waiting ... Data prepared, notify one Running ... ===========End===========
如果不用锁和等待条件控制,可能会导致虚假唤醒和唤醒丢失问题。
3.用条件变量实现信号量
https://blog.csdn.net/qq_24447809/article/details/115906017
#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; };
标签:std,count,用法,variable,include,唤醒,condition From: https://www.cnblogs.com/BlueBlueSea/p/18288457