forked from yext/edward
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
93 lines (76 loc) · 1.65 KB
/
pool.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
package worker
import (
"sync"
"github.com/pkg/errors"
)
// Pool provides a set of workers for executing functions
type Pool struct {
jobs chan func() error
finished chan struct{}
completion chan struct{}
workers int
err error
mtx sync.Mutex
}
// NewPool creates a pool with the specified number of workers.
// The pool will not begin accepting jobs until Start() is called.
func NewPool(workers int) *Pool {
return &Pool{
workers: workers,
}
}
func (p *Pool) Err() error {
p.mtx.Lock()
defer p.mtx.Unlock()
return p.err
}
func (p *Pool) setErr(err error) {
p.mtx.Lock()
defer p.mtx.Unlock()
p.err = err
}
// Start initializes the Pool to begin accepting and running jobs.
func (p *Pool) Start() {
p.jobs = make(chan func() error)
p.finished = make(chan struct{})
p.completion = make(chan struct{})
for w := 1; w <= p.workers; w++ {
go p.worker(w)
}
go func() {
for a := 1; a <= p.workers; a++ {
<-p.finished
}
close(p.finished)
close(p.completion)
}()
}
// Enqueue adds a job to the pool.
func (p *Pool) Enqueue(job func() error) error {
if p.Err() != nil {
return errors.New("aborted")
}
// Execute the job synchronously if no workers are provided
if p.workers == 0 {
return errors.WithStack(job())
}
p.jobs <- job
return nil
}
// Stop prevents this pool from accepting new jobs.
func (p *Pool) Stop() {
close(p.jobs)
}
// Complete returns a channel that will be closed when all workers have finished
func (p *Pool) Complete() <-chan struct{} {
return p.completion
}
func (p *Pool) worker(index int) {
for j := range p.jobs {
err := j()
if err != nil {
p.setErr(err)
}
}
p.finished <- struct{}{}
}