c++11版生产者-消费者

来源:互联网 发布:php throw exception 编辑:程序博客网 时间:2024/06/08 18:35
#include <iostream>#include <thread>#include <mutex>#include <condition_variable>#include <vector>#include <string>#include <cstring>#include <chrono>using namespace std;using namespace std::chrono;class store_buff{public:store_buff(void){cout<<"constructor!"<<endl;size=10;pos=0;vec.reserve(size);}~store_buff(void){cout<<"deconstructor!"<<endl;}public:vector<string> vec;int size;int pos;mutex buff_mutex;condition_variable buff_not_full;condition_variable buff_not_empty;};store_buff buff;char num[10]; //store string converted by numvoid producer(void){while(true){this_thread::sleep_for(milliseconds(300));unique_lock<mutex> guard(buff.buff_mutex);if(buff.pos==buff.size){buff.buff_not_full.wait(guard,[](){return buff.pos!=buff.size;});}memset(num,'\0',10);sprintf(num,"%d",buff.pos);printf("produce: %s\n",num);buff.vec.push_back(num);++buff.pos;if(buff.pos==1) //just now consumer maybe block for buff{buff.buff_not_empty.notify_one();}}}void consumer(void){while(true){this_thread::sleep_for(milliseconds(500));unique_lock<mutex> guard(buff.buff_mutex);if(buff.pos==0){buff.buff_not_empty.wait(guard,[](){return buff.pos!=0;});}printf("consumer: %s\n",buff.vec.back().c_str());buff.vec.pop_back();--buff.pos;if(buff.pos==9){buff.buff_not_full.notify_one();}}}int main(int argc,char* argv[]){thread consumer_thread(consumer);thread producer_thread(producer);consumer_thread.join();producer_thread.join();return 0;}