This is one way to implement a very simple semaphore using Boost.Thread. This is an inter-thread semaphore, not an inter-process one. No warranties are implied, etc. - I did not even compile the code. It illustrates the interaction of mutexes and variable conditions and suggests a reasonably recent version of Boost.
Note that the mutex variables and conditions are βpairedβ - threads must have a mutex lock in order to wait for the condition variable, and re-get the lock when they are woken up. In addition, code that modifies data must explicitly spill other code that can wait. This means that the mutex, the condition variable, the data, and the condition (conditions) that cause awakening are all closely related. A tight connection also means that data, a mutex, and a condition variable should be encapsulated, if possible β any external modification may violate the code in strange ways, including deadlocks, missed wakes, and other strange errors.
All this actually means an addition to the words of Vlad Lazarenko - understanding the theory and principles is at least as important as having a βworkingβ code in multi-threaded programming.
#include <boost/thread/condition_variable.hpp>
Doug
source share