I'm writing a service in C++, and I have some threads that needs to sleep for given amount of time.
So far so good, boost::this_thread::sleep_for
works, but I now need some interruption (for example, stopping signal). Boost has no cancellation_token
, and so far I have something like following:
boost::mutex _waiting_mutex;
boost::condition_variable _waiting_cv;
void wait(const boost::chrono::duration& timeout)
{
boost::unique_lock<boost::mutex> lk(_waiting_mutex);
_waiting_cv.wait_for(lk, timeout);
}
void signal_termination()
{
_waiting_cv.notify_all();
}
This works nicely for one thread (that sleeps for 5 seconds, or until signal_termination()
is called), but not for multiple ones - the first thread sleeps nicely, but the second waits for first thread to leave the lock, and then sleeps.
How to overcome this unique_lock? Should I introduce semaphore with maximum number of threads?
In C#, I'd use ManualResetEvent
.