Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sync.Once: Why don't use uint8 instead of uint32 to avoid using atomic #31101

Closed
anjiawei1991 opened this issue Mar 28, 2019 · 3 comments
Closed

Comments

@anjiawei1991
Copy link

anjiawei1991 commented Mar 28, 2019

func (o *Once) Do(f func()) {
	if atomic.LoadUint32(&o.done) == 0 {
		// Outlined slow-path to allow inlining of the fast-path.
		o.doSlow(f)
	}
}

func (o *Once) doSlow(f func()) {
	o.m.Lock()
	defer o.m.Unlock()
	if o.done == 0 {
		defer atomic.StoreUint32(&o.done, 1)
		f()
	}
}

I guess the atomic here is for the data integrety (won't read half-writed done) , especially on lower than 32-bits machines.

but why don't use uint8 to avoid using atomic, and that can improve performance.

like:

type Once struct {
	done uint8
	m    Mutex
}

func (o *Once) Do(f func()) {
	if o.done == 0 {
		// Outlined slow-path to allow inlining of the fast-path.
		o.doSlow(f)
	}
}

func (o *Once) doSlow(f func()) {
	o.m.Lock()
	defer o.m.Unlock()
	if o.done == 0 {
		defer func(){o.done=1}
		f()
	}
}
@anjiawei1991
Copy link
Author

@dvyukov

@dvyukov
Copy link
Member

dvyukov commented Mar 28, 2019

Besides atomicity we also need need ordering and visibility:
http://www.1024cores.net/home/lock-free-algorithms/so-what-is-a-memory-model-and-how-to-cook-it
Plain memory accesses won't provide these properties, besides races being formally undefined behavior:
https://software.intel.com/en-us/blogs/2013/01/06/benign-data-races-what-could-possibly-go-wrong

@martisch
Copy link
Contributor

As was answered atomic functions provide additional needed properties beyond data integrity.

For asking questions please see https://golang.org/wiki/Questions.

@golang golang locked and limited conversation to collaborators Mar 27, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants