gpt4 book ai didi

concurrency - 以下 golang 代码死锁。有人可以帮助理解为什么吗?

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

这个例子取自http://blog.golang.org/pipelines .它运行并给出正确答案,但它显示以下运行时错误:“ fatal error :所有 goroutines 都睡着了 - 死锁!”。谁能帮我理解为什么会这样? 包主

import (
"fmt"
)

func gen(nums ...int) <- chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
}()
return out
}

func sq(in <- chan int) <- chan int {
out := make(chan int)
go func() {
for n := range in {
out <- n * n
}
close(out)
}()
return out
}

func main() {
for n := range sq(gen(2,3)) {
fmt.Println(n)
}
}

但是下面的修改没有。

func main() {
// Set up the pipeline.
c := gen(2, 3)
out := sq(c)

// Consume the output.
fmt.Println(<-out) // 4
fmt.Println(<-out) // 9
}

最佳答案

sq() 函数的 for n := range in 永远不会退出,并开始阻塞(读取 2 个值后),因为 gen() 从未关闭其 channel 。
close(out) 添加到 gen()go func 将使其工作:see playground .

对于 channel ,接收方阻塞直到接收到一个值。
The range keyword, when used with a channel, will wait on the channel until it is closed .

sq() 被阻塞,这意味着 close(out) 永远不会被调用,而 main() 又会阻塞 range sq()(因为 channel sq 没有关闭)。

在你的第二个例子中,main() 本身退出了,这意味着即使 sq() 被阻止,一切仍然停止。

关于concurrency - 以下 golang 代码死锁。有人可以帮助理解为什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26189485/

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