這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
00. 背景
最近在學習MIT的分布式課程6.824的過程中,使用Go實現Raft協議時遇到了一些問題。參見如下代碼:
for i := 0; i < len(rf.peers); i++ { DPrintf("i = %d", i) if i == rf.me { DPrintf("skipping myself #%d", rf.me) continue } go func() { DPrintf("len of rf.peers = %d", len(rf.peers)) DPrintf("server #%d sending request vote to server %d", rf.me, i) reply := &RequestVoteReply{} ok := rf.sendRequestVote(i, args, reply) if ok && reply.VoteGranted && reply.Term == rf.currentTerm { rf.voteCount++ if rf.voteCount > len(rf.peers)/2 { rf.winElectionCh <- true } } }()}
其中,peers切片的長度為3,因此最高下標為2,在非並行編程中代碼中的for-loop應該是很直觀的,我當時並沒有意識到有什麼問題。可是在調試過程中,一直在報 index out of bounds 錯誤。調試資訊顯示i的值為3,當時就一直想不明白迴圈條件明明是 i < 2,怎麼會變成3呢。
01. 調查
雖然不明白髮生了什麼,但知道應該是迴圈中引入的 goroutine 導致的。經過Google,發現Go的wiki中就有一個頁面 Common Mistake - Using goroutines on loop iterator variables 專門提到了這個問題,看來真的是很 common 啊,笑哭~
初學者經常會使用如下代碼來平行處理資料:
for val := range values { go val.MyMethod()}
或者使用閉包(closure):
for val := range values { go func() { fmt.Println(val) }()}
這裡的問題在於 val 實際上是一個遍曆了切片中所有資料的單一變數。由於閉包只是綁定到這個 val 變數上,因此極有可能上面的代碼的運行結果是所有 goroutine 都輸出了切片的最後一個元素。這是因為很有可能當 for-loop 執行完之後 goroutine 才開始執行,這個時候 val 的值指向切片中最後一個元素。
The val variable in the above loops is actually a single variable that takes on the value of each slice element. Because the closures are all only bound to that one variable, there is a very good chance that when you run this code you will see the last element printed for every iteration instead of each value in sequence, because the goroutines will probably not begin executing until after the loop.
02. 解決方案
以上代碼正確的寫法為:
for val := range values { go func(val interface{}) { fmt.Println(val) }(val)}
在這裡將 val 作為一個參數傳入 goroutine 中,每個 val 都會被獨立計算並儲存到 goroutine 的棧中,從而得到預期的結果。
另一種方法是在迴圈內定義新的變數,由於在迴圈內定義的變數在迴圈遍曆的過程中是不共用的,因此也可以達到同樣的效果:
for i := range valslice { val := valslice[i] go func() { fmt.Println(val) }()}
對於文章開頭提到的那個問題,最簡單的解決方案就是在迴圈內加一個臨時變數,並將後面 goroutine 內的 i 都替換為這個臨時變數即可:
server := i
,