[問題] 關於保護critical section的問題

看板C_and_CPP (C/C++)作者 (v(^O^)v)時間16年前 (2010/04/13 21:45), 編輯推噓5(508)
留言13則, 7人參與, 最新討論串1/1
最近在實作 Bakery's Algorithm來保護critical section 以下是我寫的Bakery Algorithm副程式 int Choosing[4] = {0}, Number[4] = {0};/*global variable*/ /*Lock*/ void Bakery(int i){ int j, Max = 0; Choosing[i] = 1; for(j = 0; j < 4; j++){ if(Number[j] > Max) Max = Number[j]; } Number[i] = Max + 1; Choosing[i] = 0; for(j = 0; j < 4; j++){ while(Choosing[j]); /*不好意思PO版時打錯*/ while((Number[j] != 0) && ((Number[j] < Number[i]) || ((Number[j] == Number[i]) && (j < i)))); } } /*Unlock*/ void Unlock(int i){ Number[i] = 0; } 總共有4條threads 不知道為什麼還是會有兩條不同的threads同時通過Bakery這個 副程式進入critical section而造成race condition? 謝謝大家 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.124.105.193 ※ 編輯: allrain 來自: 122.124.105.193 (04/13 21:47)

04/14 02:18, , 1F
while(Choosing[j]);
04/14 02:18, 1F

04/14 11:25, , 2F
Choosing[i] = 0; while(Choosing[i]); ???????
04/14 11:25, 2F
※ 編輯: allrain 來自: 140.112.30.32 (04/14 15:24)

04/14 15:35, , 3F
建議說說你的演算法 為什麼這麼寫是安全的
04/14 15:35, 3F

04/14 17:47, , 4F
那可能要先問為什麼 Bakery algorithm 是安全的了 :p
04/14 17:47, 4F

04/14 23:20, , 5F
也許你需要宣告Choosing和Number是volatile
04/14 23:20, 5F

04/14 23:21, , 6F
我想除非用上 atomic operator...否則很難保證什麼
04/14 23:21, 6F

04/15 13:26, , 7F
因為這個演算法的正確性是已經被證明了 我想要問的是
04/15 13:26, 7F

04/15 13:26, , 8F
為什麼Mutual Exclusive這個特性還是會違反?
04/15 13:26, 8F

04/15 14:57, , 9F
就像james732說的 Bakery有他的假設 但是目前的硬體沒有提
04/15 14:57, 9F

04/15 14:58, , 10F
供 www.hpl.hp.com/research/linux/atomic_ops/ 參考看看
04/15 14:58, 10F

04/15 16:24, , 11F
可是Bakery algorithm沒有任何需要atomic operation的假設
04/15 16:24, 11F

04/15 16:25, , 12F
非常感謝樓上的回答 我試試看宣告前加volatile! 謝謝!
04/15 16:25, 12F

04/15 21:09, , 13F
volatile? 你應該要使用__asm__("lock")
04/15 21:09, 13F
文章代碼(AID): #1Bn7LXVf (C_and_CPP)
文章代碼(AID): #1Bn7LXVf (C_and_CPP)