MultiThreading
 All Modules Pages
Basic functionality of condition variables - unsafe usage

Situation:

Some thread A has processed an incoming trigger and wants to inform a waiting thread B to continue with his part of the work.

Schematic solution (still incomplete)

There is a condition variable accessible from both threads (e.g. the variable may be a class attribute and the threads are working with the same class instance):

// Data definition shared by all threads
#include <condition_variable>
std::condition_variable myCondVar //<##

Thread A finishes his part of the work and informs the waiting thread B to start his action:

// Thread A
... // do some work
// Trigger thread B to proceed
myCondVar.notify_one(); //<##
// If there are multiple waiting threads
// you can also inform all of them
myCondVar.notify_all(); //<##

Thread B waits until he receives the signal to continue with processing:

// Thread B
...
// Wait indefinitely until Thread A gives allowance to proceed
myCondVar.wait(..); //<##
// now continue with processing

Attention: This is unsafe code!
The code snippets above will work in many cases and most of the time. But you may have sporadic erraneous behaviour because of the following reasons:

Because of these restrictions you cannot use the condition variable alone for proper synchronization. You always have to set and check your specific data when a decision is needed.

The condition variable is only a trigger to repeat your checks. The meaning of that trigger is: "Now it's a good time to recheck your conditions. But be prepared that they are still not fulfilled".

Keep in mind: Never use a condition variable alone!
A condition variable must always be used together with a mutex and some specific data protected by this mutex!

The next section will describe a safe way of synchronizing with the help of condition variables.