golang/go

proposal: sync/atomic: Add method Toggle() to atomic.Bool

Closed this issue · 3 comments

Proposal Details

This method can flip an atomic bool if needed, Can be very useful when implementing a function similar to a button switch(click the button and turn on/off the light). And the existing atomic bool provide too few methods as an independent type
Function signature is like func (x *atomic.Bool) Toggle() (new bool)

for now, this can be done in this way

func Toggle(atomicBool *atomic.Bool) (new bool) {
	var b bool
	for {
		b = atomicBool.Load()
		if atomicBool.CompareAndSwap(b, !b) {
			break
		}
	}
	return !b
}

But in the lib, this can be done by a simple XOR 1

What examples of real code is there that needs this?
Toggle isn't exactly a fundamental operation on bool.
Do the necessary instructions exist for the architectures we support?

What examples of real code is there that needs this? Toggle isn't exactly a fundamental operation on bool. Do the necessary instructions exist for the architectures we support?

Yes, not by non-x86, sorry