forked from aerospike/aerospike-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_val.go
51 lines (42 loc) · 1.11 KB
/
sync_val.go
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package atomic
import "sync"
type SyncVal struct {
val interface{}
lock sync.RWMutex
}
// NewSyncVal creates a new instance of SyncVal
func NewSyncVal(val interface{}) *SyncVal {
return &SyncVal{val: val}
}
// Set updates the value of SyncVal with the passed argument
func (sv *SyncVal) Set(val interface{}) {
sv.lock.Lock()
sv.val = val
sv.lock.Unlock()
}
// Get returns the value inside the SyncVal
func (sv *SyncVal) Get() interface{} {
sv.lock.RLock()
val := sv.val
sv.lock.RUnlock()
return val
}
// GetSyncedVia returns the value returned by the function f.
func (sv *SyncVal) GetSyncedVia(f func(interface{}) (interface{}, error)) (interface{}, error) {
sv.lock.RLock()
defer sv.lock.RUnlock()
val, err := f(sv.val)
return val, err
}
// Update gets a function and passes the value of SyncVal to it.
// If the resulting err is nil, it will update the value of SyncVal.
// It will return the resulting error to the caller.
func (sv *SyncVal) Update(f func(interface{}) (interface{}, error)) error {
sv.lock.Lock()
defer sv.lock.Unlock()
val, err := f(sv.val)
if err == nil {
sv.val = val
}
return err
}