-
Notifications
You must be signed in to change notification settings - Fork 0
/
distribute.go
136 lines (123 loc) · 2.58 KB
/
distribute.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
package iterator
import (
"sync"
)
// Distribute returns an iterator of the specified number of iterators.
// Each iterator contains a subset of the items and all of them can be
// consumed in parallel.
func Distribute[T any](buffer int) Modifier[T, Iterator[T]] {
return func(iter Iterator[T]) Iterator[Iterator[T]] {
return newDistributeIterator(iter, buffer)
}
}
type distributeIterator[T any] struct {
iter Iterator[T]
wg sync.WaitGroup
startChan chan struct{}
closeChan chan int
buffer int
chans []chan ValErr[T]
curr Iterator[T]
count int
done bool
err error
lock sync.RWMutex
}
func newDistributeIterator[T any](iter Iterator[T], buffer int) *distributeIterator[T] {
d := &distributeIterator[T]{
iter: iter,
buffer: buffer,
startChan: make(chan struct{}),
closeChan: make(chan int),
}
d.wg.Add(1)
go d.run()
return d
}
func (d *distributeIterator[T]) run() {
// TODO
// go func(){
// d.wg.Wait()
// }()
defer d.iter.Close()
<-d.startChan
counter := 0
for {
select {
case id := <-d.closeChan:
d.lock.Lock()
if d.chans[id] != nil {
close(d.chans[id])
d.chans[id] = nil
d.wg.Done()
}
d.lock.Unlock()
default:
d.lock.Lock()
if !d.iter.Next() {
if err := d.iter.Err(); err != nil {
d.chans[counter] <- ValErr[T]{*new(T), err}
}
if err := d.iter.Close(); err != nil {
d.chans[counter] <- ValErr[T]{*new(T), err}
}
for i := range d.chans {
if d.chans[i] != nil {
close(d.chans[i])
d.chans[i] = nil
}
}
// close(d.closeChan)
} else {
item, err := d.iter.Get()
if d.chans[counter] != nil {
d.chans[counter] <- ValErr[T]{item, err}
counter = (d.count + 1) % len(d.chans)
d.count++
}
}
d.lock.Unlock()
}
}
}
func (d *distributeIterator[T]) Next() bool {
d.lock.Lock()
defer d.lock.Unlock()
if d.done {
return false
}
if d.startChan != nil {
d.startChan <- struct{}{}
close(d.startChan)
d.startChan = nil
}
id := len(d.chans)
c := make(chan ValErr[T], d.buffer)
d.chans = append(d.chans, c)
d.curr = OnClose(FromValErrChannel(c), func() error {
d.closeChan <- id
return nil
})
d.wg.Add(1)
return true
}
func (d *distributeIterator[T]) Get() (Iterator[T], error) {
d.lock.RLock()
defer d.lock.RUnlock()
return d.curr, d.err
}
func (d *distributeIterator[T]) Close() error {
d.lock.Lock()
defer d.lock.Unlock()
if d.done {
return d.err
}
d.done = true
d.wg.Done()
return nil
}
func (d *distributeIterator[T]) Err() error {
d.lock.RLock()
defer d.lock.RUnlock()
return d.err
}