You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
838 B

  1. package sync
  2. import "sync/atomic"
  3. // AtomicBool is an atomic Boolean.
  4. // Its methods are all atomic, thus safe to be called by multiple goroutines simultaneously.
  5. // Note: When embedding into a struct one should always use *AtomicBool to avoid copy.
  6. // it's a simple implmentation from https://github.com/tevino/abool
  7. type AtomicBool int32
  8. // NewBool creates an AtomicBool with given default value.
  9. func NewBool(ok bool) *AtomicBool {
  10. ab := new(AtomicBool)
  11. if ok {
  12. ab.Set()
  13. }
  14. return ab
  15. }
  16. // Set sets the Boolean to true.
  17. func (ab *AtomicBool) Set() {
  18. atomic.StoreInt32((*int32)(ab), 1)
  19. }
  20. // UnSet sets the Boolean to false.
  21. func (ab *AtomicBool) UnSet() {
  22. atomic.StoreInt32((*int32)(ab), 0)
  23. }
  24. // IsSet returns whether the Boolean is true.
  25. func (ab *AtomicBool) IsSet() bool {
  26. return atomic.LoadInt32((*int32)(ab))&1 == 1
  27. }