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
Related Issues
- proposal: sync/atomic: add logical operations #31748 (closed)
- proposal: sync/atomic: Add atomic work with "int", "uint" type. #54168 (closed)
- Should sync/atomic support bitwise operations? #24244 (closed)
- sync/atomic: add Exchange operation #5722 (closed)
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
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