Boost logo

Boost Users :

From: Luc Bergeron (bluc_at_[hidden])
Date: 2002-10-17 14:06:57


Hello everyone,

i'm currently trying to implement a thread safe singleton using
template. In the class I need to use a boost::mutex in order to protect
access to the singleton pointer.
The problem i'm currently encountering is that I need to initialize this
static boost::mutex, but how !?!?!?!

I tried using a pointer to a mutex and initialize it to null but that
didn't work. I also tried to new it in the initialization but that
failed too. :(

Can someone help me on this one ???

Thanks in advance for any help.

Luc.

P.S. I'm using boost 1.29 :)

P.S.S Here is my current class definition : (A link to where I got this
implementation :
http://www.drizzle.com/~scottb/publish/gpgems1_singleton.htm)

template <typename T>
class ThreadSafeSingleton
{
   static T* d_ThreadSafeSingleton;
   static boost::mutex d_mutex;

public:
   ThreadSafeSingleton()
   {
      assert(!d_ThreadSafeSingleton);
      int offset = (int)(T*)1 - (int)(ThreadSafeSingleton <T>*)(T*)1;
      d_ThreadSafeSingleton = (T*)((int)this + offset);
   }
   ~ThreadSafeSingleton()
   {
      assert(d_ThreadSafeSingleton);
      d_ThreadSafeSingleton = 0;
   }

   static T& GetSingleton(void)
   {
      boost::mutex::scoped_lock scoped_lock(d_mutex);
      assert(d_ThreadSafeSingleton);
      return *d_ThreadSafeSingleton;
   }

   static T* GetSingletonPtr(void)
   {
      boost::mutex::scoped_lock scoped_lock(d_mutex);
      return d_ThreadSafeSingleton;
   }
};

template <typename T> T* ThreadSafeSingleton <T>::d_ThreadSafeSingleton = 0;


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net