std::condition_variable(3)复习
#include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variable std::mutex mtx; std::condition_variable cv; int cargo = 0; // shared value by producers and consumers void consumer() { std::unique_lock < std::mutex > lck(mtx); while (cargo == 0) cv.wait(lck); std::cout << cargo << '\n'; cargo = 0; } void producer(int id) { std::unique_lock < std::mutex > lck(mtx); cargo = id; cv.notify_one();//如果存在多个等待唤醒的线程则唤醒的线程时不确定的 } int main() { std::thread consumers[10], producers[10]; //多个生产者,多个消费者,只要加锁还是安全的 // spawn 10 consumers and 10 producers: for (int i = 0; i < 10; ++i) { consumers[i] = std::thread(consumer);//消费者线程 producers[i] = std::thread(producer, i + 1);//生产者线程 } // join them back: for (int i = 0; i < 10; ++i) { producers[i].join(); consumers[i].join(); } getchar(); return 0; }
通常std::condition_variable使用std::unique_lock锁住线程,如果使用其的可以用std::condition_variable_any