Sending notifications between threads
Mutexes are synchronization primitives that can be used to protect access to shared data. However, the standard library provides a synchronization primitive called a condition variable that enables a thread to signal to others that a certain condition has occurred. The thread or the threads that are waiting on the condition variable are blocked until the condition variable is signaled or until a timeout or a spurious wakeup occurs. In this recipe, we will see how to use condition variables to send notifications between thread-producing data and thread-consuming data.
Getting ready
For this recipe, you need to be familiar with threads, mutexes, and locks. Condition variables are available in the std
namespace in the <condition_variable>
 header.Â
How to do it...
Use the following pattern for synchronizing threads with notifications on condition variables:
- Define a condition variable (in the appropriate context):
std::condition_variable cv;
- Define...