C++简单的单生产者单消费者模式

一、前言

         本例展示简单的单生产者单消费者模式,一个生产进程,另一个进程消费,当缓冲区满时,不能往缓冲区放数据,当缓冲区空时,不能从缓冲区取数据。

二、代码

#include<condition_variable>  
#include<mutex>  
#include<thread>  
#include<iostream>  
#include<queue>  
#include<chrono>  
 
#include <unistd.h>

static int i = 1;

int main(){  
    std::queue<int>products;          //产品队列  
  
    std::mutex m;  
    std::condition_variable cond_var; //条件变量  
    bool notifid = false;             //通知标志  

    bool done = false;                //消费者进程结束标志  
  
    std::thread producter( [&](){     //捕获互斥锁  
  
        while(1){
		    sleep(1);
            std::unique_lock<std::mutex>lock(m);        //创建互斥量 保证下列操作不被打断 
		    if(products.size() < 3){	
				std::cout<<"producting "<<i<<std::endl;  
				products.push(i);  
				notifid = true;
                ++i;				
				cond_var.notify_one();   
            }else{               			//通知另一线程  
                notifid = true;
				cond_var.notify_one();
			}
        }  


        if(1) done = true;                      //生产结束  
        cond_var.notify_one();  
    });  
  
  
    std::thread consumer( [&](){  
        while(!done){  
            std::unique_lock<std::mutex>lock(m);  
            while(!notifid){  
                cond_var.wait(lock);             //通过调用 互斥量 来等待 条件变量  
            }  
            while(!products.empty()){  
                std::cout<<"consumer "<<products.front()<<std::endl;  
                products.pop();  
            }  
            notifid = false;  
        }  
    });  


    producter.join();  
    consumer.join();  
    return 0;  
}  

三、编译

sudo g++ -Wl,--no-as-needed -std=c++11 -pthread producer.cpp -o producer




猜你喜欢

转载自blog.csdn.net/AP1005834/article/details/79555760