gpt4 book ai didi

go - 工作池上的 channel 死锁

转载 作者:IT王子 更新时间:2023-10-29 01:26:30 26 4
gpt4 key购买 nike

我正在通过创建一个包含 1000 个工作人员的工作池来玩弄 channel 。目前我收到以下错误:

fatal error: all goroutines are asleep - deadlock!

这是我的代码:

package main

import "fmt"
import "time"


func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "started job", j)
time.Sleep(time.Second)
fmt.Println("worker", id, "finished job", j)
results <- j * 2
}
}

func main() {
jobs := make(chan int, 100)
results := make(chan int, 100)

for w := 1; w <= 1000; w++ {
go worker(w, jobs, results)
}

for j := 1; j < 1000000; j++ {
jobs <- j
}
close(jobs)
fmt.Println("==========CLOSED==============")

for i:=0;i<len(results);i++ {
<-results
}
}

为什么会这样?我还是个新手,我希望能理解这一点。

最佳答案

虽然 Thomas 的回答基本上是正确的,但我发布了我的版本,IMO 更好的 Go,也适用于无缓冲 channel :

func main() {
jobs := make(chan int)
results := make(chan int)

var wg sync.WaitGroup

// you could init the WaitGroup's count here with one call but this is error
// prone - if you change the loop's size you could forget to change the
// WG's count. So call wg.Add in loop
//wg.Add(1000)
for w := 1; w <= 1000; w++ {
wg.Add(1)
go func() {
defer wg.Done()
worker(w, jobs, results)
}()
}

go func() {
for j := 1; j < 2000; j++ {
jobs <- j
}
close(jobs)
fmt.Println("==========CLOSED==============")
}()

// in this gorutine we wait until all "producer" routines are done
// then close the results channel so that the consumer loop stops
go func() {
wg.Wait()
close(results)
}()

for i := range results {
fmt.Print(i, " ")
}
fmt.Println("==========DONE==============")
}

关于go - 工作池上的 channel 死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44244881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com