From 861d094757551d2f65d1003f0ec93bc92b254a5a Mon Sep 17 00:00:00 2001 From: chressie Date: Thu, 4 Apr 2024 16:07:42 +0200 Subject: [PATCH] glog: don't hold mutex when sync'ing (#68) Some environments are slow when syncing and holding the lock might cause contention. cl/621846576 (google-internal) --- glog_file.go | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/glog_file.go b/glog_file.go index e7d125c5..a1551dbc 100644 --- a/glog_file.go +++ b/glog_file.go @@ -369,9 +369,6 @@ func (s *fileSink) Flush() error { // flush flushes all logs of severity threshold or greater. func (s *fileSink) flush(threshold logsink.Severity) error { - s.mu.Lock() - defer s.mu.Unlock() - var firstErr error updateErr := func(err error) { if err != nil && firstErr == nil { @@ -379,13 +376,23 @@ func (s *fileSink) flush(threshold logsink.Severity) error { } } - // Flush from fatal down, in case there's trouble flushing. - for sev := logsink.Fatal; sev >= threshold; sev-- { - file := s.file[sev] - if file != nil { - updateErr(file.Flush()) - updateErr(file.Sync()) + // Remember where we flushed, so we can call sync without holding + // the lock. + var files []flushSyncWriter + func() { + s.mu.Lock() + defer s.mu.Unlock() + // Flush from fatal down, in case there's trouble flushing. + for sev := logsink.Fatal; sev >= threshold; sev-- { + if file := s.file[sev]; file != nil { + updateErr(file.Flush()) + files = append(files, file) + } } + }() + + for _, file := range files { + updateErr(file.Sync()) } return firstErr