[thread] static mutex construction

Hello all, I've been wondering how boost::mutex plays in the static initialization game. I'm toying with a "plugin" system where plugins statically register with a singleton plugin_manager using a helper struct like this: template <typename PluginT> struct register_plugin { register_plugin () { shared_ptr<plugin_base> ptr(new PluginT); plugin_manager::instance().register(ptr); } }; static register_plugin objects, specialized for each plugin type, are constructed in an anonymous namespace to register the plugin at static initialization time, like so: namespace { register_plugin<foo_plugin> rp; } plugin_manager::instance() looks like: { static plugin_manager* s_instance; // s_mutex is a static member { boost::mutex::scoped_lock lock(s_mutex); if (s_instance == 0) { s_instance = new plugin_manager; } } return *s_instance; } So far I've implemented two plugins in this application and everything just works. It seems to me there is a static initialization race between every register_plugin object and plugin_manager::s_mutex. Am I just lucky or is there some magic about mutexes in this regard? I'm working on a Fedora 7 i386 system. -- Pedro Lamarão

Pedro Lamarão <pedro.lamarao@mndfck.org> writes:
I've been wondering how boost::mutex plays in the static initialization game.
boost::mutex has a default constructor, so is just like any other class in that regard.
I'm toying with a "plugin" system where plugins statically register with a singleton plugin_manager using a helper struct like this:
It seems to me there is a static initialization race between every register_plugin object and plugin_manager::s_mutex.
Am I just lucky or is there some magic about mutexes in this regard?
You're just lucky. A general solution which does not involve explicitly checking for initialization every time has not yet been implemented. To avoid the race, use call_once. Anthony -- Anthony Williams Just Software Solutions Ltd - http://www.justsoftwaresolutions.co.uk Registered in England, Company Number 5478976. Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL
participants (2)
-
Anthony Williams
-
Pedro Lamarão