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

1 Answer 1

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 } 
Sign up to request clarification or add additional context in comments.

2 Comments

Victor: thank you very much for your answer! What is the difference between std::unique_lock and std::lock_guard<std::mutex>? The latter seems to pop-up when searching for std::mutex. Could the mutex also be a member variable?
Of course mutex can be a class member. About std::lock_guard - see here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.