-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi.go
156 lines (117 loc) · 2.45 KB
/
multi.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package batch
import (
"context"
)
type (
Multi[Res any] struct {
CommitFunc func(ctx context.Context, coach int) (Res, error)
Balancer func(bitset []uint64) int
available []uint64
locs
cs []coach[Res]
}
)
func NewMulti[Res any](n int, f func(ctx context.Context, coach int) (Res, error)) *Multi[Res] {
return &Multi[Res]{
CommitFunc: f,
cs: make([]coach[Res], n),
}
}
func (c *Multi[Res]) Init(n int, f func(ctx context.Context, coach int) (Res, error)) {
c.CommitFunc = f
c.cs = make([]coach[Res], n)
}
func (c *Multi[Res]) Queue() *Queue {
return &c.locs.queue
}
func (c *Multi[Res]) Notify() {
c.cond.Broadcast()
}
func (c *Multi[Res]) Enter(blocking bool) (coach, idx int) {
c.mu.Lock()
c.queue.Out()
if c.cond.L == nil {
c.cond.L = &c.mu
}
again:
if c.Balancer != nil {
coach, idx := c.enterBalancer()
if idx >= 0 {
return coach, idx
}
} else {
for coach := range c.cs {
if idx := c.cs[coach].cnt; idx >= 0 {
c.cs[coach].cnt++
return coach, idx
}
}
}
if !blocking {
c.mu.Unlock()
c.cond.Broadcast()
return -1, -1
}
c.cond.Wait()
goto again
}
func (c *Multi[Res]) enterBalancer() (coach, idx int) {
if c.available == nil {
c.available = make([]uint64, (len(c.cs)+63)/64)
}
for i := range c.available {
c.available[i] = 0
}
for coach := range c.cs {
if c.cs[coach].cnt < 0 {
continue
}
i, j := coach/64, coach%64
c.available[i] |= 1 << j
}
coach = c.Balancer(c.available)
if coach < 0 || c.cs[coach].cnt < 0 {
return -1, -1
}
c.cs[coach].cnt++
return coach, c.cs[coach].cnt - 1
}
func (c *Multi[Res]) Exit(coach int) int {
defer func() {
c.mu.Unlock()
c.cond.Broadcast()
}()
cc := &c.cs[coach]
if cc.cnt > 0 {
p := recover()
if p == nil { // we just left
cc.cnt--
return cc.cnt
}
cc.cnt = -cc.cnt
cc.err = PanicError{Panic: p}
cc.ready = true
defer panic(p)
}
cc.cnt++
idx := -cc.cnt
if cc.cnt == 0 {
var zero Res
cc.res, cc.err, cc.ready = zero, nil, false
}
return idx
}
func (c *Multi[Res]) Trigger(coach int) {
c.cs[coach].trigger = true
}
func (c *Multi[Res]) Commit(ctx context.Context, coach int) (Res, error) {
return commit(ctx, &c.locs, &c.cs[coach], nil, func(ctx context.Context) (Res, error) {
return c.CommitFunc(ctx, coach)
})
}
func (c *Multi[Res]) Cancel(ctx context.Context, coach int, err error) (Res, error) {
if err == nil {
err = Canceled
}
return commit(ctx, &c.locs, &c.cs[coach], err, nil)
}