summaryrefslogtreecommitdiff
path: root/src/util/atomicbool.go
blob: c5c7e6904cbd08876c0c240e6ef9e6a012072926 (plain)
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
package util

import (
	"sync/atomic"
)

func convertBoolToInt32(b bool) int32 {
	if b {
		return 1
	}
	return 0
}

// AtomicBool is a boxed-class that provides synchronized access to the
// underlying boolean value
type AtomicBool struct {
	state int32 // "1" is true, "0" is false
}

// NewAtomicBool returns a new AtomicBool
func NewAtomicBool(initialState bool) *AtomicBool {
	return &AtomicBool{state: convertBoolToInt32(initialState)}
}

// Get returns the current boolean value synchronously
func (a *AtomicBool) Get() bool {
	return atomic.LoadInt32(&a.state) == 1
}

// Set updates the boolean value synchronously
func (a *AtomicBool) Set(newState bool) bool {
	atomic.StoreInt32(&a.state, convertBoolToInt32(newState))
	return newState
}