2016-06-01 13:38:57 +03:00
|
|
|
// Package abool provides atomic Boolean type for cleaner code and
|
2016-05-25 07:06:29 +03:00
|
|
|
// better performance.
|
2016-05-25 06:42:19 +03:00
|
|
|
package abool
|
|
|
|
|
|
|
|
import "sync/atomic"
|
|
|
|
|
2016-05-25 10:06:49 +03:00
|
|
|
// New creates an AtomicBool with default to false
|
2016-05-25 06:42:19 +03:00
|
|
|
func New() *AtomicBool {
|
|
|
|
return new(AtomicBool)
|
|
|
|
}
|
|
|
|
|
2016-05-25 10:06:49 +03:00
|
|
|
// NewBool creates an AtomicBool with given default value
|
|
|
|
func NewBool(ok bool) *AtomicBool {
|
|
|
|
ab := New()
|
|
|
|
if ok {
|
|
|
|
ab.Set()
|
|
|
|
}
|
|
|
|
return ab
|
|
|
|
}
|
|
|
|
|
2016-06-02 06:48:02 +03:00
|
|
|
// AtomicBool is an atomic Boolean
|
|
|
|
// Its methods are all atomic, thus safe to be called by
|
|
|
|
// multiple goroutines simultaneously
|
2016-05-25 06:42:19 +03:00
|
|
|
// Note: When embedding into a struct, one should always use
|
|
|
|
// *AtomicBool to avoid copy
|
|
|
|
type AtomicBool int32
|
|
|
|
|
2016-06-02 06:48:02 +03:00
|
|
|
// Set sets the Boolean to true
|
2016-05-25 06:42:19 +03:00
|
|
|
func (ab *AtomicBool) Set() {
|
|
|
|
atomic.StoreInt32((*int32)(ab), 1)
|
|
|
|
}
|
|
|
|
|
2016-06-02 06:48:02 +03:00
|
|
|
// UnSet sets the Boolean to false
|
2016-05-25 06:42:19 +03:00
|
|
|
func (ab *AtomicBool) UnSet() {
|
|
|
|
atomic.StoreInt32((*int32)(ab), 0)
|
|
|
|
}
|
|
|
|
|
2016-06-02 06:48:02 +03:00
|
|
|
// IsSet returns whether the Boolean is true
|
2016-05-25 06:42:19 +03:00
|
|
|
func (ab *AtomicBool) IsSet() bool {
|
|
|
|
return atomic.LoadInt32((*int32)(ab)) == 1
|
|
|
|
}
|
2016-05-25 09:57:10 +03:00
|
|
|
|
2016-06-02 06:48:02 +03:00
|
|
|
// SetTo sets the boolean with given Boolean
|
2016-05-25 09:57:10 +03:00
|
|
|
func (ab *AtomicBool) SetTo(yes bool) {
|
|
|
|
if yes {
|
|
|
|
atomic.StoreInt32((*int32)(ab), 1)
|
|
|
|
} else {
|
|
|
|
atomic.StoreInt32((*int32)(ab), 0)
|
|
|
|
}
|
|
|
|
}
|
2016-06-02 06:47:41 +03:00
|
|
|
|
|
|
|
// SetToIf sets the Boolean to new only if the Boolean matches the old
|
|
|
|
// Returns whether the set was done
|
|
|
|
func (ab *AtomicBool) SetToIf(old, new bool) (set bool) {
|
|
|
|
var o, n int32
|
|
|
|
if old {
|
|
|
|
o = 1
|
|
|
|
}
|
|
|
|
if new {
|
|
|
|
n = 1
|
|
|
|
}
|
|
|
|
return atomic.CompareAndSwapInt32((*int32)(ab), o, n)
|
|
|
|
}
|