天天看點

基于double lock的多線程安全的Singleton實作要點

老問題了,直接上代碼(C#)

class Singleton

{

private static volatile bool beInitialized= false;

private static object thisLock = new object();

private static Singleton instance;

Singleton GetInstance()

{

if (!beInitialized)

{

lock(thisLock)

{

if (!beInitialized)

{

instance = new Singleton();

beInitialized = true;

}

}

}

return instance;

}

}

1. 使用volatile修飾初始化标志beInitialized。

2. 先執行個體化對象,再設定标志。

Note:

1. 可以把beInitialized省去,直接用instance==null作為标記,但要用volatile修飾。不過用volatile最大的問題是,對變量的讀保護和寫保護是同時的,但且是使用變量處都要進行。是以有些性能損失。

2.使用interlocked.exchange代替volatile獲得更好的性能。

class Singleton

{

private static object thisLock = new object();

private static Singleton instance;

Singleton GetInstance()

{

if (instance==null)

{

lock(thisLock)

{

Singleton temp = new Singleton();

Interlocked.Exchange(ref instance, temp);

}

}

return instance;

}

}

3.換成是C++,還得加上神奇的栅欄,才能保證通用性。比如IA64上。