Created
April 12, 2014 10:39
-
-
Save davidmz/10529299 to your computer and use it in GitHub Desktop.
Простой броадкастер на 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
package bcast | |
type Broadcaster interface { | |
// Неблокирующая отправка сообщения | |
Send(interface{}) | |
// Блокирующее получение одного сообщения | |
Fetch() interface{} | |
} | |
type bcaster struct { | |
in chan interface{} | |
listeners chan chan interface{} | |
} | |
func NewBroadcaster() Broadcaster { | |
b := &bcaster{ | |
in: make(chan interface{}), | |
listeners: make(chan chan interface{}), | |
} | |
go b.run() | |
return b | |
} | |
func (b *bcaster) Send(v interface{}) { | |
go func() { b.in <- v }() | |
} | |
func (b *bcaster) Fetch() interface{} { | |
ch := make(chan interface{}) | |
b.listeners <- ch | |
v := <-ch | |
close(ch) | |
return v | |
} | |
func (b *bcaster) run() { | |
for { | |
v := <-b.in | |
loop: | |
for { | |
select { | |
case ch := <-b.listeners: | |
go func() { ch <- v }() | |
default: | |
break loop | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment