| 1 |
package util |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync/atomic" |
| 5 |
) |
| 6 |
|
| 7 |
func convertBoolToInt32(b bool) int32 { |
| 8 |
if b { |
| 9 |
return 1 |
| 10 |
} |
| 11 |
return 0 |
| 12 |
} |
| 13 |
|
| 14 |
// AtomicBool is a boxed-class that provides synchronized access to the |
| 15 |
// underlying boolean value |
| 16 |
type AtomicBool struct { |
| 17 |
state int32 // "1" is true, "0" is false |
| 18 |
} |
| 19 |
|
| 20 |
// NewAtomicBool returns a new AtomicBool |
| 21 |
func NewAtomicBool(initialState bool) *AtomicBool { |
| 22 |
return &AtomicBool{state: convertBoolToInt32(initialState)} |
| 23 |
} |
| 24 |
|
| 25 |
// Get returns the current boolean value synchronously |
| 26 |
func (a *AtomicBool) Get() bool { |
| 27 |
return atomic.LoadInt32(&a.state) == 1 |
| 28 |
} |
| 29 |
|
| 30 |
// Set updates the boolean value synchronously |
| 31 |
func (a *AtomicBool) Set(newState bool) bool { |
| 32 |
atomic.StoreInt32(&a.state, convertBoolToInt32(newState)) |
| 33 |
return newState |
| 34 |
} |