Skip to content
Permalink
Browse files

Use defer for locks. Move to Prev() in All()

License: MIT
Signed-off-by: Hector Sanjuan <code@hector.link>
  • Loading branch information...
hsanjuan authored and lanzafame committed Mar 21, 2019
1 parent da3c543 commit 4e619353791658f512950022d73ebb8ba90401f0
Showing with 10 additions and 6 deletions.
  1. +10 −6 monitor/metrics/window.go
@@ -48,22 +48,24 @@ func (mw *Window) Add(m *api.Metric) {
m.ReceivedAt = time.Now().UnixNano()

mw.wMu.Lock()
defer mw.wMu.Unlock()

mw.window = mw.window.Next()
mw.window.Value = m
mw.wMu.Unlock()
return
}

// Latest returns the last metric added. It returns an error
// if no metrics were added.
func (mw *Window) Latest() (*api.Metric, error) {
mw.wMu.RLock()
defer mw.wMu.RUnlock()

var last *api.Metric
var ok bool
if last, ok = mw.window.Value.(*api.Metric); !ok || last == nil {
return nil, ErrNoMetrics
}
mw.wMu.RUnlock()

return last, nil
}

@@ -72,19 +74,21 @@ func (mw *Window) Latest() (*api.Metric, error) {
// metric.
func (mw *Window) All() []*api.Metric {
mw.wMu.Lock()
defer mw.wMu.Unlock()

// get to position so window.Do starts on the correct value
mw.window = mw.window.Next()
mw.wMu.Unlock()

mw.wMu.RLock()
values := make([]*api.Metric, 0, mw.window.Len())
mw.window.Do(func(v interface{}) {
if i, ok := v.(*api.Metric); ok {
// append younger values to older value
values = append([]*api.Metric{i}, values...)
}
})
mw.wMu.RUnlock()

// return to previous pos
mw.window = mw.window.Prev()
return values
}

0 comments on commit 4e61935

Please sign in to comment.
You can’t perform that action at this time.