通道没有死锁或锁定

cur*_*eer 3 go

我有一小段这样的代码

func main() {
    var c chan string
    go func() {
        c <- "let's get started"//write1
        //c <- "let's get started"//write2
        //c <- "let's get started"//write3
        fmt.Println("wrote the stuff....")
    }()
    //time.Sleep(3 * time.Second) //adding this always shows fatal exception
    c = make(chan string)
    fmt.Println(<-c)
}
Run Code Online (Sandbox Code Playgroud)

wrote the stuff....如果我取消注释//write2和write3编码片段行,我在控制台上看不到输出.我知道可能我不认为这是因为通道是无缓冲且完全同步的,并且通道外只有一次读取.但是,当程序退出时,go例程被阻止,为什么deadlocked...在这种情况下没有像我看到的那样的错误?

use*_*ica 6

在尝试写入通道之前创建通道.如果funcgoroutine尝试c在那里实际存在通道之前发送元素,则它最终使用nil通道,该通道永久阻塞.

  • 如果您写了3次并且只读了一次goroutine泄漏但没有死锁,因为主程序将在读取第一个值后退出. (2认同)