[問題] singleton pattern for multithread
看板C_and_CPP (C/C++)作者su31o4gj83 (哈哈哈哈哈哈哈哈哈哈哈)時間16年前 (2009/07/03 14:00)推噓5(5推 0噓 16→)留言21則, 5人參與討論串1/2 (看更多)
我的問題是關於singleton pattern在多執行緒下的一種解決方法
即所謂的雙重檢查法(double-checked locking)
我對於雙重檢查法並沒有覺得有什麼問題
不過有瀏覽到一個網頁, 其中提到這個方法會有問題
網頁如下:
http://www.oaklib.org/docs/oak/singleton.html
其中提到
For the following case:
pInstance_ = new WindowManager();
the compiler allocates space for WindowManager object, calls the constructor
and initializes pInstance_. It's quite possible that the optimizer moves
around instructions so that pInstance_ is initialized before the object has
been completely initialized. This may cause some other thread calling
getInstance() to return partially initialzed object.
就我的理解是說 pInstance_ = new WindowManager();
這個動作執行時, 由於multithread的關係,
可能使pInstance被初始化了, 但物件卻沒有建立完全
這點我就有點不太了解, 因為我看程式碼中在執行這行時,
前後有被lock_mutex()與unlock_mutex()包起來,
這樣仍有可能在跑 new WindowManager() 的過程中,
暫時停止new的動作, 而去跑其他的thread嗎 ??
另外, 如果網頁上所展示的雙重檢查法(第3段程式碼)是有問題的,
除了網頁上提到的solution外, 還有其他的方法嗎 ??
因為我覺得網頁上的solution不是很"直覺"
我有看到一個網頁也談到雙重檢查法, 但並沒有談到這個問題,
網頁如下:
http://www.codeproject.com/KB/architecture/singleton.aspx
段落的標題為"Resolving the multi-threading issue"
另外, Head First Design Patterns 中講到雙重檢查法時,
也沒有提到這個問題
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 210.209.20.225
推
07/03 14:24, , 1F
07/03 14:24, 1F
→
07/03 14:25, , 2F
07/03 14:25, 2F
→
07/03 14:26, , 3F
07/03 14:26, 3F
→
07/03 17:17, , 4F
07/03 17:17, 4F
→
07/03 17:21, , 5F
07/03 17:21, 5F
→
07/03 17:21, , 6F
07/03 17:21, 6F
→
07/03 17:22, , 7F
07/03 17:22, 7F
→
07/03 17:26, , 8F
07/03 17:26, 8F
→
07/03 17:26, , 9F
07/03 17:26, 9F
推
07/03 17:31, , 10F
07/03 17:31, 10F
→
07/03 17:42, , 11F
07/03 17:42, 11F
→
07/03 17:48, , 12F
07/03 17:48, 12F
→
07/03 17:52, , 13F
07/03 17:52, 13F
推
07/03 18:20, , 14F
07/03 18:20, 14F
→
07/03 18:20, , 15F
07/03 18:20, 15F
推
07/03 19:57, , 16F
07/03 19:57, 16F
→
07/03 19:57, , 17F
07/03 19:57, 17F
推
07/04 00:20, , 18F
07/04 00:20, 18F
→
07/04 00:21, , 19F
07/04 00:21, 19F
→
07/04 00:21, , 20F
07/04 00:21, 20F
→
07/04 14:32, , 21F
07/04 14:32, 21F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章