| 14 | #include <chrono> |
| 15 | |
| 16 | int main() |
| 17 | { |
| 18 | // 生产者数量 |
| 19 | std::queue<int> produced_nums; |
| 20 | // 互斥锁 |
| 21 | std::mutex m; |
| 22 | // 条件变量 |
| 23 | std::condition_variable cond_var; |
| 24 | // 结束标志 |
| 25 | bool done = false; |
| 26 | // 通知标志 |
| 27 | bool notified = false; |
| 28 | |
| 29 | // 生产者线程 |
| 30 | std::thread producer([&]() { |
| 31 | for (int i = 0; i < 5; ++i) { |
| 32 | std::this_thread::sleep_for(std::chrono::seconds(1)); |
| 33 | // 创建互斥锁 |
| 34 | std::unique_lock<std::mutex> lock(m); |
| 35 | std::cout << "producing " << i << '\n'; |
| 36 | produced_nums.push(i); |
| 37 | notified = true; |
| 38 | // 通知一个线程 |
| 39 | cond_var.notify_one(); |
| 40 | } |
| 41 | done = true; |
| 42 | cond_var.notify_one(); |
| 43 | }); |
| 44 | // 消费者线程 |
| 45 | std::thread consumer([&]() { |
| 46 | std::unique_lock<std::mutex> lock(m); |
| 47 | while (!done) { |
| 48 | while (!notified) { // 循环避免虚假唤醒 |
| 49 | cond_var.wait(lock); |
| 50 | } |
| 51 | while (!produced_nums.empty()) { |
| 52 | std::cout << "consuming " << produced_nums.front() << '\n'; |
| 53 | produced_nums.pop(); |
| 54 | } |
| 55 | notified = false; |
| 56 | } |
| 57 | }); |
| 58 | |
| 59 | producer.join(); |
| 60 | consumer.join(); |
| 61 | } |
nothing calls this directly
no outgoing calls
no test coverage detected