-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Closed as not planned
Labels
Milestone
Description
Issue
It would be useful to know whether a function protected by sync.Once has been run or not.
Example:
var once sync.Once
var timer *time.Timer
func reset(d time.Duration) {
done := false
once.Do(func() {
timer = time.AfterFunc(d, func() { ... })
done = true
})
if !done {
timer.Reset(d)
}
}
Proposal
The above code relies on making new variable and setting it in the closure. It could be more cleanly expressed if sync.Once.Do
return true
or false
depending on whether the function has run.
var once sync.Once
var timer *time.Timer
func reset(d time.Duration) {
if !once.Do(func() {
timer = time.AfterFunc(d, func() { ... })
}) {
timer.Reset(d)
}
}
package sync
...
func (o *Once) Do(f func()) bool {
if atomic.LoadUint32(&o.done) == 0 {
o.doSlow(f)
return true //
}
return false //
}
...