c++11实现生产者、消费者
用互斥和条件变量实现:
1 #include <iostream> 2 #include <thread> 3 #include <mutex> 4 #include <queue> 5 #include <condition_variable> 6 7 using namespace std; 8 9 10 mutex mtx; 11 condition_variable produce,consume; 12 13 queue<int> que; 14 const int maxSize = 5; 15 16 void consumer() 17 { 18 while (true) 19 { 20 this_thread::sleep_for(chrono::milliseconds(1000)); 21 unique_lock<mutex> lck(mtx); 22 consume.wait(lck, []() { 23 return que.size() !=0; 24 }); 25 cout << "consumer" << this_thread::get_id() << ":"; 26 que.pop(); 27 cout << que.size() << endl; 28 29 produce.notify_all(); 30 } 31 } 32 33 void producer(int id) 34 { 35 while (true) 36 { 37 this_thread::sleep_for(chrono::milliseconds(800));//速度比消费者快一点 38 unique_lock<mutex> lck(mtx); 39 produce.wait(lck, []() { 40 return que.size() != maxSize; 41 }); 42 cout << "producer" << this_thread::get_id() << ":"; 43 que.push(id); 44 cout << que.size() << endl; 45 consume.notify_all(); 46 } 47 } 48 49 int main() 50 { 51 thread consumers[2], producers[2]; 52 53 for (int i = 0; i < 2; ++i) 54 { 55 consumers[i] = thread(consumer); 56 producers[i] = thread(producer, i + 1); 57 } 58 59 for (int i = 0; i < 2; ++i) 60 { 61 consumers[i].join(); 62 producers[i].join(); 63 } 64 }
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号