Boost logo

Boost :

From: Alexander Terekhov (terekhov_at_[hidden])
Date: 2001-09-18 13:38:02


> 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;
    }

  }

regards,
alexander.


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