I wrote a timer which works in the following way:
a class using the timer implements a callback function call_()
.
The timer runs in a separate thread and executes call_()
when the timer expires.
My test program is as follows:
void TestCase::loop()
{
unique_lock<mutex> lock(*this);
while(running_)
{
timer_->SetTimer(time);
signal_.wait(lock);
do_something();
}
}
void TestCase::call_()
{
signal_.notify_all();
}
If time
is very small (e.g. 2ms) the test program sometimes executes do_something()
, sometimes not (in different runs of the test program).
My guess is a race condition, it seems that if time
is small call()_
is executed (and thus signal_.notify_all()
) before signal_.wait(lock)
.
If I add this_thread::sleep(posix_time::milliseconds(2))
before signal_.notify_all()
,
do_something()
is executed in almost every run and for sleep(5)
everything works fine.
How can I assure that signal_.wait(lock)
is executed before signal_.notify_all()
?