Use std::condition_variable to resolve the producer-consumer problem
The simplest version of the producer-consumer problem is where you have one process that produces data and another that consumes data, using one buffer or container to hold the data. This requires coordination between the producer and consumer to manage the buffer and prevent unwanted side effects.
How to do it…
In this recipe, we consider a simple solution to the producer-consumer problem using std::condition_variable
to coordinate the processes:
- We begin with some namespace and alias declarations for convenience:
using namespace std::chrono_literals; namespace this_thread = std::this_thread; using guard_t = std::lock_guard<std::mutex>; using lock_t = std::unique_lock<std::mutex>;
The lock_guard
and unique_lock
aliases make it easier to use these types without error.
- We use a couple of constants:
constexpr size_t num_items{ 10 }; constexpr auto delay_time{ 200ms };
...