6

Broadcast a signal on a channel

 3 years ago
source link: https://yourbasic.org/golang/broadcast-channel/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Broadcast a signal on a channel

yourbasic.org/golang

All readers receive zero values on a closed channel.

phonograph.jpg

In this example the Publish function returns a channel, which is used to broadcast a signal when a message has been published.

// Print text after the given time has expired.
// When done, the wait channel is closed.
func Publish(text string, delay time.Duration) (wait <-chan struct{}) {
    ch := make(chan struct{})
    go func() {
        time.Sleep(delay)
        fmt.Println("BREAKING NEWS:", text)
        close(ch) // Broadcast to all receivers.
    }()
    return ch
}

Notice that we use a channel of empty structs: struct{}. This clearly indicates that the channel will only be used for signalling, not for passing data.

This is how you may use the function.

func main() {
    wait := Publish("Channels let goroutines communicate.", 5*time.Second)
    fmt.Println("Waiting for news...")
    <-wait
    fmt.Println("Time to leave.")
}
Waiting for news...
BREAKING NEWS: Channels let goroutines communicate.
Time to leave.

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK