//
// 7.2.cpp
// c++1x tutorial
//
// created by changkun at changkun.de
//
// ç产è
æ¶è´¹è
模å
#include
#include
#include
#include
#include
#include
int main()
{
// ç产è
æ°é
std::queue produced_nums;
// äºæ¥é
std::mutex m;
// æ¡ä»¶åé
std::condition_variable cond_var;
// ç»ææ å¿
bool done = false;
// éç¥æ å¿
bool notified = false;
// ç产è
线ç¨
std::thread producer([&]() {
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
// åå»ºäºæ¥é
std::unique_lock<:mutex> lock(m);
std::cout << "producing " << i << '\n';
produced_nums.push(i);
notified = true;
// éç¥ä¸ä¸ªçº¿ç¨
cond_var.notify_one();
}
done = true;
notified = true;
cond_var.notify_one();
});
// æ¶è´¹è
线ç¨
std::thread consumer([&]() {
std::unique_lock<:mutex> lock(m);
while (!done) {
while (!notified) { // 循ç¯é¿å
èåå¤é
cond_var.wait(lock);
}
while (!produced_nums.empty()) {
std::cout << "consuming " << produced_nums.front() << '\n';
produced_nums.pop();
}
notified = false;
}
});
producer.join();
consumer.join();
}