summaryrefslogtreecommitdiffstats
path: root/src/util
diff options
context:
space:
mode:
authorAlexandr <aabruyako@gmail.com>2020-03-29 19:42:58 +0300
committerGitHub <noreply@github.com>2020-03-30 01:42:58 +0900
commita6a732e1fc2a0cb3cc31dc31c7c67f29ece2df9a (patch)
treeeefb8e4bf914e7f91acc08a4d49c9ab94ad7bd9e /src/util
parenta5c2f28539c460d9ac42d1a8e37f2b149b694d4a (diff)
Update AtomicBool to use atomic memory operation (#1939)
Diffstat (limited to 'src/util')
-rw-r--r--src/util/atomicbool.go28
1 files changed, 15 insertions, 13 deletions
diff --git a/src/util/atomicbool.go b/src/util/atomicbool.go
index 9e1bdc8f..c5c7e690 100644
--- a/src/util/atomicbool.go
+++ b/src/util/atomicbool.go
@@ -1,32 +1,34 @@
package util
-import "sync"
+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 {
- mutex sync.Mutex
- state bool
+ state int32 // "1" is true, "0" is false
}
// NewAtomicBool returns a new AtomicBool
func NewAtomicBool(initialState bool) *AtomicBool {
- return &AtomicBool{
- mutex: sync.Mutex{},
- state: initialState}
+ return &AtomicBool{state: convertBoolToInt32(initialState)}
}
// Get returns the current boolean value synchronously
func (a *AtomicBool) Get() bool {
- a.mutex.Lock()
- defer a.mutex.Unlock()
- return a.state
+ return atomic.LoadInt32(&a.state) == 1
}
// Set updates the boolean value synchronously
func (a *AtomicBool) Set(newState bool) bool {
- a.mutex.Lock()
- defer a.mutex.Unlock()
- a.state = newState
- return a.state
+ atomic.StoreInt32(&a.state, convertBoolToInt32(newState))
+ return newState
}