atomicbool.go 933 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package syncx
  2. import "sync/atomic"
  3. // An AtomicBool is an atomic implementation for boolean values.
  4. type AtomicBool uint32
  5. // NewAtomicBool returns an AtomicBool.
  6. func NewAtomicBool() *AtomicBool {
  7. return new(AtomicBool)
  8. }
  9. // ForAtomicBool returns an AtomicBool with given val.
  10. func ForAtomicBool(val bool) *AtomicBool {
  11. b := NewAtomicBool()
  12. b.Set(val)
  13. return b
  14. }
  15. // CompareAndSwap compares current value with given old, if equals, set to given val.
  16. func (b *AtomicBool) CompareAndSwap(old, val bool) bool {
  17. var ov, nv uint32
  18. if old {
  19. ov = 1
  20. }
  21. if val {
  22. nv = 1
  23. }
  24. return atomic.CompareAndSwapUint32((*uint32)(b), ov, nv)
  25. }
  26. // Set sets the value to v.
  27. func (b *AtomicBool) Set(v bool) {
  28. if v {
  29. atomic.StoreUint32((*uint32)(b), 1)
  30. } else {
  31. atomic.StoreUint32((*uint32)(b), 0)
  32. }
  33. }
  34. // True returns true if current value is true.
  35. func (b *AtomicBool) True() bool {
  36. return atomic.LoadUint32((*uint32)(b)) == 1
  37. }