看板 C_Sharp 關於我們 聯絡資訊
另外問一下 在單例模式有些範例寫法會寫成如下 public class Singleton { private volatile static Singleton _instance = null; private static readonly object lockHelper = new object(); private Singleton(){} public static Singleton CreateInstance() { if(_instance == null) { lock(lockHelper) { if(_instance == null) _instance = new Singleton(); } } return _instance; } } 都已經用lock包住了 為什麼還需要volatile lock不就有屏蔽效果了 哪還需要volatile達到記憶體的屏蔽 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.41.238.99
jinmin88:用synchronized感覺才不需要用lock 06/17 14:34
iterator:這是 "double-checked locking is broken" 的問題 06/17 20:03
iterator:在_inst=new ...()的同時,if(_inst==null)可能會錯誤判斷 06/17 20:06
iterator:volatile是拿來避免這個問題的 06/17 20:08
iterator:不過, 在 .NET 裡面, 因為 memory model 設計, 06/17 20:09
iterator:所以不會遇到這樣的情況產生 06/17 20:09
iterator:但是, 在 ECMA 標準或是其它 implement 下, 06/17 20:10
iterator:不同CPU(x86/x64/IA-64)差異,就不能保證不會有這個問題 06/17 20:11
ghostx2:我在MSDN Magazine有看到類似記憶體架構, 無奈實力不夠 06/17 22:33
ghostx2:尚不能理解文章內容, 看到iterator講解後就比較淺顯易懂 06/17 22:34
ghostx2:附上我看到的文章http://ppt.cc/SKkx 06/17 22:35