

Broadcast a signal on a channel
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
All readers receive zero values on a closed channel.

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:
Recommend
-
5
為什麼 signal.Notify 要使用 buffered channel 如果不了解什麼是 buffer 或 unbuffer channel 的朋友們,可以參考
-
9
February 24, 2022
-
1
Signal’s new Stories feature is now available on the beta channel Privacy-focused messaging app Signal is receiving a new update on the beta channel, which brings the Stories fe...
-
9
Widening the Channel: Exertis Broadcast Adds Backblaze B2 Reserve December 9, 2022 by Elton Carneiro //
-
9
Instagram Adds Broadcast Channel Guests to Provide More Content Options Published May 16, 2023 By
-
5
AirTunes signal injection and broadcast
-
5
Instagram Expands Broadcast Channels to All Creators, Tests New Channel Options Published June 15, 2023 By
-
6
5 Tips for Maximizing Your Instagram Broadcast Channel [Infographic] Published June 22, 2023 By
-
2
How to broadcast message using channel Asked...
-
5
Positron Broadcast Signal Processor TRA7005 v1.20 - Authentication Bypass...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK