-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
67 lines (54 loc) · 1021 Bytes
/
worker.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
package hunkee
import (
"sync/atomic"
)
type pool struct {
size int
free chan *worker
}
func initPool(size int) *pool {
free := make(chan *worker, size)
for i := 0; i < size; i++ {
free <- &worker{}
}
return &pool{
size: size,
free: free,
}
}
func (p *pool) get(parent *mapper) *worker {
w := <-p.free
w.parent = parent
return w
}
func (p *pool) put(w *worker) {
p.free <- w
}
// worker need to safely use any amount of parsers for
// corresponded format without any memory overhead and races.
type worker struct {
id uint
pos uint32
len uint32
parent *mapper
}
func (w *worker) seek(i uint32) *field {
if w.len == 0 {
w.len = uint32(len(w.parent.tokensSeq))
}
if i >= w.len {
return nil
}
f := w.parent.getField(w.parent.tokensSeq[i])
atomic.StoreUint32(&w.pos, uint32(i+1))
return f
}
func (w *worker) next() *field {
return w.seek(atomic.LoadUint32(&w.pos))
}
func (w *worker) first() *field {
return w.seek(0)
}
func (w *worker) free() {
w.parent.workerPool.put(w)
}