mirror of
https://github.com/Llewellynvdm/fzf.git
synced 2024-09-22 10:19:02 +00:00
Update AtomicBool to use atomic memory operation (#1939)
This commit is contained in:
parent
a5c2f28539
commit
a6a732e1fc
@ -1,32 +1,34 @@
|
|||||||
package util
|
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
|
// AtomicBool is a boxed-class that provides synchronized access to the
|
||||||
// underlying boolean value
|
// underlying boolean value
|
||||||
type AtomicBool struct {
|
type AtomicBool struct {
|
||||||
mutex sync.Mutex
|
state int32 // "1" is true, "0" is false
|
||||||
state bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewAtomicBool returns a new AtomicBool
|
// NewAtomicBool returns a new AtomicBool
|
||||||
func NewAtomicBool(initialState bool) *AtomicBool {
|
func NewAtomicBool(initialState bool) *AtomicBool {
|
||||||
return &AtomicBool{
|
return &AtomicBool{state: convertBoolToInt32(initialState)}
|
||||||
mutex: sync.Mutex{},
|
|
||||||
state: initialState}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the current boolean value synchronously
|
// Get returns the current boolean value synchronously
|
||||||
func (a *AtomicBool) Get() bool {
|
func (a *AtomicBool) Get() bool {
|
||||||
a.mutex.Lock()
|
return atomic.LoadInt32(&a.state) == 1
|
||||||
defer a.mutex.Unlock()
|
|
||||||
return a.state
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set updates the boolean value synchronously
|
// Set updates the boolean value synchronously
|
||||||
func (a *AtomicBool) Set(newState bool) bool {
|
func (a *AtomicBool) Set(newState bool) bool {
|
||||||
a.mutex.Lock()
|
atomic.StoreInt32(&a.state, convertBoolToInt32(newState))
|
||||||
defer a.mutex.Unlock()
|
return newState
|
||||||
a.state = newState
|
|
||||||
return a.state
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user