我试图创建一个用来确保一切准备就绪的频道,
所以我可以继续这个过程,例如: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.
但我不确定该怎么做,有什么想法吗?
答案 0 :(得分:2)
您可以关闭频道而不是发送消息。关闭将表现为好像广播给所有收听的节目
<强>代码强>
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!")
}
以下是播放链接play.golang