|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2008-01-18 13:18:35
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;
}
A sufficiently good compiler will fold this code into "static X s_x" so you
won't need to do anything.
The reason this works (except on Alpha) is that the accesses through the
returned pointer are data-dependent and carry implicit acquire semantics.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk