Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this way of creating static instance thread safe?

I have the following sample C++ code:

class Factory
{
public:
    static Factory& createInstance()
    {
        static Factory fac;
        return fac;
    }

private:
    Factory() 
    {
        //Does something non-trivial
    }
};

Let's assume that createInstance is called by two threads at the same time. So will the resulting object be created properly? What happens if the second thread enters the createInstance call when the first thread is in the constructor of Factory?

like image 201
Naveen Avatar asked Dec 18 '10 06:12

Naveen


1 Answers

C++11 and above: local static creation is thread-safe.

The standard guarantees that:

  • The creation is synchronized.
  • Should the creation throws an exception, the next time the flow of execution passes the variable definition point, creation will be attempted again.

It is generally implemented with double-checking:

  • first a thread-local flag is checked, and if set, then the variable is accessed.
  • if not yet set, then a more expensive synchronized path is taken, and if the variable is created afterward, the thread-local flag is set.

C++03 and C++98: the standard knows no thread.

There are no threads as far as the Standard is concerned, and therefore there is no provision in the Standard regarding synchronization across threads.

However some compilers implement more than the standard mandates, either in the form of extensions or by giving stronger guarantees, so check out for the compilers you're interested in. If they are good quality ones, chances are that they will guarantee it.

Finally, it might not be necessary for it to be thread-safe. If you call this method before creating any thread, then you ensures that it will be correctly initialized before the real multi-threading comes into play, and you'll neatly side-step the issue.

like image 141
Matthieu M. Avatar answered Sep 28 '22 10:09

Matthieu M.