Created
May 19, 2013 18:25
-
-
Save whyrusleeping/5608502 to your computer and use it in GitHub Desktop.
Broadcast Channel for go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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