go-zero/core/syncx/atomicbool.go

45 lines
933 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import "sync/atomic"
2021-02-28 16:16:22 +08:00
// An AtomicBool is an atomic implementation for boolean values.
2020-07-26 17:09:05 +08:00
type AtomicBool uint32
2021-02-28 16:16:22 +08:00
// NewAtomicBool returns an AtomicBool.
2020-07-26 17:09:05 +08:00
func NewAtomicBool() *AtomicBool {
return new(AtomicBool)
}
2021-02-28 16:16:22 +08:00
// ForAtomicBool returns an AtomicBool with given val.
2020-07-26 17:09:05 +08:00
func ForAtomicBool(val bool) *AtomicBool {
b := NewAtomicBool()
b.Set(val)
return b
}
2021-02-28 16:16:22 +08:00
// CompareAndSwap compares current value with given old, if equals, set to given val.
2020-07-26 17:09:05 +08:00
func (b *AtomicBool) CompareAndSwap(old, val bool) bool {
var ov, nv uint32
if old {
ov = 1
}
if val {
nv = 1
}
return atomic.CompareAndSwapUint32((*uint32)(b), ov, nv)
}
2021-02-28 16:16:22 +08:00
// Set sets the value to v.
2020-07-26 17:09:05 +08:00
func (b *AtomicBool) Set(v bool) {
if v {
atomic.StoreUint32((*uint32)(b), 1)
} else {
atomic.StoreUint32((*uint32)(b), 0)
}
}
2021-02-28 16:16:22 +08:00
// True returns true if current value is true.
2020-07-26 17:09:05 +08:00
func (b *AtomicBool) True() bool {
return atomic.LoadUint32((*uint32)(b)) == 1
}