github.com/lingyao2333/mo-zero@v1.4.1/core/syncx/atomicbool.go (about)

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