Search code examples
goblockingchannel

Blocking by a channel in different place with only one message in 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: 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!")
}

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?


Solution

  • 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