阻止通道畅通无阻

默认情况下,通道上的通信是同步的; 当你发送一些值时,必须有一个接收器。否则你会得到 fatal error: all goroutines are asleep - deadlock! 如下:

package main

import "fmt"

func main() {
    msg := make(chan string)
    msg <- "Hey There"
    go func() {
        fmt.Println(<-msg)
    }()
}

有一个解决方案使用:使用缓冲通道:

package main

import "fmt"
import "time"

func main() {
    msg :=make(chan string, 1)
    msg <- "Hey There!"
    go func() {
        fmt.Println(<-msg)
    }()
    time.Sleep(time.Second * 1)
}