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
}
gabyhelp commented
Related Issues
- proposal: sync: allow checking state of sync.Once (add `Done()`) #53649 (closed)
- proposal: sync: sync.Once.Do return done #53485 (closed)
- proposal: sync: add Done() bool method to sync.Once #41690 (closed)
- proposal: sync: add a HasRun method to sync.Once #19245 (closed)
- proposal: sync: Add Once.Try #53696 (closed)
- sync: Once uses, but doesn't need atomic operations #22104 (closed)
- Fine-tune sync.Once #16914 (closed)
- sync: return true from the last WaitGroup.Done #7019 (closed)
- proposal: sync: add blocking methods with Context parameter to Once and WaitGroup #25312 (closed)
- sync: merge defers in once.doSlow #38320 (closed)
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)