From b2702de4b1927e8982b51640f096b14f8ddfa026 Mon Sep 17 00:00:00 2001 From: Prabhav Dogra <55079966+prabhavdogra@users.noreply.github.com> Date: Sun, 20 Apr 2025 10:42:43 +0530 Subject: [PATCH 1/2] sync: use atomic.Bool for Once.done --- src/sync/once.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sync/once.go b/src/sync/once.go index 90840b19b5e705..1573b28b28a463 100644 --- a/src/sync/once.go +++ b/src/sync/once.go @@ -25,7 +25,7 @@ type Once struct { // The hot path is inlined at every call site. // Placing done first allows more compact instructions on some architectures (amd64/386), // and fewer instructions (to calculate offset) on other architectures. - done atomic.Uint32 + done atomic.Bool m Mutex } @@ -64,7 +64,7 @@ func (o *Once) Do(f func()) { // This is why the slow path falls back to a mutex, and why // the o.done.Store must be delayed until after f returns. - if o.done.Load() == 0 { + if !o.done.Load() { // Outlined slow-path to allow inlining of the fast-path. o.doSlow(f) } @@ -73,8 +73,8 @@ func (o *Once) Do(f func()) { func (o *Once) doSlow(f func()) { o.m.Lock() defer o.m.Unlock() - if o.done.Load() == 0 { - defer o.done.Store(1) + if !o.done.Load() { + defer o.done.Store(true) f() } } From d36e0f431fcde988f90badf86bbf04a18a411947 Mon Sep 17 00:00:00 2001 From: Prabhav Dogra Date: Sun, 20 Apr 2025 13:12:50 +0530 Subject: [PATCH 2/2] Updated tests --- test/inline_sync.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/inline_sync.go b/test/inline_sync.go index eaa2176d5fdc3d..8359aa3aa22cd2 100644 --- a/test/inline_sync.go +++ b/test/inline_sync.go @@ -37,7 +37,7 @@ var once *sync.Once func small7() { // ERROR "can inline small7" // the Do fast path should be inlined - once.Do(small5) // ERROR "inlining call to sync\.\(\*Once\)\.Do" "inlining call to atomic\.\(\*Uint32\)\.Load" + once.Do(small5) // ERROR "inlining call to sync\.\(\*Once\)\.Do" "inlining call to atomic\.\(\*Bool\)\.Load" } var rwmutex *sync.RWMutex