在 go Channel 中尝试 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


当年话下
浏览 112回答 2
2回答

慕沐林林

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

茅侃侃

根据@Tinwor 的反馈,我尝试添加几行来检查消息计数并且它有效。谢谢。package mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; str := "hello"&nbsp; &nbsp; hiChannel := make(chan string, 5)&nbsp; &nbsp; for j := 1; j <= 5; j++ {&nbsp; &nbsp; &nbsp; &nbsp; go func(hi string) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hiChannel <- hi&nbsp; &nbsp; &nbsp; &nbsp; }(str)&nbsp; &nbsp; }&nbsp; &nbsp; i := 1&nbsp; &nbsp; for s := range hiChannel {&nbsp; &nbsp; &nbsp; &nbsp; i++&nbsp; &nbsp; &nbsp; &nbsp; if i == 5 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(s)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; close(hiChannel)&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(s)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go