Singleton class and thread safety

1k views Asked by At
class NumberStorage {
public:
    static NumberStorage& instance();
    double getNumber();
    void setNumber(double d);
private:
    NumberStorage() { number = 0.0; };
    double number;
};

NumberStorage& NumberStorage::instance()
{
    static NumberStorage instance;
    return instance;
}

I think I have read somewhere that the instance() method implemented this way is thread safe. Is this correct? I guess I also must lock the member variable number in the getNumber() and setNumber()? How do I do this (C++11)?

1

There are 1 answers

2
VP. On BEST ANSWER
  1. C++11 compiler makes this thread safe. Static variables can only be created by one single thread.
  2. Other questions about locks both depend on how threads should work with your methods. If you have multiple threads that can do something with one same piece of memory - use locks.

Simple lock can be used with std::unique_lock and std::mutex:

void setNumber(double number) {
    static std::mutex _setNumberLock;
    std::unique_lock _lock(&_setNumberLock);

    // your code
}