2015-01-12 03:56:17 +00:00
|
|
|
package util
|
2015-01-01 19:49:30 +00:00
|
|
|
|
2020-03-29 16:42:58 +00:00
|
|
|
import (
|
|
|
|
"sync/atomic"
|
|
|
|
)
|
|
|
|
|
|
|
|
func convertBoolToInt32(b bool) int32 {
|
|
|
|
if b {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
2015-01-01 19:49:30 +00:00
|
|
|
|
2015-01-11 18:01:24 +00:00
|
|
|
// AtomicBool is a boxed-class that provides synchronized access to the
|
|
|
|
// underlying boolean value
|
2015-01-01 19:49:30 +00:00
|
|
|
type AtomicBool struct {
|
2020-03-29 16:42:58 +00:00
|
|
|
state int32 // "1" is true, "0" is false
|
2015-01-01 19:49:30 +00:00
|
|
|
}
|
|
|
|
|
2015-01-11 18:01:24 +00:00
|
|
|
// NewAtomicBool returns a new AtomicBool
|
2015-01-01 19:49:30 +00:00
|
|
|
func NewAtomicBool(initialState bool) *AtomicBool {
|
2020-03-29 16:42:58 +00:00
|
|
|
return &AtomicBool{state: convertBoolToInt32(initialState)}
|
2015-01-01 19:49:30 +00:00
|
|
|
}
|
|
|
|
|
2015-01-11 18:01:24 +00:00
|
|
|
// Get returns the current boolean value synchronously
|
2015-01-01 19:49:30 +00:00
|
|
|
func (a *AtomicBool) Get() bool {
|
2020-03-29 16:42:58 +00:00
|
|
|
return atomic.LoadInt32(&a.state) == 1
|
2015-01-01 19:49:30 +00:00
|
|
|
}
|
|
|
|
|
2015-01-11 18:01:24 +00:00
|
|
|
// Set updates the boolean value synchronously
|
2015-01-01 19:49:30 +00:00
|
|
|
func (a *AtomicBool) Set(newState bool) bool {
|
2020-03-29 16:42:58 +00:00
|
|
|
atomic.StoreInt32(&a.state, convertBoolToInt32(newState))
|
|
|
|
return newState
|
2015-01-01 19:49:30 +00:00
|
|
|
}
|