1. linux x86平台上局部静态对象构造是线程安全的
class Singleton{
public:
static Singleton*GetInstance(){
//函数静态局部变量的初始化,汇编指令上已经自动添加了互斥指令了,所以这里是线程安全的
static Singleton instance;
return &instance;
}
private:
Singleton(){}
Singleton(const Singleton&) = delete;
void operator=(const Singleton&) = delete;
};
2. c++11提供了std::call_once保证函数在多线程环境下只执行一次
保证instance = new Singleton()
在多线程环境下只被调用一次:
class Singleton{
public:
static Singleton*GetInstance(){
std::call_once(once, [&](){ instance = new Singleton(); });
return instance;
}
private:
static std::once_flag once;
static Singleton *instance;
Singleton(){}
Singleton(const Singleton&) = delete;
void operator=(const Singleton&) = delete;
};
Singleton * Singleton:: instance = nullptr;