当 golang 关闭通道时,接收 goroutine 永远不会被阻塞

问题描述 投票:0回答:3

我刚接触Golang,我写了一些代码来学习Golang通道,如下一段代码:

func main(){
    intChan := make(chan int, 1)
    strChan := make(chan string, 1)

    intChan <- 3
    strChan <- "hello"
    fmt.Println("send")

    // comment this, fatal error: all goroutines are asleep - deadlock!
    // close(intChan)
    // close(strChan)

    for {
        select {
        case e, ok := <-intChan:
            time.Sleep(time.Second * 2)
            fmt.Println("The case intChan ok: ", ok)
            fmt.Println("The case intChan is selected.", e)

        case e, ok := <-strChan:
            time.Sleep(time.Second)
            fmt.Println("The case strChan ok: ", ok)
            fmt.Println("The case strChan is selected.", e)
        }
    }
}

如果我评论

close()
函数,“for”语句被阻塞,就像错误说“all goroutines are asleep - deadlock!”,这似乎是合理的。

如果我取消注释

close()
,“for”语句永远不会停止。接收者从通道中获取默认值 0 和 nil,并且从不阻塞。

即使我没有向频道发送任何内容,并在定义频道后调用

close()
。接收器永远不会阻塞或导致任何错误。

我对

close
函数做了什么感到困惑,它是否启动了一个go例程将特定类型的默认值发送到通道,并且永不停止?

有人可以给我一些提示吗?非常感谢。

go goroutine
3个回答
0
投票

当您取消注释

close(intChan)
close(strChan)
时,for 循环会继续在主函数中重复,即使没有更多的消息通过通道到达。

如果通道关闭,向其发送值将被阻塞,但从中接收值仍将返回剩余值,直到它为空。


0
投票

关闭频道后,您仍然可以阅读,但您的

ok
将是错误的。所以,这就是为什么你的
for
永远不会停止。

当通道未关闭时,当您尝试从中读取数据时,它将被阻塞或不被阻塞取决于缓冲/未缓冲通道。


缓冲通道:你给大小(

make(chan int, 1)
)。
无缓冲通道:你不给尺寸(
make(chan int)
)


在你评论

close
的情况下,它会从你缓冲的通道中读取一次数据,因为你通过
intChan <- 3
strChan <- "hello"
发送数据到通道。所以,你会看到你的控制台打印出以下结果。

send
The case strChan ok:  true
The case strChan is selected. hello
The case intChan ok:  true
The case intChan is selected. 3

但是,在那之后,两个缓冲通道都没有数据了。然后,如果您尝试读取它,您将被阻塞,因为缓冲通道中没有任何数据。 (实际上,当没有数据时,无缓冲是相同的情况。)

然后,你得到

all goroutines are asleep - deadlock
因为主 goroutine 被阻塞等待来自通道的数据。顺便说一下,当你运行这个程序时,它会启动一个主 goroutine 来运行你的代码。如果只有一个主 goroutine 被阻塞,那意味着没有人可以帮助你运行你的代码。

你可以在 for 语句之前添加以下代码。

go func() {
    fmt.Println("another goroutine")
    for {}
}()

你会看到你没有遇到死锁,因为仍然有一个 goroutine“可能””运行你的代码。


0
投票

我猜你需要验证频道是否仍然可以接收消息;如果没有,只需使用“break”退出 for-loop

package main

import (
    "fmt"
    "time"
)

func main() {
    intChan := make(chan int, 1)
    strChan := make(chan string, 1)

    intChan <- 3
    strChan <- "hello"
    fmt.Println("send")

    // comment this, fatal error: all goroutines are asleep - deadlock!
    // close(intChan)
    // close(strChan)

    for {
        select {
        case e, ok := <-intChan:
            if !ok {
                break
            }
            time.Sleep(time.Second * 2)
            fmt.Println("The case intChan ok: ", ok)
            fmt.Println("The case intChan is selected.", e)
            close(intChan)

        case e, ok := <-strChan:
            if !ok {
                break
            }
            time.Sleep(time.Second)
            fmt.Println("The case strChan ok: ", ok)
            fmt.Println("The case strChan is selected.", e)
            close(strChan)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.