1
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)?

gmas80
  • 1,218
  • 1
  • 14
  • 44
Andy
  • 3,251
  • 4
  • 32
  • 53

1 Answers1

3
  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
}
VP.
  • 15,509
  • 17
  • 91
  • 161
  • Victor: thank you very much for your answer! What is the difference between std::unique_lock and std::lock_guard? The latter seems to pop-up when searching for std::mutex. Could the mutex also be a member variable? – Andy Jun 10 '15 at 13:46
  • Of course mutex can be a class member. About `std::lock_guard` - [see here](http://stackoverflow.com/questions/20516773/stdunique-lockstdmutex-or-stdlock-guardstdmutex) – VP. Jun 10 '15 at 13:51