bool.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Package abool provides atomic Boolean type for cleaner code and
  2. // better performance.
  3. package abool
  4. import "sync/atomic"
  5. // New creates an AtomicBool with default to false
  6. func New() *AtomicBool {
  7. return new(AtomicBool)
  8. }
  9. // NewBool creates an AtomicBool with given default value
  10. func NewBool(ok bool) *AtomicBool {
  11. ab := New()
  12. if ok {
  13. ab.Set()
  14. }
  15. return ab
  16. }
  17. // AtomicBool is an atomic Boolean
  18. // Its methods are all atomic, thus safe to be called by
  19. // multiple goroutines simultaneously
  20. // Note: When embedding into a struct, one should always use
  21. // *AtomicBool to avoid copy
  22. type AtomicBool int32
  23. // Set sets the Boolean to true
  24. func (ab *AtomicBool) Set() {
  25. atomic.StoreInt32((*int32)(ab), 1)
  26. }
  27. // UnSet sets the Boolean to false
  28. func (ab *AtomicBool) UnSet() {
  29. atomic.StoreInt32((*int32)(ab), 0)
  30. }
  31. // IsSet returns whether the Boolean is true
  32. func (ab *AtomicBool) IsSet() bool {
  33. return atomic.LoadInt32((*int32)(ab)) == 1
  34. }
  35. // SetTo sets the boolean with given Boolean
  36. func (ab *AtomicBool) SetTo(yes bool) {
  37. if yes {
  38. atomic.StoreInt32((*int32)(ab), 1)
  39. } else {
  40. atomic.StoreInt32((*int32)(ab), 0)
  41. }
  42. }
  43. // SetToIf sets the Boolean to new only if the Boolean matches the old
  44. // Returns whether the set was done
  45. func (ab *AtomicBool) SetToIf(old, new bool) (set bool) {
  46. var o, n int32
  47. if old {
  48. o = 1
  49. }
  50. if new {
  51. n = 1
  52. }
  53. return atomic.CompareAndSwapInt32((*int32)(ab), o, n)
  54. }