Go: Broadcast a signal on a channel

When you close a channel, all readers receive a zero value.

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 the news...")
        <-wait
        fmt.Println("The news is out, time to leave.")
}

Comments

Be the first to comment!