// examples/ch25/ch25_prod_cons.cpp #include #include #include #include #include #include std::queue q; std::mutex m; // Return the shared condition variable as a function-local static. // Function-local statics are initialized on first use, so the // condition variable never participates in dynamic initialization. std::condition_variable_any& cv() { static std::condition_variable_any c; return c; } void producer(std::stop_token st) { int value = 0; while (!st.stop_requested()) { { std::scoped_lock lock(m); q.push(value++); } cv().notify_one(); std::this_thread::sleep_for(std::chrono::milliseconds(5)); } // notify consumer to finish cv().notify_one(); } void consumer(std::stop_token st) { while (true) { std::unique_lock lock(m); cv().wait(lock, [&]{ return !q.empty() || st.stop_requested(); }); if (st.stop_requested() && q.empty()) break; int v = q.front(); q.pop(); lock.unlock(); std::cout << "got " << v << std::endl; if (v >= 9) { // have enough, request stop via external means // In this demo, we just continue; main will request stop. } } std::cout << "consumer exit" << std::endl; } int main() { std::jthread prod(producer); std::jthread cons(consumer); std::this_thread::sleep_for(std::chrono::milliseconds(100)); prod.request_stop(); cons.request_stop(); return 0; }