Skip to content

Commit 0b1c7bc

Browse files
committed
cli/command/container: RunStats: small tweaks on closeChan
Some suggestions from ChatGPT to prevent deadlocks. Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent d309027 commit 0b1c7bc

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

cli/command/container/stats.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,10 @@ func RunStats(ctx context.Context, dockerCLI command.Cli, options *StatsOptions)
113113

114114
// waitFirst is a WaitGroup to wait first stat data's reach for each container
115115
waitFirst := &sync.WaitGroup{}
116-
// closeChan is a non-buffered channel used to collect errors from goroutines.
117-
closeChan := make(chan error)
116+
// closeChan is used to collect errors from goroutines. It uses a small buffer
117+
// to avoid blocking sends when sends occur after closeChan is set to nil or
118+
// after the reader has exited, preventing deadlocks.
119+
closeChan := make(chan error, 4)
118120
cStats := stats{}
119121

120122
showAll := len(options.Containers) == 0
@@ -197,7 +199,12 @@ func RunStats(ctx context.Context, dockerCLI command.Cli, options *StatsOptions)
197199
case event := <-eventChan:
198200
c <- event
199201
case err := <-errChan:
200-
closeChan <- err
202+
// Prevent blocking if closeChan is full or unread
203+
select {
204+
case closeChan <- err:
205+
default:
206+
// drop if not read; avoids deadlock
207+
}
201208
return
202209
}
203210
}

0 commit comments

Comments
 (0)