gpt4 book ai didi

go - 多次运行相同的go程序会引发 panic : send on closed channel

转载 作者:行者123 更新时间:2023-12-01 21:15:58 27 4
gpt4 key购买 nike

我刚接触golang并试图了解workerpool的工作原理。如果我运行一次,并且如果尝试运行多次,以下示例程序将运行良好,并且出现紧急情况:在关闭 channel 上发送错误。 Go版本是go1.14.2

package main
import (
"fmt"
"time"
)
func main() {
jobs := make(chan int, 10)
results := make(chan int, 10)

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

for j := 1; j <= 6; j++ {
jobs <- j
}
close(jobs)
for r:=range results{
fmt.Println("Result received from worker: ", r)
}
}
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)
}

第一次运行可以
go run main.go                                                                            
Worker 3 is working on job 1
Worker 1 is working on job 2
Worker 2 is working on job 3
Worker 2 completed work on job 3
Worker 2 is working on job 4
Result received from worker: 3
Worker 1 completed work on job 2
Worker 1 is working on job 5
Result received from worker: 2
Worker 3 completed work on job 1
Worker 3 is working on job 6
Result received from worker: 1
Worker 3 completed work on job 6
Result received from worker: 6

第二次运行给出了这一点。
Worker  3  is working on job  2
Worker 2 is working on job 3
Worker 1 is working on job 1
Worker 3 completed work on job 2
Worker 3 is working on job 4
Worker 2 completed work on job 3
Worker 2 is working on job 5
Worker 1 completed work on job 1
Worker 1 is working on job 6
Result received from worker: 2
Result received from worker: 3
Result received from worker: 1
Worker 1 completed work on job 6
Worker 3 completed work on job 4
Result received from worker: 6
panic: send on closed channel

goroutine 35 [running]:
main.worker(0x3, 0xc0000b0000, 0xc0000b00b0)
/home/jibi_makkar/code/go/src/main.go:30 +0x252
created by main.main
/home/jibi_makkar/code/go/src/main.go:13 +0xad
exit status 2

谁能帮助我了解发生了什么事?

最佳答案

您有多个goroutines关闭results channel 。

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
}

您可以在三个不同的并行goroutine中运行此 worker函数。第一个到达标记行的 channel 关闭,其他 channel 尝试在循环中的 results <- job中发送已关闭的 channel 。

关于go - 多次运行相同的go程序会引发 panic : send on closed channel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61534605/

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