forked from nxenon/port-scanner-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexec.go
72 lines (63 loc) · 1.2 KB
/
exec.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
package main
import (
"context"
"runtime/pprof"
"strconv"
"sync"
)
type Job func(ctx context.Context) error
type JobsExecutor interface {
Submit(job Job)
Shutdown()
}
type jobsExecutor struct {
ctx context.Context
cancel func()
jobsChan chan Job
wg *sync.WaitGroup
}
func NewJobsExecutor(ctx context.Context, jobs int, parallelism int) JobsExecutor {
ctx, cancel := context.WithCancel(ctx)
var wg sync.WaitGroup
je := &jobsExecutor{
ctx: ctx,
cancel: cancel,
jobsChan: make(chan Job, jobs),
wg: &wg,
}
je.start(parallelism)
return je
}
func (je *jobsExecutor) start(parallelism int) {
for i := 0; i < parallelism; i++ {
labels := pprof.Labels(`worker`, strconv.Itoa(i))
pprof.Do(je.ctx, labels, func(ctx context.Context) {
je.runWorker(ctx)
})
}
}
func (je *jobsExecutor) runWorker(ctx context.Context) {
je.wg.Add(1)
go func() {
defer je.wg.Done()
for {
select {
case job, ok := <-je.jobsChan:
if !ok {
return
}
_ = job(ctx)
case <-ctx.Done():
return
}
}
}()
}
func (je *jobsExecutor) Submit(job Job) {
je.jobsChan <- job
}
func (je *jobsExecutor) Shutdown() {
defer je.cancel()
close(je.jobsChan)
je.wg.Wait()
}