You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/syncx/atomicbool.go

47 lines
935 B
Go

4 years ago
package syncx
import "sync/atomic"
// An AtomicBool is an atomic implementation for boolean values.
4 years ago
type AtomicBool uint32
// NewAtomicBool returns an AtomicBool.
4 years ago
func NewAtomicBool() *AtomicBool {
return new(AtomicBool)
}
// ForAtomicBool returns an AtomicBool with given val.
4 years ago
func ForAtomicBool(val bool) *AtomicBool {
b := NewAtomicBool()
b.Set(val)
return b
}
// CompareAndSwap compares current value with given old, if equals, set to given val.
4 years ago
func (b *AtomicBool) CompareAndSwap(old, val bool) bool {
var ov, nv uint32
4 years ago
if old {
ov = 1
}
if val {
nv = 1
}
4 years ago
return atomic.CompareAndSwapUint32((*uint32)(b), ov, nv)
}
// Set sets the value to v.
4 years ago
func (b *AtomicBool) Set(v bool) {
if v {
atomic.StoreUint32((*uint32)(b), 1)
} else {
atomic.StoreUint32((*uint32)(b), 0)
}
}
// True returns true if current value is true.
4 years ago
func (b *AtomicBool) True() bool {
return atomic.LoadUint32((*uint32)(b)) == 1
}