On 19/04/12 07:42, Serge Skorokhodov wrote:
Say, I need a threadsafe static factory method. It may be implemented in two ways:
1. class F { ... public: static PTR_TO_SOMETHING* create_something() { static boost::mutex m; boost::scope_lock(m); .... retrunt something_created; } };
2. H-file: class F { private: static boost::mutex m_; ... public: static PTR_TO_SOMETHING* create_something(); }; CPP-file: boost::mutex F:m_;
PTR_TO_SOMETHING* F::create_something() { boost::scope_lock(m_); .... retrunt something_created; }
create_something is to be called from different threads but after main is entered. Are both of the above implementation threadsafe?
That depends on your compiler. In case 1, the mutex is constructed when "create_something" is first called. With gcc there is a command-line option (-fthreadsafe-statics) which ensures that this is done in a thread-safe manner, so you don't have 2 threads thinking they are "first". On many builds this is enabled by default, but the user can still disable it. I don't think MSVC has thread-safe statics before VC11, but I'm not sure. I don't know about other compilers. In case 2, if you call create_something() after main() has started then it should be fine, as the class static will be fully constructed before main. Anthony -- Author of C++ Concurrency in Action http://www.stdthread.co.uk/book/ just::thread C++11 thread library http://www.stdthread.co.uk Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk 15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976