douningchang3610 2017-02-10 07:20
浏览 15
已采纳

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

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: <kbd>playground</kbd>

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条回答 默认 最新

  • doudouba4520 2017-02-10 07:33
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值