Boost logo

Boost :

From: Alexander Terekhov (terekhov_at_[hidden])
Date: 2001-09-25 13:24:15

> static boost::once_flag m_once = boost::once_init;
> static boost::mutex * pm = 0;
> void m_init()
> {
> pm = new boost::mutex;
> }
> X & X::get()
> {
> boost::call_once(&m_once, m_init);
> boost::mutex::scoped_lock lock(*pm);
> static X x;
> return x;
> }
> I still don't like it. Such a common pattern shouldn't be that hard. Some
> day C++ may guarantee that a function local static is thread safe; but
> again, it might not, and besides, we need a stop gap solution in the
> meantime.

how about something along the lines of:

static Singleton* theSingleton;
static pthread_once_t singleton_init_once_control = PTHREAD_ONCE_INIT;

          static Singleton _theSingleton( _..._ );
          theSingleton = &_theSingleton;

          pthread_once( &singleton_init_once_control,singleton_init_once );
          return theSingleton;

well, it is not formally guaranteed to be C++ exception
safe but since posix does require pthread_once to be
thread cancellation safe it is most likely to work
correctly with C++ exception as well.. (on decent
C++_with_posix_threads implementations :)

34939 The pthread_once() function is not a cancelation point.
      However, if init_routine is a cancelation
34940 point and is canceled, the effect on once_control shall
      be as if pthread_once() was never called.


Boost list run by bdawes at, gregod at, cpdaniel at, john at