Multithreaded singleton: is a mutex instance method needed?

I have my application config stored in a singleton class like this (simplified):

class Conf
{
    Conf();
    Conf(const Conf&);
    Conf& operator=(const Conf&);
    ~Conf();

public:

    static Conf& instance() 
    {
        static Conf singleton;
        return singleton;
    };

    static void setProperty(const std::string& name,
                            const std::string& value);
    static std::string getProperty(const std::string& name);

private:

    QMutex _mutex;
    std::map<std::string, std::string> _properties;
};

      

Since the config class can be accessed from many threads, I use a mutex for synchronization:

void Conf::setProperty(const std::string& name,
                 const std::string& value)
{
    QMutexLocker(&Conf::instance()._mutex);
    Conf::instance()._properties[name]=value;
}

std::string Conf::getProperty(const std::string& name)
{
    QMutexLocker(&Conf::instance()._mutex);
    return Conf::instance()._properties[name];
}

      

Is the method required to Conf::instance()

block?

I found a similar question: Is a mutex getter function needed? but in my case there is no setter method (assume the singleton is instantiated before the threads start).

+3


source to share


3 answers


If you are using C ++ 11 or better, creating a static singleton is guaranteed to be thread safe.

If you are still using C ++ 03 you need to provide your own mechanism.

on request:

section 6.7 of the C ++ 11 standard:



such a variable is initialized when the first control passes through its declaration; such a variable is considered initialized after completion of its initialization. [...] If the control enters the declaration at the same time and the variable is initialized, the concurrent execution must wait for the initialization to complete.

Footnote:

An implementation should not introduce any deadlock around initializer execution.

+5


source


in C ++ 11 instance()

a mutex is not needed, in C ++ 98 it works because two threads can immediately inject it into the object creating the origin. C ++ 11 provides single initialization for local variables static

.



+3


source


Used this way, no instance () needs a mutex.

However, I would enforce this by moving the instance in the private section, allowing client code to only use setProperty / getProperty.

+2


source







All Articles