条件变量实现生产者消费者模型

#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <time.h>
#include <Windows.h>
#include <condition_variable>

using namespace std;

mutex mtx;
condition_variable consume;
//定义消费工厂,生产者添加数据,消费者取走数据
vector<int> factory;
//消费者线程入口函数
void f_consumer()
{
	unique_lock<mutex> lk(mtx);
	while (true)
	{
		consume.wait(lk, []() {return factory.size() > 0; });
		cout << "线程" << GetCurrentThreadId() << "消费了:" << factory.at(factory.size() - 1) << endl;
		factory.pop_back();
		Sleep(800);
	}
	
}
//生产者线程入口函数
void f_producer()
{
	srand(time(NULL));
	while (true)
	{
		int num = rand() % 100;
		factory.push_back(num);
		cout << "生产了:" << num << endl;
		Sleep(600);
		consume.notify_all();
	}
	
}

int main()
{
	thread producer(f_producer);
	thread consumer(f_consumer);
	

	producer.join();
	consumer.join();


	system("pause");
	return 0;
}