Skip to content

Commit

Permalink
Merge pull request #11 from gregorychen3/bugfix/prevent-possible-conc…
Browse files Browse the repository at this point in the history
…urrent-map-write

Bugfix/prevent possible concurrent map write
  • Loading branch information
luiccn authored Mar 22, 2021
2 parents eba92cf + cd8dfff commit c430c26
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions internal/espresso/temperature/temperature.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ type Sampler interface {
}

type Monitor struct {
subscriptionChans map[uuid.UUID]chan *Sample
subscriptionsMu sync.RWMutex
subscriptions map[uuid.UUID]chan *Sample

sampler Sampler
temperatureHistoryMu sync.RWMutex
Expand All @@ -29,8 +30,8 @@ type Monitor struct {

func NewMonitor(sampler Sampler, sampleRate time.Duration) *Monitor {
return &Monitor{
subscriptionChans: map[uuid.UUID]chan *Sample{},
sampler: sampler,
subscriptions: map[uuid.UUID]chan *Sample{},
sampler: sampler,
}
}

Expand All @@ -49,9 +50,11 @@ func (m *Monitor) Run() {
m.temperatureHistory = append(m.temperatureHistory, sample)
m.temperatureHistoryMu.Unlock()

for _, ch := range m.subscriptionChans {
m.subscriptionsMu.RLock()
for _, ch := range m.subscriptions {
ch <- sample
}
m.subscriptionsMu.RUnlock()

time.Sleep(time.Second)
}
Expand All @@ -75,14 +78,21 @@ func (m *Monitor) Run() {
}

func (m *Monitor) Subscribe() (uuid.UUID, chan *Sample) {
m.subscriptionsMu.Lock()
defer m.subscriptionsMu.Unlock()

subId := uuid.New()
subscriptionCh := make(chan *Sample)
m.subscriptionChans[subId] = subscriptionCh
m.subscriptions[subId] = subscriptionCh

return subId, subscriptionCh
}

func (m *Monitor) Unsubscribe(subId uuid.UUID) {
delete(m.subscriptionChans, subId)
m.subscriptionsMu.Lock()
defer m.subscriptionsMu.Unlock()

delete(m.subscriptions, subId)
}

func (m *Monitor) GetHistory() []*Sample {
Expand Down

0 comments on commit c430c26

Please sign in to comment.