Skip to content

Commit 1416501

Browse files
committed
sync: use atomic.Uint32 in Once
1 parent 36ecff0 commit 1416501

File tree

2 files changed

+7
-7
lines changed

2 files changed

+7
-7
lines changed

src/sync/once.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ type Once struct {
2121
// The hot path is inlined at every call site.
2222
// Placing done first allows more compact instructions on some architectures (amd64/386),
2323
// and fewer instructions (to calculate offset) on other architectures.
24-
done uint32
24+
done atomic.Uint32
2525
m Mutex
2626
}
2727

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

63-
if atomic.LoadUint32(&o.done) == 0 {
63+
if o.done.Load() == 0 {
6464
// Outlined slow-path to allow inlining of the fast-path.
6565
o.doSlow(f)
6666
}
@@ -69,8 +69,8 @@ func (o *Once) Do(f func()) {
6969
func (o *Once) doSlow(f func()) {
7070
o.m.Lock()
7171
defer o.m.Unlock()
72-
if o.done == 0 {
73-
defer atomic.StoreUint32(&o.done, 1)
72+
if o.done.Load() == 0 {
73+
defer o.done.Store(1)
7474
f()
7575
}
7676
}

test/inline_sync.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ var once *sync.Once
3737

3838
func small7() { // ERROR "can inline small7"
3939
// the Do fast path should be inlined
40-
once.Do(small5) // ERROR "inlining call to sync\.\(\*Once\)\.Do"
40+
once.Do(small5) // ERROR "inlining call to sync\.\(\*Once\)\.Do" "inlining call to atomic\.\(\*Uint32\)\.Load"
4141
}
4242

4343
var rwmutex *sync.RWMutex

0 commit comments

Comments
 (0)