-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker_pool.go
57 lines (44 loc) · 1.08 KB
/
worker_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
package goapp
import (
"context"
"time"
"github.com/alitto/pond"
)
type WorkerPoolJob interface {
Do()
}
type WorkerPool struct {
context context.Context
workerPond *pond.WorkerPool
}
func StartWorkerPool(ctx context.Context, workersCount int) *WorkerPool {
workerPool := WorkerPool{
context: ctx,
}
//max 2 workers, max 1000 tasks in queue
workerPool.workerPond = pond.New(workersCount, 1000, pond.MinWorkers(1), pond.Context(workerPool.context))
return &workerPool
}
func (wp *WorkerPool) Stop() {
wp.workerPond.StopAndWaitFor(10 * time.Second)
}
func (wp *WorkerPool) DoSingleJob(job WorkerPoolJob, wait bool) {
localJob := job //scoped copy of struct
if wait {
wp.workerPond.SubmitAndWait(localJob.Do)
} else {
wp.workerPond.Submit(localJob.Do)
}
}
func (wp *WorkerPool) DoJobList(jobList []WorkerPoolJob, wait bool) {
group := wp.workerPond.Group()
// Submit a group of tasks
for _, job := range jobList {
localJob := job //scoped copy of struct
group.Submit(localJob.Do)
}
// Wait for all tasks in the group to complete
if wait {
group.Wait()
}
}