blob: ec859964b57075c67e5c0df6d5272f5b392119dd (
plain) (
blame)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
package stm
import (
"sync"
"github.com/alecthomas/atomic"
)
// Holds an STM variable.
type Var struct {
value atomic.Value[VarValue]
watchers sync.Map
mu sync.Mutex
}
func (v *Var) changeValue(new interface{}) {
old := v.value.Load()
newVarValue := old.Set(new)
v.value.Store(newVarValue)
if old.Changed(newVarValue) {
go v.wakeWatchers(newVarValue)
}
}
func (v *Var) wakeWatchers(new VarValue) {
v.watchers.Range(func(k, _ interface{}) bool {
tx := k.(*Tx)
// We have to lock here to ensure that the Tx is waiting before we signal it. Otherwise we
// could signal it before it goes to sleep and it will miss the notification.
tx.mu.Lock()
if read := tx.reads[v]; read != nil && read.Changed(new) {
tx.cond.Broadcast()
for !tx.waiting && !tx.completed {
tx.cond.Wait()
}
}
tx.mu.Unlock()
return !v.value.Load().Changed(new)
})
}
type varSnapshot struct {
val interface{}
version uint64
}
// Returns a new STM variable.
func NewVar(val interface{}) *Var {
v := &Var{}
v.value.Store(versionedValue{
value: val,
})
return v
}
func NewCustomVar(val interface{}, changed func(interface{}, interface{}) bool) *Var {
v := &Var{}
v.value.Store(customVarValue{
value: val,
changed: changed,
})
return v
}
func NewBuiltinEqVar(val interface{}) *Var {
return NewCustomVar(val, func(a, b interface{}) bool {
return a != b
})
}
|