Skip to content

proposal: sync: sync.Once.Do return done #53485

@eNV25

Description

@eNV25

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 //
}
...

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions