github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xsync/xatomic/atomic_bool.go (about) 1 package xatomic 2 3 import ( 4 "sync/atomic" 5 ) 6 7 func boolToInt(b bool) uint32 { 8 if b { 9 return 1 10 } 11 return 0 12 } 13 14 func truthy(n uint32) bool { 15 return n&1 == 1 16 } 17 18 // AtomicBool is an atomic Boolean. 19 type AtomicBool struct{ v uint32 } 20 21 // NewAtomicBool creates a AtomicBool. 22 func NewAtomicBool(initial bool) *AtomicBool { 23 return &AtomicBool{boolToInt(initial)} 24 } 25 26 // Load atomically loads the Boolean. 27 func (b *AtomicBool) Load() bool { 28 return truthy(atomic.LoadUint32(&b.v)) 29 } 30 31 // CAS is an atomic compare-and-swap. 32 func (b *AtomicBool) CAS(old, new bool) bool { 33 return atomic.CompareAndSwapUint32(&b.v, boolToInt(old), boolToInt(new)) 34 } 35 36 // Store atomically stores the passed value. 37 func (b *AtomicBool) Store(new bool) { 38 atomic.StoreUint32(&b.v, boolToInt(new)) 39 } 40 41 // Swap sets the given value and returns the previous value. 42 func (b *AtomicBool) Swap(new bool) bool { 43 return truthy(atomic.SwapUint32(&b.v, boolToInt(new))) 44 } 45 46 // Toggle atomically negates the Boolean and returns the previous value. 47 func (b *AtomicBool) Toggle() bool { 48 return truthy(atomic.AddUint32(&b.v, 1) - 1) 49 }