|
Boost : |
From: Giovanni Piero Deretta (gpderetta_at_[hidden])
Date: 2008-01-18 14:51:15
On Jan 18, 2008 7:18 PM, Peter Dimov <pdimov_at_[hidden]> wrote:
> Martin Bonner:
>
> > This has been raised before. I normally write single-threaded code.
> > Occasionally I am forced to write a worker thread to perform a
> > particular function. That means that I need BOOST_HAS_THREADS defined.
> > On the other hand, I /know/ that most of my singletons will only be used
> > by the main thread, so why do I have to pay for synchronization on those
> > singletons?
>
> This might be a relevant objection to the specific implementation under
> discussion, but I just want to point out that you don't need to pay for
> thread-safe initialization of function-level statics, especially in a
> "Singleton" context. Illustration:
>
> X* X::instance()
> {
> static X* s_px = 0;
>
> if( X* px = atomic_load_relaxed( &s_px ) )
> {
> return px; // fast path
> }
>
> static X s_x; // "slow" thread-safe init
>
> atomic_store_release( &s_px, &s_x );
>
> return s_px;
> }
>
Don't you need a mutex in the slow path to prevent two threads that
both find s_ps null to
try initialize s_x withoug mutual exclusion? Or are you assuming C++0x
thread safe
initialization of statics? In the latter case, isn't safe to assume
that the compiler will already use a form of the above pattern anyway?
BTW, slightly off-topic, will C++0x standardize load dependent memory barriers?
According to the latest memory model paper, the then-current consensus
was not to.
gpd
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk