c++ - Singleton class and thread safety -
class numberstorage { public: static numberstorage& instance(); double getnumber(); void setnumber(double d); private: numberstorage() { number = 0.0; }; double number; }; colorramps& colorramps::instance() { static colorramps instance; return instance; }
i think have read somewhere instance() method implemented way thread safe. correct? guess must lock member variable number in getnumber() , setnumber()? how do (c++11)?
- c++11 compiler makes thread safe. static variables can created 1 single thread.
- other questions locks both depend on how threads should work methods. if have multiple threads can 1 same piece of memory - use locks.
simple lock can used std::unique_lock
, std::mutex
:
void setnumber(double number) { static std::mutex _setnumberlock; std::unique_lock _lock(&_setnumberlock); // code }
Comments
Post a Comment