#include <stdio.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
const int length = 5;
int buffer[length];
int read_index;
int write_index;
mutex mtx;
condition_variable cond_not_full;// 指示产品缓冲区不为满
condition_variable cond_not_empty;// 指示产品缓冲区不为空
void produce(int arg) {
unique_lock<mutex> lock(mtx);
//cout << "生产者thread_id:" << this_thread::get_id() << endl;
while (((write_index + 1) % length) == read_index) {
std::cout << "篮子现在是满的,等待消费者腾出一个位置\n";
cond_not_full.wait(lock); // 生产者等待"产品库缓冲区不为满"这一条件发生.
}
buffer[write_index] = arg;
printf("生产了data:%d\n", arg);
write_index++; // 写入位置后移.
if (write_index >= length) // 写入位置若是在队列最后则重新设置为初始位置.
write_index = 0;
cond_not_empty.notify_all();// 通知消费者产品库不为空.
lock.unlock();
}
int consume() {
int arg;
unique_lock<mutex> lock(mtx);
//cout << "消费者thread_id:" << this_thread::get_id() << endl;
while (read_index == write_index) {
printf("消费者等待%d这个位置填充产品\n",read_index);
cond_not_empty.wait(lock); // 消费者等待"产品库缓冲区不为空"这一条件发生.
}
arg = buffer[read_index];
read_index++;
if (read_index >= length) // 读取位置若移到最后,则重新置位.
read_index = 0;
printf("取出了data:%d\n", arg);
cond_not_full.notify_all(); // 通知消费者产品库不为满.
lock.unlock();
return arg;
}
void producerThread(int arg) // 生产者线程
{
for (int i = 1; i <= 10; ++i) {
this_thread::sleep_for(chrono::milliseconds(2000));
produce(i);
}
}
void consumeThread(int arg) // 消费者线程
{
for (int i = 1; i <= 10; ++i) {
this_thread::sleep_for(chrono::milliseconds(1000));
consume();
}
}
int main(int argc, const char *argv[])
{
thread t1(producerThread, NULL);
thread t2(consumeThread, NULL);
t1.join();
t2.join();
return getchar();
}
c++11 多线程实现生产者消费者模型
最新推荐文章于 2022-08-29 16:35:12 发布