2个线程实现生产者消费者
作者:
贺谦
,
2021-09-07 12:47:36
,
所有人可见
,
阅读 485
notify_all()
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
condition_variable produceCV, consumeCV;
queue<int> q;
int maxv = 10;
void producer(int id)
{
while (true)
{
this_thread::sleep_for(chrono::milliseconds(100));
unique_lock<mutex> ul(mtx);
produceCV.wait(ul, []{
return q.size() != maxv;
});
cout << "producer produce: ";
q.push(id);
cout << q.size() << endl;
consumeCV.notify_all();
}
}
void consumer()
{
while (true)
{
this_thread::sleep_for(chrono::milliseconds(200));
unique_lock<mutex> ul(mtx);
consumeCV.wait(ul, []{
return q.size() != 0;
});
cout << "consumer consume: ";
q.pop();
cout << q.size() << endl;
produceCV.notify_all();
}
}
int main()
{
thread cnsr;
thread prdr;
cnsr = thread(consumer);
prdr = thread(producer, 1);
cnsr.join();
prdr.join();
return 0;
}
notify_one()
#include <iostream>
#include <thread>
#include <mutex>
#include <queue>
using namespace std;
mutex mtx;
condition_variable produceCV, consumeCV;
queue<int> q;
int maxv = 10;
void producer(int id)
{
while (true)
{
this_thread::sleep_for(chrono::milliseconds(100));
unique_lock<mutex> ul(mtx);
produceCV.wait(ul, []{
return q.size() != maxv;
});
cout << "producer produce: ";
q.push(id);
cout << q.size() << endl;
consumeCV.notify_one();
}
}
void consumer()
{
while (true)
{
this_thread::sleep_for(chrono::milliseconds(200));
unique_lock<mutex> ul(mtx);
consumeCV.wait(ul, []{
return q.size() != 0;
});
cout << "consumer consume: ";
q.pop();
cout << q.size() << endl;
produceCV.notify_one();
}
}
int main()
{
thread prdr = thread(producer, 9);
thread cnsr = thread(consumer);
prdr.join();
cnsr.join();
return 0;
}