go - 在 go Channel 中尝试 Range 和 Close
问题描述
我正在尝试在频道中使用 range 和 close 来更好地理解它。以下是我根据自己的理解尝试的代码示例。
执行下面的代码后,我得到代码下面提到的错误。
代码:
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
当您关闭 for 语句时退出hiChannel
,实际上您并没有关闭通道,因此,您的代码会引发死锁。
有几种方法可以关闭通道,例如,您可以计算打印了多少字符串,然后您可以关闭通道。
或者,您可以创建一个信号通道并在收到所有必要信息后关闭。
推荐阅读
- reactjs - React Native - 如何在 ASYNC 函数完成后执行函数
- python - 如何使用 re.sub() 在 Python 中添加字符串的开头?
- flutter - 在谷歌地图颤振包中使用不同于默认位置源
- python - 此消息是什么意思 [错误 71] 协议错误:'lib' -> 'folder/where/iam/building'/venv/lib64'
- stellar - 是否可以使用 XLM 从恒星网络上的锚点撤回法定货币
- javascript - 如何使用 localStorage 加载变量?
- python - IndexError:维度为 2 的张量的索引过多
- javascript - 从 Javascript 字符串中提取并保留域的 URL
- c++ - 将函数转换为本地函数 (lamba)
- xcode - Flutter Xcode Build Error 当我打开一个下载的项目时