gpt4 book ai didi

go - 在Go Channel中尝试范围和关闭

转载 作者:行者123 更新时间:2023-12-01 22:07:10 24 4
gpt4 key购买 nike

我正在尝试使用范围并在 channel 中关闭以更好地理解它。
以下是根据我的理解尝试过的代码示例。

执行下面的代码后,我得到代码下面提到的错误。

代码:

package main

import (
"fmt"
)

func main() {
str := "hello"
hiChannel := make(chan string, 5)
for j := 1; j <= 5; j++ {
go func(hi string) {
hiChannel <- hi
}(str)
}
defer close(hiChannel)
for s := range hiChannel {
fmt.Println(s)
}
}

错误:
go run restsample/restsample.go
hello
hello
hello
hello
hello
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
C:/Users/Indian/personal/Workspaces/Learning/src/restsample/restsample.go:16 +0x169
exit status 2

最佳答案

for s := range hiChannel

当您关闭 hiChannel时,for语句退出,实际上您并未关闭 channel ,因此,您的代码引发了死锁。
有几种关闭 channel 的方法,例如,您可以计算已打印的字符串数,然后可以关闭 channel 。
或者,您可以创建一个信号 channel 并在收到所有必要信息后关闭。

关于go - 在Go Channel中尝试范围和关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60928562/

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