#include<iostream>#include<thread>#include<mutex>#include<condition_variable>#include<chrono>#include<queue>#include<atomic>
std::queue<int> buffer_;
std::mutex mutex_;
std::condition_variable cv_;
std::atomic_bool stop_(false);voidproducer(){for(int i =0; i <10; i++){{
std::lock_guard<std::mutex>lk(mutex_);
buffer_.push(i);}
std::cout <<"producer produce number "<< i << std::endl;
cv_.notify_one();// sleep 100ms
std::this_thread::sleep_for(std::chrono::milliseconds(100));}}voidconsumer(int index){while(!stop_.load()){
std::unique_lock<std::mutex>lk(mutex_);
cv_.wait(lk);if(!buffer_.empty()){int tmp = buffer_.front();
buffer_.pop();
std::cout <<"consumer #"<< index <<" consume number "<< tmp << std::endl;}}}intmain(){
std::thread p1(producer);
std::thread c1(consumer,1);
std::thread c2(consumer,2);
p1.join();
stop_.store(true);// 消费者线程退出
cv_.notify_all();// 唤醒所有消费者线程,退出cv_阻塞
c1.join();
c2.join();return0;}
输出结果
xufengbao@MacBook-Pro study % g++ test.cpp -std=c++11
xufengbao@MacBook-Pro study % ./a.out
producer produce number 0
consumer #1 consume number 0
producer produce number 1
consumer #2 consume number 1
producer produce number 2
consumer #1 consume number 2
producer produce number 3
consumer #2 consume number 3
producer produce number 4
consumer #1 consume number 4
producer produce number 5
consumer #2 consume number 5
producer produce number 6
consumer #1 consume number 6
producer produce number 7
consumer #2 consume number 7
producer produce number 8
consumer #1 consume number 8
producer produce number 9
consumer #2 consume number 9