Skip to content

Instantly share code, notes, and snippets.

@whyrusleeping
Created May 19, 2013 18:25
Show Gist options
  • Save whyrusleeping/5608502 to your computer and use it in GitHub Desktop.
Save whyrusleeping/5608502 to your computer and use it in GitHub Desktop.
Broadcast Channel for go
//In this example i assume that 'T' is an int
func DoWhatever(toSay string, c chan int) {
for {
n := <-c
fmt.Printf('%s %d\n', toSay, n)
}
}
func main() {
bc := NewBroadcastChannel()
go DoWhatever('hello', bc.GetReciever())
go DoWhatever('number is:', bc.GetReceiver())
go DoWhatever('i like', bc.GetReceiver())
sc := bc.Sender
for i := 0; i < 15; i++ {
sc <- i
}
}
type BroadChannel struct {
Sender chan<- T
recievers []<-chan T
newRecv chan <-chan T
}
func NewBroadcastChannel() *BroadChannel {
bc := new(BroadChannel)
bc.Sender = make(chan T)
bc.newRecv = make(chan chan T)
return bc
}
func (b *BroadChannel) StartBroadcast() {
for {
select {
case v := <- b.Sender:
for c := range b.recievers {
go func() {c <- v}()
}
case nc := <- b.newRecv:
b.recievers = append(b.recievers, nc)
}
}
}
func (b *BroadChannel) GetReceiver() <-chan T {
nc := make(chan T)
b.newRecv <- nc
return nc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment