多線程爲什麼要Double-Check Locking

public static Singleton Value{

 

  get {

        // Has the singleton object already been created?

        if (s_value == null) {

        // No, only one thread should create it

        lock (s_lock) {

        // Did another thread create it?

        if (s_value == null) {

        // No, OK, this thread will create it.

        // Volatile ensures that all of singleton object's fields

        // (initialled by the constructor) are flushed before

        // other threads see the reference to the Singleton object

        s_value = new Singleton();

    }

}

第二次檢查是因爲如果兩個線程都進入了 if (s_value == null) {,一個線程lock住new完了以後,另一個線程又lock並new,把原來的實例沖掉了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章