std::condition_variable(二)
#include <iostream> // std::cout #include <thread> // std::thread, std::this_thread::yield #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variable std::mutex mtx; std::condition_variable cv; //通过cargo来判断有没有被消费 int cargo = 0; bool shipment_available() { return cargo != 0; } // 消费者线程. void consume(int n) { for (int i = 0; i < n; ++i) { std::unique_lock <std::mutex> lck(mtx); cv.wait(lck, shipment_available);//第二个参数不知干什么的 std::cout << cargo << '\n'; cargo = 0; } } int main() { std::thread consumer_thread(consume, 10); // 消费者线程. // 主线程为生产者线程, 生产 10 个物品. for (int i = 0; i < 10; ++i) {
/*当consumer_thread时就有两条线,主和工作者线程,shipment_available正好可以判断子线程是否取走商品*/
while (shipment_available()) std::this_thread::yield();//估计类似sleep() std::unique_lock <std::mutex> lck(mtx); cargo = i + 1; cv.notify_one();//cargo有值通知阻塞的的线程运行 } consumer_thread.join(); getchar(); return 0; }
具体看http://www.cnblogs.com/haippy/p/3252041.html