atomicbool.go 885 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package atomic
  2. import (
  3. "sync/atomic"
  4. )
  5. // AtomicBool alias leverages a 32-bit integer CAS
  6. type AtomicBool int32
  7. // NewAtomicBool creates an AtomicBool with given default value
  8. func NewAtomicBool(value bool) *AtomicBool {
  9. ab := new(AtomicBool)
  10. ab.Set(value)
  11. return ab
  12. }
  13. // Loads the bool value atomically
  14. func (ab *AtomicBool) Get() bool {
  15. return atomic.LoadInt32((*int32)(ab)) != 0
  16. }
  17. // Sets the bool value atomically
  18. func (ab *AtomicBool) Set(value bool) {
  19. if value {
  20. atomic.StoreInt32((*int32)(ab), 1)
  21. } else {
  22. atomic.StoreInt32((*int32)(ab), 0)
  23. }
  24. }
  25. // CompareAndSet sets value to new if current is equal to the current value. If the new value is
  26. // set, this function returns true.
  27. func (ab *AtomicBool) CompareAndSet(current, new bool) bool {
  28. var o, n int32
  29. if current {
  30. o = 1
  31. }
  32. if new {
  33. n = 1
  34. }
  35. return atomic.CompareAndSwapInt32((*int32)(ab), o, n)
  36. }