cli/command/container: use RWMutex for stats to allow concurrent reads

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2022-03-28 11:29:06 +02:00
parent 34dd43bf1b
commit a2e9ed3b87
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
3 changed files with 10 additions and 10 deletions

View File

@ -43,7 +43,7 @@ type StatsEntry struct {
// Stats represents an entity to store containers statistics synchronously // Stats represents an entity to store containers statistics synchronously
type Stats struct { type Stats struct {
mutex sync.Mutex mutex sync.RWMutex
StatsEntry StatsEntry
err error err error
} }
@ -51,8 +51,8 @@ type Stats struct {
// GetError returns the container statistics error. // GetError returns the container statistics error.
// This is used to determine whether the statistics are valid or not // This is used to determine whether the statistics are valid or not
func (cs *Stats) GetError() error { func (cs *Stats) GetError() error {
cs.mutex.Lock() cs.mutex.RLock()
defer cs.mutex.Unlock() defer cs.mutex.RUnlock()
return cs.err return cs.err
} }
@ -94,8 +94,8 @@ func (cs *Stats) SetStatistics(s StatsEntry) {
// GetStatistics returns container statistics with other meta data such as the container name // GetStatistics returns container statistics with other meta data such as the container name
func (cs *Stats) GetStatistics() StatsEntry { func (cs *Stats) GetStatistics() StatsEntry {
cs.mutex.Lock() cs.mutex.RLock()
defer cs.mutex.Unlock() defer cs.mutex.RUnlock()
return cs.StatsEntry return cs.StatsEntry
} }

View File

@ -184,13 +184,13 @@ func runStats(dockerCli command.Cli, opts *statsOptions) error {
waitFirst.Wait() waitFirst.Wait()
var errs []string var errs []string
cStats.mu.Lock() cStats.mu.RLock()
for _, c := range cStats.cs { for _, c := range cStats.cs {
if err := c.GetError(); err != nil { if err := c.GetError(); err != nil {
errs = append(errs, err.Error()) errs = append(errs, err.Error())
} }
} }
cStats.mu.Unlock() cStats.mu.RUnlock()
if len(errs) > 0 { if len(errs) > 0 {
return errors.New(strings.Join(errs, "\n")) return errors.New(strings.Join(errs, "\n"))
} }
@ -221,11 +221,11 @@ func runStats(dockerCli command.Cli, opts *statsOptions) error {
for range ticker.C { for range ticker.C {
cleanScreen() cleanScreen()
ccstats := []StatsEntry{} ccstats := []StatsEntry{}
cStats.mu.Lock() cStats.mu.RLock()
for _, c := range cStats.cs { for _, c := range cStats.cs {
ccstats = append(ccstats, c.GetStatistics()) ccstats = append(ccstats, c.GetStatistics())
} }
cStats.mu.Unlock() cStats.mu.RUnlock()
if err = statsFormatWrite(statsCtx, ccstats, daemonOSType, !opts.noTrunc); err != nil { if err = statsFormatWrite(statsCtx, ccstats, daemonOSType, !opts.noTrunc); err != nil {
break break
} }

View File

@ -14,7 +14,7 @@ import (
) )
type stats struct { type stats struct {
mu sync.Mutex mu sync.RWMutex
cs []*Stats cs []*Stats
} }