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

proposal: sync: allow checking state of sync.Once (add Done()) #53649

Closed
0x1a8510f2 opened this issue Jul 1, 2022 · 2 comments
Closed

proposal: sync: allow checking state of sync.Once (add Done()) #53649

0x1a8510f2 opened this issue Jul 1, 2022 · 2 comments

Comments

@0x1a8510f2
Copy link

Example Code

This version waits for Do() to finish if it is currently executing:

func (o *Once) Done() bool {
	o.m.Lock()
	defer o.m.Unlock()

	return atomic.LoadUint32(&o.done) == 1
}

Note: Not tested

This version returns true if Do() is currently executing (probably not what we want to do):

func (o *Once) Done() bool {
	if o.m.TryLock() {
		defer o.m.Unlock()
		return atomic.LoadUint32(&o.done) == 1
	}
	return false
}

Note: Not tested

Reason

I sometimes find myself needing to check if a goroutine which executes a sync.Once.Do() has done so yet. This could be done with channels or a separate variable but that can introduce a lot of unnecessary boilerplate. Not to mention that this means we're storing the same state twice which, depending on the code, could possibly get out of sync (ironically, given the package we're dealing with).

@gopherbot gopherbot added this to the Proposal milestone Jul 1, 2022
@ianlancetaylor
Copy link
Contributor

Personally I feel like sync.Once does one job. No need to have it do another job. The implementation is less than 100 lines of well commented code; it would be simple to copy it and modify it for your needs.

@ianlancetaylor ianlancetaylor added this to Incoming in Proposals (old) Jul 1, 2022
@seankhliao
Copy link
Member

Duplicate of #41690

@seankhliao seankhliao marked this as a duplicate of #41690 Jul 1, 2022
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Jul 1, 2022
@ianlancetaylor ianlancetaylor removed this from Incoming in Proposals (old) Jul 1, 2022
@golang golang locked and limited conversation to collaborators Jul 1, 2023
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