【C++】学习记录--condition_variable 的使用

时间:2024-03-25 19:35:25
  1. condition_variable使用步骤如下:
  2. 创建一个condition_variable对象
  3. 创建一个互斥锁mutex对象,用来保护共享资源的访问
  4. 在需要等待条件变量的地方,使用unique_lock<mutec>对象锁定互斥锁并调用condition_variable::wait()、condition_variable::wait_for()或condition_variable::wait_until()函数等条件变量
  5. 在其他线程中通知等待的线程时,调用condition_variable::notify_one()或condition_variable::notify_all()函数通知等待的线程

生产者与消费者模型

代码示例:

#include<iostream>
using namespace std;
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>

mutex g_mutex;
condition_variable g_cv;
queue<int>g_queue;

void Producer() {
	for (int i = 0; i < 10; i++)
	{
		unique_lock<mutex>lock(g_mutex);
		g_queue.push(i);
		cout << "Producer: prodeced " << i << endl;
		g_cv.notify_one();
		this_thread::sleep_for(chrono::milliseconds(100));
	}
}

void Consumer() {
	while (true)
	{
		unique_lock<mutex>lock(g_mutex);
		g_cv.wait(lock, []() {return !g_queue.empty(); });
		int value = g_queue.front();
		g_queue.pop();
		cout << "Consumer: consumed " << value << endl;
	}
}

int main()
{
	thread producer_thread(Producer);
	thread consumer_thread(Consumer);
	producer_thread.join();
	consumer_thread.join();
	system("pause");
	system("cls");
}