在 Golang 中只有一条消息被不同地方的频道阻塞?

Blocking by a channel in different place with only one message in Golang?

我正在尝试创建一个频道,用于确保一切就绪,

所以我可以继续这个过程,一个例子是这样的:playground

package main

import (
    "fmt"
)

// done sends the channel a "okay" status.
func done(ok chan<- bool) {
    ok <- true
}

// waiting is a function that waiting for everything's okay.
func waiting(ok <-chan bool) {
    <-ok

    // Do something here
    // when everything's okay...
}

func main() {
    ok := make(chan bool)

    // Send the "ok" status once.
    go done(ok)

    // function A mockup
    waiting(ok)
    // function B mockup
    waiting(ok)

    fmt.Println("All Ok!")
}

这是输出:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /tmp/sandbox709143808/main.go:29 +0xc0

我被排除在发送 ok <- true 一次 ,

然后我可以在多个地方使用它,并得到这样的输出:

All Ok!

Program exited.

但我不确定该怎么做,知道吗?

您可以关闭频道而不是发送消息。关闭操作就像将 ok 广播给所有正在收听的 froutines

代码

package main

import (
    "fmt"
)

// done sends the channel a "okay" status.
func done(ok chan<- bool) {
    close(ok)
}

// waiting is a function that waits for everything's okay.
func waiting(ok <-chan bool) {
    <-ok

    // Do something here
    // when everything's okay...
}

func main() {
    ok := make(chan bool)

    // Send the "ok" status once.
    go done(ok)
    //go done(ok)

    // function A mockup
    waiting(ok)
    // function B mockup
    waiting(ok)

    fmt.Println("All Ok!")
}

这里有戏linkplay.golang