title: c++: is this getInstance() method of my singleton threadsafe?
body: <p>I am currently trying to write a threadsafe singleton (at least in terms of construction and destruction) using boost::mutex. I read that boost mutex can't be initialized statically(I lost the link where I read it, sorry) so to work around that I tried this, if threadsafety for construction and destruction is:</p>
  
  <pre><code>                static T&amp; getInstance()
              {
  #ifndef STATIC_VARIABLES_ARE_THREADSAFE
                  boost::mutex mutex; 
                  boost::lock_guard lock(mutex);
  #endif
                  static T instance;
                  return instance;
              }
  </code></pre>
  
  <p>is that threadsafe, or should I use boost::call_once? Will boost once give me any performance benefit over this approach?</p>
  
  <p><strong>EDIT:</strong>
  Okay, my first idea was obviously not correct. To clearify the question. Can a boost::mutex safely be initialized statically? Like this:</p>
  
  <pre><code>class Singleton
  {
  private:
  static boost::mutex m_mutex;
  
  public:
  static Singleton &amp; getInstance()
  {
      boost::lock_guard lock(m_mutex);
      static T instance;
      return instance;
  }
  
  };
  </code></pre>
  
  <p>Is that a working approach or is it in fact not safe to init boost::mutex statically (which is what I read)?</p>
  
  <p><strong>EDIT2</strong>:
  Ah, that was the link by the way <a href="http://uint32t.blogspot.com/2007/12/you-lazy-bastard-part-1.html" rel="nofollow">http://uint32t.blogspot.com/2007/12/you-lazy-bastard-part-1.html</a></p>