英文:
Blocking by a channel in different place with only one message in Golang?
问题
我正在尝试创建一个通道,用于确保一切准备就绪,这样我就可以继续进行处理。一个示例可以是这样的:
package main
import (
"fmt"
)
// done sends the channel a "okay" status.
func done(ok chan<- bool) {
ok <- true
}
// waiting is a function that waits for everything to be okay.
func waiting(ok <-chan bool) {
<-ok
// 在这里做一些操作
// 当一切都准备就绪时...
}
func main() {
ok := make(chan bool)
// 发送"okay"状态一次。
go done(ok)
// 函数A模拟
waiting(ok)
// 函数B模拟
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.
但我不确定如何做到这一点,有什么想法吗?
英文:
I'm trying to create a channel which used to make sure that everything is ready,
so I can continue with the process, an example would be like this: <a href="https://play.golang.org/p/WXG1quHPwd"><kbd>playground</kbd></a>
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!")
}
and here's the output:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/tmp/sandbox709143808/main.go:29 +0xc0
I'm excepted to send the ok <- true
once,
then I can use it in multiple places, and get the output like this:
All Ok!
Program exited.
but I'm not sure how to do that, any idea?
答案1
得分: 2
你可以关闭通道而不是发送消息。关闭通道将被视为向所有正在监听的例程广播"ok"。
代码
package main
import (
"fmt"
)
// done 向通道发送"ok"状态。
func done(ok chan<- bool) {
close(ok)
}
// waiting 是一个等待一切都正常的函数。
func waiting(ok <-chan bool) {
<-ok
// 在一切都正常时做一些操作...
}
func main() {
ok := make(chan bool)
// 发送一次"ok"状态。
go done(ok)
//go done(ok)
// 函数A模拟
waiting(ok)
// 函数B模拟
waiting(ok)
fmt.Println("一切正常!")
}
这是play链接 play.golang
英文:
You may close the channel isstead of sending a message .Closing will act as if the ok is broadcasted to all listening froutines
Code
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!")
}
Here is the play link play.golang
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论