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;
}
我想我已经在某处读过以这种方式实现的instance()方法是线程安全的。它是否正确?我想我还必须在getNumber()和setNumber()中锁定成员变量号?我该怎么做(C ++ 11)?
答案 0 :(得分:2)
简单锁可以与std::unique_lock
和std::mutex
:
void setNumber(double number) {
static std::mutex _setNumberLock;
std::unique_lock _lock(&_setNumberLock);
// your code
}