Go Broadcast, one channel send to many goroutines channel recieve
package main
import (
"fmt"
"time"
"sync
)
var (
bcast *broadcast
wg sync.WaitGroup
)
func main() {
// Create broadcast group to send the []byte to all subscribed routines
bcast = NewBroadcast()
// Start listener routines
wg.Add(5)
for i := 0; i < 5; i++ {
go reciever(i)
}
// Send some messages
for i := 0; i < 5; i++ {
bcast.SendMessage([]byte("Test Message"))
time.Sleep(time.Second)
}
wg.Wait()
}
func reciever(i int) {
defer wg.Done()
// Create a new listener to subscribe to the channel
instanceID, instanceChan := bcast.NewListener()
// Defer leaving the broadcast group, unsubscribe
defer bcast.LeaveGroup(instanceID)
// Listen for messages
for {
select {
case msg <-instanceChan:
fmt.Printf("Recieved msg from routine %d: %s\n", i, msg)
}
}
}