Skip to content

Instantly share code, notes, and snippets.

@Shikugawa
Created August 19, 2020 15:04
Show Gist options
  • Save Shikugawa/8abcad578d559f8ce449914343a9bcf7 to your computer and use it in GitHub Desktop.
Save Shikugawa/8abcad578d559f8ce449914343a9bcf7 to your computer and use it in GitHub Desktop.
PubSub
package main
import (
"fmt"
"sync"
"time"
)
type PubSub struct {
mux sync.RWMutex
sub map[string][]chan string
}
func NewPubSub() *PubSub {
s := make(map[string][]chan string, 0)
ps := &PubSub{
sub: s,
}
return ps
}
func (ps *PubSub) Subscribe(topic string) chan string {
ps.mux.Lock()
defer ps.mux.Unlock()
ch := make(chan string, 1)
ps.sub[topic] = append(ps.sub[topic], ch)
return ch
}
func (ps *PubSub) Publish(topic string, message string) {
for _, ch := range ps.sub[topic] {
ch <- message
}
}
func main() {
ps := NewPubSub()
ch1 := ps.Subscribe("test")
ch2 := ps.Subscribe("test")
go func() {
for {
select {
case msg := <-ch1:
fmt.Println(msg + " to ch1")
case msg := <-ch2:
fmt.Println(msg + " to ch2")
}
}
}()
for {
ps.Publish("test", "sample")
time.Sleep(time.Second * 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment