首页 > 解决方案 > 在 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

标签: gorangechannel

解决方案


for s := range hiChannel

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


推荐阅读