forked from flynn/flynn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.go
47 lines (39 loc) · 832 Bytes
/
watcher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import (
"sync"
"github.com/flynn/flynn/router/types"
)
type Watcher interface {
Watch(chan *router.Event)
Unwatch(chan *router.Event)
}
func NewWatchManager() *WatchManager {
return &WatchManager{watchers: make(map[chan *router.Event]struct{})}
}
type WatchManager struct {
mtx sync.RWMutex
watchers map[chan *router.Event]struct{}
}
func (m *WatchManager) Watch(ch chan *router.Event) {
m.mtx.Lock()
m.watchers[ch] = struct{}{}
m.mtx.Unlock()
}
func (m *WatchManager) Unwatch(ch chan *router.Event) {
go func() {
// drain channel so that we don't deadlock
for _ = range ch {
}
}()
m.mtx.Lock()
delete(m.watchers, ch)
m.mtx.Unlock()
close(ch)
}
func (m *WatchManager) Send(event *router.Event) {
m.mtx.RLock()
defer m.mtx.RUnlock()
for ch := range m.watchers {
ch <- event
}
}