Skip to content

Instantly share code, notes, and snippets.

@algogrit
Created December 14, 2019 17:41
Show Gist options
  • Save algogrit/e3bf3a86df9957792a8594a4834d13b7 to your computer and use it in GitHub Desktop.
Save algogrit/e3bf3a86df9957792a8594a4834d13b7 to your computer and use it in GitHub Desktop.
#ChnGoTurns10
package main
import (
"fmt"
"sync"
"time"
)
type Subscriber func(int)
type PubSub struct {
ch chan int
Subscribers []Subscriber
subscriberMutex sync.RWMutex
}
func (p *PubSub) Publish(val int) {
p.ch <- val
fmt.Println("DEBUG: Publishing - ", val)
}
func (p *PubSub) Subscribe(s Subscriber) {
p.subscriberMutex.Lock()
p.Subscribers = append(p.Subscribers, s)
p.subscriberMutex.Unlock()
}
func NewPubSub() *PubSub {
var pubSub PubSub
pubSub.ch = make(chan int)
go func() {
for {
val := <-pubSub.ch
fmt.Println("DEBUG: Notifying subscribers - ", val)
pubSub.subscriberMutex.RLock()
for _, subscriber := range pubSub.Subscribers {
subscriber(val)
}
pubSub.subscriberMutex.RUnlock()
}
}()
return &pubSub
}
func main() {
p := NewPubSub()
p.Subscribe(func(val int) {
fmt.Println("Multiplier: ", val*10)
})
go p.Publish(42) // Independent
// go p.Publish(52)
// go p.Publish(62)
for i := 1; i <= 10; i++ {
k := i
p.Subscribe(func(val int) {
fmt.Println("Adder: ", val+k)
})
}
p.Publish(100)
time.Sleep(1 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment