对我来说,使用 c++11 实现单例的最佳方法是:
class Singleton
{
public:
static Singleton & Instance()
{
// Since it's a static variable, if the class has already been created,
// It won't be created again.
// And it **is** thread-safe in C++11.
static Singleton myInstance;
// Return a reference to our instance.
return myInstance;
}
// delete copy and move constructors and assign operators
Singleton(Singleton const&) = delete; // Copy construct
Singleton(Singleton&&) = delete; // Move construct
Singleton& operator=(Singleton const&) = delete; // Copy assign
Singleton& operator=(Singleton &&) = delete; // Move assign
// Any other public methods
protected:
Singleton()
{
// Constructor code goes here.
}
~Singleton()
{
// Destructor code goes here.
}
// And any other protected methods.
}
这是一个 c++11 的特性,但是通过这种方式你可以创建一个线程安全的 Singleton。按照新标准,这个问题就不用管了。对象初始化将仅由一个线程进行,其他线程将等待它完成。或者你可以使用 std::call_once。
如果你想独占访问单例的资源,你必须在这些函数中使用锁。
不同类型的锁:
使用 atomic_flg_lck:
class SLock
{
public:
void lock()
{
while (lck.test_and_set(std::memory_order_acquire));
}
void unlock()
{
lck.clear(std::memory_order_release);
}
SLock(){
//lck = ATOMIC_FLAG_INIT;
lck.clear();
}
private:
std::atomic_flag lck;// = ATOMIC_FLAG_INIT;
};
使用原子:
class SLock
{
public:
void lock()
{
while (lck.exchange(true));
}
void unlock()
{
lck = true;
}
SLock(){
//lck = ATOMIC_FLAG_INIT;
lck = false;
}
private:
std::atomic<bool> lck;
};
使用互斥锁:
class SLock
{
public:
void lock()
{
lck.lock();
}
void unlock()
{
lck.unlock();
}
private:
std::mutex lck;
};
仅适用于 Windows:
class SLock
{
public:
void lock()
{
EnterCriticalSection(&g_crit_sec);
}
void unlock()
{
LeaveCriticalSection(&g_crit_sec);
}
SLock(){
InitializeCriticalSectionAndSpinCount(&g_crit_sec, 0x80000400);
}
private:
CRITICAL_SECTION g_crit_sec;
};
atomic 和 and atomic_flg_lck 将线程保持在旋转计数中。 Mutex 只是让线程休眠。如果等待时间太长,最好让线程休眠。最后一个“CRITICAL_SECTION”使线程保持旋转计数,直到消耗了一段时间,然后线程进入睡眠状态。
如何使用这些关键部分?
unique_ptr<SLock> raiilock(new SLock());
class Smartlock{
public:
Smartlock(){ raiilock->lock(); }
~Smartlock(){ raiilock->unlock(); }
};
使用 raii 成语。锁定临界区的构造函数和解锁临界区的析构函数。
例子
class Singleton {
void syncronithedFunction(){
Smartlock lock;
//.....
}
}
这个实现是线程安全和异常安全的,因为变量锁保存在堆栈中,所以当函数作用域结束(函数结束或异常)时,将调用析构函数。
希望对您有所帮助。
谢谢!!