Something went wrong. Try again.
A Tour of C++ for experienced programmers, as if C++26 is the only version that ever existed.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758// examples/ch25/ch25_prod_cons.cpp#include <iostream>#include <thread>#include <mutex>#include <condition_variable>#include <queue>#include <stop_token>
std::queue<int> 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;}