-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkrun.go
121 lines (99 loc) · 1.76 KB
/
krun.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
package krun
import (
"context"
"sync"
"time"
)
type Result struct {
Data interface{}
Error error
}
type Job func(ctx context.Context) (interface{}, error)
type Krun interface {
Run(ctx context.Context, f Job) <-chan *Result
Wait(ctx context.Context)
Size() int
}
type krun struct {
n int
waitSleep time.Duration
workers chan *worker
mu sync.RWMutex
}
type worker struct {
job Job
result chan *Result
}
type Config struct {
Size int
WaitSleep time.Duration
}
func New(cfg *Config) Krun {
k := &krun{
n: cfg.Size,
workers: make(chan *worker, cfg.Size),
waitSleep: cfg.WaitSleep,
}
for i := 0; i < cfg.Size; i++ {
k.push(&worker{})
}
return k
}
func (k *krun) Size() int {
k.mu.RLock()
s := k.n
k.mu.RUnlock()
return s
}
func (k *krun) Run(ctx context.Context, f Job) <-chan *Result {
// get worker from the channel
w := k.pop()
// assign Job to the worker and Run it
cr := make(chan *Result)
w.job = f
w.result = cr
go k.work(ctx, w)
// return channel to the caller
return cr
}
func (k *krun) Wait(ctx context.Context) {
k.mu.RLock()
n := k.n
k.mu.RUnlock()
if k.len() == n {
return
}
for {
select {
case <-ctx.Done():
return
case <-time.After(k.waitSleep):
// "wait" until all workers are back
if k.len() < n {
continue
}
return
}
}
}
func (k *krun) work(ctx context.Context, w *worker) {
// run the job
d, err := w.job(ctx)
// send Result into the caller channel
// this will block until is read
w.result <- &Result{d, err}
// return worker to Krun
k.push(w)
}
func (k *krun) push(w *worker) {
k.workers <- w
}
func (k *krun) pop() *worker {
return <-k.workers
}
func (k *krun) len() int {
k.mu.RLock()
l := len(k.workers)
k.mu.RUnlock()
return l
}