2 回答

TA貢獻1982條經驗 獲得超2個贊
您有多個關閉results通道的 goroutine。
func worker(ID int, jobs <-chan int, results chan<- int) {
for job := range jobs {
fmt.Println("Worker ", ID, " is working on job ", job)
time.Sleep(1000*time.Millisecond)
fmt.Println("Worker ", ID, " completed work on job ", job)
results <- job
}
close(results) <<<<-------- Here
}
worker你在三個不同的并發 goroutine 中運行這個函數。第一個到達標記線的人關閉通道,其他人嘗試results <- job在循環中的關閉通道上發送。

TA貢獻1873條經驗 獲得超9個贊
Eli Bendersky 的回答描述了這個問題。這個答案描述了修復。我知道你沒有要求修復,但我假設你有興趣。所以就在這里。
修復方法是在關閉通道之前等待工作 goroutine 完成。使用sync.WaitGroup來實現等待。
var wg sync.WaitGroup
for x := 1; x <= 3; x++ {
wg.Add(1) // increment worker counter
go func(x int) {
defer wg.Done() // decrement on return from goroutine
worker(x, jobs, results)
}(x)
}
// Close results channel when workers are done.
go func() {
wg.Wait()
close(results)
}()
在 PlayGround 上運行這個 GoLANG 程序:https: //play.golang.org/p/GM-0Gqx0Gbg
- 2 回答
- 0 關注
- 162 瀏覽
添加回答
舉報