1 回答
TA贡献1873条经验 获得超9个赞
这段代码有几个错误,
值 chan 永远不会耗尽,所以任何写入都会阻塞
价值通道永远不会关闭,所以任何流失都是无限的
通道必须始终排空,通道必须在某个时刻关闭。
另外,请发布可重现的示例,否则很难诊断问题。
这是 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 关注
- 86 浏览
添加回答
举报