我想編寫三個(gè)同時(shí)發(fā)送整數(shù)的并發(fā)go例程?,F(xiàn)在,我的代碼已正確編譯,但是在第一次執(zhí)行后,出現(xiàn)錯(cuò)誤“拋出:所有g(shù)oroutine都處于睡眠狀態(tài)-死鎖!”。我試圖找到錯(cuò)誤,但在代碼邏輯中找不到任何錯(cuò)誤。有人可以幫助我在我的代碼中查找錯(cuò)誤嗎?我的代碼如下。package mainimport "rand"func Routine1(command12 chan int, response12 chan int, command13 chan int, response13 chan int) { // z12 is a variable which stores the value comming from channel 2 and z13 is a variable which stores the value comming from channel 3. z12 := 200 z13 := 200 m12 := false m13 := false y := 0 for i := 0; i < 20; i++ { y = rand.Intn(100) // If y's value is not 0 then the value will be sent to routine 2 or 3 according to prime or not. // If y's value is 0 then process state (the varibles used by it means z12, z13) and channel state will be saved.[routine 1 is initiator] if y == 0 { print(z12, " z12 STATE SAVED\n") print(z13, " z13 STATE SAVED\n") // Routine 1 is initiator, it sends 0 to make other process to save the state. y = 0 command12 <- y command13 <- y // Untill routine 2 and 3 does not send 0, process 1 is on channel saving state (it's process state is already saved). // When routine 1 recives 0 from both other processes, channel is saved and routine 1 retuns to it's common routine procedure. // When routine 1 recives 0 from any other processes, saving channel bettwen them is stopped. // m12, m13 is used to mark whether 0 recived or not.
2 回答

森林海
TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
我不知道您的問題的答案,但是中的switch
語句Routine3
看起來有問題,因?yàn)樗瑑蓚€(gè)相同的case
語句(這使我感到奇怪,為什么6g不會(huì)抱怨此代碼)。
一些使您的代碼更清晰的建議:
正如Evan已經(jīng)指出的那樣,請(qǐng)嘗試為變量提供更多描述性的名稱。讀取的代碼
if someConditionIsMet
比容易理解if m23 == false
。通過將通用部分分解為函數(shù)來干燥代碼。
刪除無效代碼,例如將布爾值設(shè)置為true,然后檢查其是否為true或檢查奇數(shù)是否等于零。
考慮使用
else
代替if <condition> {...}; if <negated condition> {...}
我建議嘗試提出單元測(cè)試,以詳盡地描述您的功能的預(yù)期行為。這不僅可以幫助您找到錯(cuò)誤,還可以提高您的編碼技能。根據(jù)我的經(jīng)驗(yàn),考慮到測(cè)試編寫的代碼通常比未經(jīng)測(cè)試的代碼更易于理解,維護(hù)和發(fā)展。
快樂黑客:)
- 2 回答
- 0 關(guān)注
- 259 瀏覽
添加回答
舉報(bào)
0/150
提交
取消