1 回答

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
這段代碼有幾個(gè)錯(cuò)誤,
值 chan 永遠(yuǎn)不會(huì)耗盡,所以任何寫入都會(huì)阻塞
價(jià)值通道永遠(yuǎn)不會(huì)關(guān)閉,所以任何流失都是無限的
通道必須始終排空,通道必須在某個(gè)時(shí)刻關(guān)閉。
另外,請(qǐng)發(fā)布可重現(xiàn)的示例,否則很難診斷問題。
這是 OP 代碼的略微修改但有效的版本。
package main
import (
"fmt"
"math"
"time"
)
func sineWave(value chan float64) {
defer close(value) // A channel must always be closed by the writer.
var div float64
sinMult := 6.2839
i := 0
fmt.Println("started")
for {
div = (float64(i+1) / sinMult)
time.Sleep(100 * time.Millisecond)
value <- math.Sin(div)
i++
if i == 4 {
// i = 0 // commented in order to quit the loop, thus close the channel, thus end the main for loop
break
}
}
}
func main() {
value := make(chan float64)
go sineWave(value) // start writing the values in a different routine
// drain the channel, it will end the loop whe nthe channel is closed
for v := range value {
fmt.Println(v)
}
}
- 1 回答
- 0 關(guān)注
- 115 瀏覽
添加回答
舉報(bào)