#include <unistd.h>
#include <cstdlib>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <queue>
#include <time.h>
#include <atomic>
#include <stdlib.h>
using namespace std;
// 定义初始数据
static atomic<int> initNum_ = 0;
// 定义最多生成多少数据
static const int maxNum_ = 128;
// 用来设置缓存队列的最多item
static const int maxSize_ = 8;
// 使用queue 来做数据生成的缓存
queue<int> cacheQueue_;
// 定义访问缓存队列的互斥锁
mutex queueMtx_;
// 定义两个条件变量
condition_variable notEmpty_;
condition_variable notFull_;
// 定义是否退出模式 true 的时候准备要退出了
atomic<bool> readyExit_ = false;
void producer()
{ // 生产者线程
cout << "create producer tid [ " << this_thread::get_id() << " ]!" << endl;
srand((unsigned)time(NULL));
while (true)
{
{
unique_lock<mutex> locker(queueMtx_);
if (initNum_ != maxNum_)
{ // 还没生产到给点数量的数据
// 还没生产完
if (cacheQueue_.size() < maxSize_)
{
// 缓存也还没满 这个时候生产数据
int item = rand() % 100;
cacheQueue_.push(item);
cout << "tid [ " << this_thread::get_id() << " ] produce " << item << " !" << endl;
++initNum_;
notEmpty_.notify_all(); // 唤醒等待的消费者线程
if (initNum_ != maxNum_ && cacheQueue_.size() < maxSize_)
{
// 缓存还没有满 通知别的生产者线程 可以起来继续生产了
notFull_.notify_all();
}
}
else
{
// 缓存已经满了 等待消费者线程消费后唤醒
notFull_.wait(locker);
}
}
else
{
// 生产给定数量的数据 要退出线程了
readyExit_ = true;
cout << "producer tid [ " << this_thread::get_id() << " ] over!" << endl;
notFull_.notify_all(); // 通知生产者线程该退出了
notEmpty_.notify_all(); // 不加这行 会造成消费者线程概率死锁 他会唤醒别的线程
break;
}
}
sleep(0.03);
}
}
void consumer()
{
cout << "create consumer tid [ " << this_thread::get_id() << " ]!" << endl;
while (true)
{ // 消费者线程
{
unique_lock<mutex> locker(queueMtx_);
if (cacheQueue_.empty())
{
// 如果缓存数据没有了
if (readyExit_)
{
// 数据已经不生成了 准备退出了
cout << "consumer tid [ " << this_thread::get_id() << " ] over!" << endl;
// 如果生产者线程没有了 那么我还要通知我的其他消费者线程 该退出了
notEmpty_.notify_all();
break;
}
else
{
// 还没结束 等待生产者生产数据 进行消费
notEmpty_.wait(locker);
}
}
else
{
int item = cacheQueue_.front();
cacheQueue_.pop();
cout << "tid [ " << this_thread::get_id() << " ] consume " << item << " !" << endl;
// 消费了数据 要告诉生产者 缓存不为空了
notFull_.notify_all();
if (!cacheQueue_.empty())
{
// 通知别的消费者进行消费
notEmpty_.notify_all();
}
}
}
sleep(0.05);
}
}
int main()
{
thread t1(producer);
thread t2(producer);
// thread t3(producer);
// thread t4(producer);
thread t5(consumer);
thread t6(consumer);
// thread t7(consumer);
// thread t8(consumer);
t1.join();
t2.join();
// t3.join();
// t4.join();
t5.join();
t6.join();
// t7.join();
// t8.join();
// t5.join();
// t6.join();
}
c++ 多生产者 多消费者实现
最新推荐文章于 2024-06-09 20:18:37 发布