生产者消费者问题 C++实现

  1 // operator_system.cpp: 定义控制台应用程序的入口点。
  2 //
  3 
  4 #include "stdafx.h"
  5 #include<iostream>
  6 #include <mutex>
  7 #include <condition_variable>
  8 #include <windows.h>
  9 #include <thread>
 10 
 11 using namespace std;
 12 
 13 static const int buffer_size = 10; // 缓存大小
 14 static const int item_total = 100; //总共要生产 item_total个item
 15 
 16 // 缓存结构体, 使用循环队列当做缓存
 17 struct Buffer 
 18 {
 19     int buffer[buffer_size];
 20     size_t read_position; // 当前读位置
 21     size_t write_position; // 当前写位置
 22     mutex mtx; // 读写互斥
 23     //条件变量
 24     condition_variable not_full; 
 25     condition_variable not_empty;
 26 }buffer_res;
 27 
 28 typedef struct Buffer Buffer;
 29 
 30 void porduce_item(Buffer *b, int item)
 31 {
 32     unique_lock<mutex> lock(b->mtx);//设置互斥锁
 33 
 34     while(((b->write_position + 1) % buffer_size) == b->read_position) {
 35         //当前缓存已经满了
 36         cout << "buffer is full now, producer is wating....." << endl;
 37         (b->not_full).wait(lock); // 等待缓存非full
 38     }
 39     // 向缓存中添加item
 40     (b->buffer)[b->write_position] = item;
 41     (b->write_position)++;
 42 
 43     // 若到达最后一个, 写位置置位0
 44     if (b->write_position == buffer_size)
 45         b->write_position = 0;
 46 
 47     (b->not_empty).notify_all();
 48     lock.unlock();
 49 }
 50 
 51 int consume_item(Buffer *b)
 52 {
 53     int data;
 54     unique_lock <mutex> lock(b->mtx);
 55     while (b->write_position == b->read_position)
 56     {   // 当前buffer 为空
 57         cout << "buffer is empty , consumer is waiting....." << endl;
 58         (b->not_empty).wait(lock);
 59     }
 60 
 61     data = (b->buffer)[b->read_position];
 62     (b->read_position)++;
 63 
 64     if (b->read_position >= buffer_size)
 65         b->read_position = 0;
 66 
 67     (b->not_full).notify_all();
 68     lock.unlock();
 69 
 70     return data;
 71 }
 72 
 73 //生产者任务
 74 void producer() {
 75     for (int i = 1; i<= item_total;i++) {
 76         cout << "prodece the " << i << "^th item ..." << endl;
 77         porduce_item(&buffer_res, i);
 78     }
 79 }
 80 
 81 //消费者任务
 82 void consumer()
 83 {
 84     static int cnt = 0;
 85     while(1) {
 86         Sleep(1);
 87         int item = consume_item(&buffer_res);
 88         cout << "consume the " << item << "^th item" << endl;
 89         if (++cnt == item_total)
 90             break;
 91     }
 92 }
 93 
 94 //初始化 buffer
 95 void init_buffer(Buffer *b)
 96 {
 97     b->write_position = 0;
 98     b->read_position = 0;
 99 }
100 
101 int main()
102 {
103     init_buffer(&buffer_res);
104     thread prodece(producer);
105     thread consume(consumer);
106     prodece.join();
107     consume.join();
108     getchar();
109 }

 

posted on 2020-09-26 21:08  回形针的迷宫  阅读(399)  评论(0编辑  收藏  举报

导航