我是新手golang,我对这个僵局感到困惑(在这里运行)package mainimport ( "fmt" "runtime" "time")func main() { c := make(chan string) work := make(chan int, 1) clvl := runtime.NumCPU() count := 0 for i := 0; i < clvl; i++ { go func(i int) { for jdId := range work { time.Sleep(time.Second * 1) c <- fmt.Sprintf("done %d", jdId) } }(i) } go func() { for i := 0; i < 10; i++ { work <- i } close(work) }() for resp := range c { fmt.Println(resp, count) count += 1 }}
1 回答
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
你永远不会 close c,所以你的for range循环永远等待。像这样关闭它:
var wg sync.WaitGroup
for i := 0; i < clvl; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
for jdId := range work {
time.Sleep(time.Second * 1)
c <- fmt.Sprintf("done %d", jdId)
}
}(i)
}
go func() {
for i := 0; i < 10; i++ {
work <- i
}
close(work)
wg.Wait()
close(c)
}()
编辑:修复了恐慌,感谢 Crast
- 1 回答
- 0 关注
- 147 浏览
添加回答
举报
0/150
提交
取消