使用条件变量condition_variable 进行程序的休眠与唤醒
notify_one
notify_all
程序示例
#include <condition_variable>
#include <deque>
#include <fstream>
#include <functional>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
/*
condition_variable 条件变量的使用
notify_one一次只能激活一个等待线程
notify_all可以激活所有等待线程
*/
using namespace std;
std::deque<int> q;
std::mutex que_mutex;
std::condition_variable contion;
//线程是往队列里添加数据
void funtion_1() {
int count = 10;
while (count > 0) {
std::unique_lock<mutex> locker(que_mutex);
q.push_front(count);
locker.unlock();
//唤醒等待线程,只能激活一个线程
//与此相对应的是 notify_all,可以激活所有等待线程
//contion.notify_one();
std::this_thread::sleep_for(chrono::seconds(1));
count--;
}
}
void function_2() {
int data = 0;
while (data != 1) {
std::unique_lock<mutex> locker(que_mutex);
//解锁后等待,一个线程不会在被锁住的情况下休眠,
//wait函数会解锁互斥对象mu,并休眠,休眠后,重新加锁
//由于需要重复加锁解锁,故这里只能使用 unique_lock 不能使用lock_guard
contion.wait(locker);
//也可能被自己激活,即伪激活
//添加第二个参数 lamba函数
//contion.wait(locker, []({ return !q.empty() });
data = q.back();
q.pop_back();
locker.unlock();
std::cout << "thread 2 get a value from t1: " << data << std::endl;
}
}
void function_3() {
int data = 0;
while (data != 1) {
std::unique_lock<mutex> locker(que_mutex);
if (!q.empty()) {
data = q.back();
q.pop_back();
locker.unlock();
std::cout << "thread 2 get a value from t1: " << data << std::endl;
}
//如果使用条件变量的话,就不需要下面这些
//按照下面的写法会有很多无畏的休眠循环
else {
locker.unlock();
std::this_thread::sleep_for(chrono::seconds(10));
}
}
}
int main() {
std::thread t1(funtion_1);
std::thread t2(function_2);
t1.join();
t2.join();
return 0;
}