waiting thread until a condition has been occurred

You need conditional variables.

If your compiler supports std::conditional introduced by C++11, then you can see this for detail:

  • std::condition_variable (C++11 threads)

If your compiler doesn’t support it, and you work with win32 threads, then see this:

  • Condition Variables (Win32 threads)

And here is a complete example.

And if you work with POSIX threads, then see this:

  • Condition Variables (POSIX threads)

You can see my implementation of conditional_variable using win32 primitives here:

  • Implementation of concurrent blocking queue for producer-consumer

Scroll down and see it’s implementation first, then see the usage in the concurrent queue implementation.

A typical usage of conditional variable is this:

//lock the mutex first!
scoped_lock myLock(myMutex); 

//wait till a condition is met
myConditionalVariable.wait(myLock, CheckCondition);

//Execute this code only if the condition is met

whereCheckCondition is a function (or functor) which checks the condition. It is called by wait() function internally when it spuriously wakes up and if the condition has not met yet, the wait() function sleeps again. Before going to sleep, wait() releases the mutex, atomically.

Leave a Comment