Skip to content

Commit

Permalink
sync: use atomic.Uint32 in Once
Browse files Browse the repository at this point in the history
Change-Id: If9089f8afd78de3e62cd575f642ff96ab69e2099
GitHub-Last-Rev: 1416501
GitHub-Pull-Request: #63386
Reviewed-on: https://go-review.googlesource.com/c/go/+/532895
Auto-Submit: Ian Lance Taylor <[email protected]>
Reviewed-by: Jorropo <[email protected]>
LUCI-TryBot-Result: Go LUCI <[email protected]>
Reviewed-by: Ian Lance Taylor <[email protected]>
Reviewed-by: Michael Pratt <[email protected]>
Auto-Submit: Michael Pratt <[email protected]>
  • Loading branch information
mstmdev authored and pull[bot] committed Feb 1, 2024
1 parent 73150de commit f1215c5
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
12 changes: 6 additions & 6 deletions src/sync/once.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,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 uint32
done atomic.Uint32
m Mutex
}

Expand All @@ -48,7 +48,7 @@ type Once struct {
func (o *Once) Do(f func()) {
// Note: Here is an incorrect implementation of Do:
//
// if atomic.CompareAndSwapUint32(&o.done, 0, 1) {
// if o.done.CompareAndSwap(0, 1) {
// f()
// }
//
Expand All @@ -58,9 +58,9 @@ func (o *Once) Do(f func()) {
// call f, and the second would return immediately, without
// waiting for the first's call to f to complete.
// This is why the slow path falls back to a mutex, and why
// the atomic.StoreUint32 must be delayed until after f returns.
// the o.done.Store must be delayed until after f returns.

if atomic.LoadUint32(&o.done) == 0 {
if o.done.Load() == 0 {
// Outlined slow-path to allow inlining of the fast-path.
o.doSlow(f)
}
Expand All @@ -69,8 +69,8 @@ func (o *Once) Do(f func()) {
func (o *Once) doSlow(f func()) {
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
if o.done.Load() == 0 {
defer o.done.Store(1)
f()
}
}
2 changes: 1 addition & 1 deletion test/inline_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
once.Do(small5) // ERROR "inlining call to sync\.\(\*Once\)\.Do" "inlining call to atomic\.\(\*Uint32\)\.Load"
}

var rwmutex *sync.RWMutex
Expand Down

0 comments on commit f1215c5

Please sign in to comment.