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
then
> 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
void
      singleton_init_once()
      {
          static Singleton _theSingleton( _..._ );
          theSingleton = &_theSingleton;
      }

Singleton*
     Singleton::get_instance()
     {
          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.

regards,
alexander.


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