|
Boost : |
From: williamkempf_at_[hidden]
Date: 2001-09-21 13:48:39
--- In boost_at_y..., "Alexander Terekhov" <terekhov_at_d...> wrote:
>
> > The DCL pattern is non-portable and unsafe even in C
>
> "classic" DCL pattern. however, it could be
> fixed using thread locals to be fully portable.
> e.g. version in Java:
>
> class Singleton {
> private static Singleton theInstance;
>
> private static final ThreadLocal perThreadInstance =
> new ThreadLocal() {
> // initially (per accessing thread)
> // called by ThreadLocal.get() below
> public Object initialValue() { return createInstance(); }
> };
>
> public static Singleton getInstance() {
> // 1st check w/o synchronization; inside
> // ThreadLocal.get(); it calls initialValue()
> // ONCE PER ACCESSING THREAD (with respect
> // to its instance of thread local variable
> // "perThreadInstance"
> return (Singleton)perThreadInstance.get();
> }
>
> private static synchronized Singleton createInstance() {
> // 2nd check; synchronized; guaranteed to occur
> // ONCE PER ACCESSING THREAD/SINGLETON; that solves
> // the problem of memory synchronization (w/o use
> // of explicit read/write memory barriers or
> // excessive locking) at expense of thread
> // specific data access overhead.
> if (theInstance == null)
> theInstance = new Singleton();
> return theInstance;
> }
>
> }
The above is Java not C++. The idea can be applied, but not easily.
However, there are issues, chief among them being that TLS slots are
usually quite limited. With the existence of pthread_once or
boost::call_once I honestly don't see a benefit to trying to code a
portable DCL. The only "gotcha" is in implementing boost::call_once
portably, but it can be done at the expense of optimizations today,
and can be "fixed" on specific platforms as the need arises or when
accepted into the standard.
Bill Kempf
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk