Boost logo

Boost :

Subject: Re: [boost] [threads / signals2] Win events replace by boost signals (threadsafe)
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2015-03-25 18:26:48

On 25/03/2015 20:57, Fu ji wrote:
> I read about condition variable and it's also not the best idea, because we
> can receive signal only if we actually wait in this time. For example:

That's the purpose of the mutex. You have to lock the mutex, *then*
check for the condition which would wake you up, and only then after
this fails should you wait on the cond_var. You also have to test the
condition after you wake up, as you might be woken spuriously.

The mutex also has to protect anything that can change the true/false
state of the conditional test you're doing, before you notify. This
way, the notify thread can't miss waking up any thread that hasn't gone
to sleep yet because it won't have tested the condition yet.

> boost::unique_lock<boost::mutex> lock(CondMutex);
> bool result = cond.timed_wait(lock,
> boost::posix_time::milliseconds(1000));

This sort of thing is really unsafe, for the above reasons.

> and we have 0 as result. Probably i should write some wrapper on cond
> variable if i would like to have this functionality.

Yes, you will need to write a wrapper that has some state to protect
with the lock and that you can check when woken (eg. a bool
is_event_set). You'll also have to decide whether you're trying to
emulate auto-reset or manual-reset events, since they have different
behaviour in the woken thread.

Boost list run by bdawes at, gregod at, cpdaniel at, john at