-
Notifications
You must be signed in to change notification settings - Fork 1
/
atomic-bool.go
48 lines (39 loc) · 1.17 KB
/
atomic-bool.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
45
46
47
48
/*
© 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
ISC License
*/
package parl
import "sync/atomic"
/*
AtomicBool is a thread-safe flag.
AtomicBool requires no initialization
var isDone parl.AtomicBool
if isDone.Set() // isDone was not set, but is set now
…
if !isDone.IsTrue() // isDone is not set
*/
type AtomicBool struct {
value int32 // atomic
}
const (
abTrue = int32(1)
abFalse = int32(0)
)
// IsTrue returns the flag’s current bool value. thread-safe
func (ab *AtomicBool) IsTrue() (isTrue bool) {
return atomic.LoadInt32(&ab.value) == abTrue
}
// IsFalse returns the flag’s current bool value. thread-safe
func (ab *AtomicBool) IsFalse() (isFalse bool) {
return atomic.LoadInt32(&ab.value) == abFalse
}
// Set sets the flag to true and returns true if the flag was not already true.
// thread-safe
func (ab *AtomicBool) Set() (wasNotSet bool) {
return atomic.SwapInt32(&ab.value, abTrue) != abTrue
}
// Clear sets the flag to false and returns true if the flag was not already false.
// thread-safe
func (ab *AtomicBool) Clear() (wasSet bool) {
return atomic.SwapInt32(&ab.value, abFalse) == abTrue
}