golang/go

sync/once: add new function done

Closed this issue · 1 comments

dxasu commented

Proposal Details

Sometimes we need to understand the internal state of once, specifically whether it has already been executed.
In the implementation of AfterFunc in context/context.go, once is used to determine if it has already been executed, it is rather complicated.
It is recommended to add one of the following two functions to check if Once has been executed, to improve performance and readability.

// Add a function to `IsDone` to check if `Once` has been executed
func (o *Once) IsDone() bool {
	return o.done.Load() == 1
}
// Use the return value of `DoWithReturn` to check if `Once` has been executed
func (o *Once) DoWithReturn(f func()) bool {
	if o.done.Load() == 0 {
		o.doSlow(f)
		return true
	}
	return false
}