c++11 多线程实现生产者消费者模型

#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();
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值