forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atomicbool.go
44 lines (37 loc) · 933 Bytes
/
atomicbool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package syncx
import "sync/atomic"
// An AtomicBool is an atomic implementation for boolean values.
type AtomicBool uint32
// NewAtomicBool returns an AtomicBool.
func NewAtomicBool() *AtomicBool {
return new(AtomicBool)
}
// ForAtomicBool returns an AtomicBool with given val.
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.
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)
}
// Set sets the value to v.
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.
func (b *AtomicBool) True() bool {
return atomic.LoadUint32((*uint32)(b)) == 1
}