Using c++ 11 to achieve producer and consumer model ,its simpler than i thought!
The heart of the model is add data to the buffer area and get the data out from the buffer area(缓冲区)!And the two steps is objectively synchronous (同步)by using two thread!
I use the queue library to simulate(模拟) the buffer area ,because of the FIFO function of the queue!When the queue is empty,the consumer will add data to the queue,of course ,now the queue must been protected with the mutex,the program which i write use unique_lockto achieve.The key word’s function is make the sharing variable be used by only one thread,only use the one sentence will achieve the goal,of cource the same function key word we can find is lock_guard,use the two keyword can achieve same function,as far as the difference of the two key words i have not explore because i’m too busy these days,so i don’t know!But I 'm sure i will spare my time to find in the days comming!Oh,let’s turn back! the mutex set Ok!Then the producer thread run to add data to the queue!,of course the consumer’s static is wait util he receive the signal from the producer!while add data finished ,the produce thread send to the consumer thread a signal which remind he that the products has been make OK !then the consumer thread start runnig to read the data and pop the queue data which he has read,of couse ,you must add use unique_lockto protecting the queue!after finish reading !The consumer sends the signal to producer and drives him to produce!OK ! the model has been described finished !then let’s read the source core which I have write~~~
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<queue>
using namespace std;
queue<int>products;
mutex m ;
condition_variable cond ;
bool notify = false ;
bool done = false ;
void producer();
void consumer(){
while(!done){
//protect the sharing variable,only invoking once can
//achieve lock and unlock ,
//the same function key word in c++ is lock_guard
unique_lock<mutex>lk(m);
//wait the producer's notify
while(!notify){
cond.wait(lk) ;
}
//while the data queue is not empty
//the consumer will read the data after get the notify
if(!products.empty()){
cout<<"consumer..."<<products.front()<<endl ;
products.pop();
//after read finished ,notify been set false until the
//producer thread make the nityfy true,
//the consumer can read again
notify = false ;
cond.notify_one();
}
}
}
void producer(){
int i ;
for(i = 0 ;i<10 ;i++){
//主动让出cpu,不参与cpu 的本次调度,让其他线程使用,等一秒后在参与调度
this_thread ::sleep_for(chrono::seconds(1));
unique_lock<mutex>lk(m);
cout<<"product..."<<i<<endl ;
products.push(i);
notify = true ;
//notify the consumer
cond.notify_one();
}
done = true ;
cond.notify_one();
}
int main(){
thread t1(producer);
thread t2(consumer);
t1.join();
t2.join();
}
The article use many grammers in the c++11 ,many function been achieved only by use many class’s ways!But the buttom of the function’s achieve is very worth to analysis!