Boost logo

Boost :

From: Anthony Williams (anthony_w.geo_at_[hidden])
Date: 2008-05-19 18:37:44


"vicente.botet" <vicente.botet_at_[hidden]> writes:

> From: "Anthony Williams" <anthony_w.geo_at_[hidden]>
>
>> "vicente.botet" <vicente.botet_at_[hidden]> writes:
>>
>>> In the Join library I have see the following idiom
>>>
>>> mutex mtx;
>>> condition_variable cond;
>>> unsigned num_blocked;
>>>
>>> void foo() {
>>> unique_lock l(mtx);
>>> ++num_blocked;
>>> cond.wait(lock);
>>> --num_blocked;
>>>
>>> // ...
>>> }
>>>
>>> void foo() {
>>> unique_lock l(mtx);
>>> // ...
>>> if (num_blocked > 0) cond.notify_one();
>>> // ...
>>> }
>>>
>>> Does this perform better in some contexts? if yes in which ones?
>>
>> It really shouldn't do. The check is part of the notify.
>
>
> On windows notify_one is defined as:
>
> void notify_one()
> {
> if(detail::interlocked_read_acquire(&total_count))
> {
> boost::mutex::scoped_lock internal_lock(internal_mutex);
> // ...
> }
> }
>
> detail::interlocked_read_acquire do a system call.

Not with MSVC it doesn't: it's just a plain volatile read and a compiler
barrier to prevent optimizations changing the ordering. See
boost/thread/win32/interlocked_read.hpp

> This should be more
> expensive than doing a test >0, isn't it?

It could be on non-MSVC compilers.

> With pthreads notify_one is defined as
>
> inline void condition_variable::notify_one()
> {
> BOOST_VERIFY(!pthread_cond_signal(&cond));
> }
>
> Does pthread_cond_signal needs to protect its own counter from multiple
> threads? Could some one point to the pthread_cond_signal source code, or how
> to get it?

pthread_cond_signal is the POSIX condition variable notify. You can get the
source code from your favourite linux distro. The POSIX standard requires that
it is thread-safe and only notifies threads currently waiting on the cond var:
if there aren't any it does nothing.

> Note that this idiom is only applicable if the application use the same lock
> to wait and to notify, which is quite current.

In general, you don't need to hold a mutex across the notify. If you take an
extra lock in order to check the count, you're imposing unnecessary
synchronization.

Anthony

-- 
Anthony Williams            | Just Software Solutions Ltd
Custom Software Development | http://www.justsoftwaresolutions.co.uk
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk