#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;
}