-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.go
51 lines (41 loc) · 850 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
package async
import (
"github.com/gammazero/workerpool"
)
type WorkerPool struct {
wp *workerpool.WorkerPool
tasks []*Task
}
func NewWorkerPool() *WorkerPool {
return NewWorkerPoolWithSize(10)
}
func NewWorkerPoolWithSize(size int) *WorkerPool {
return &WorkerPool{
wp: workerpool.New(size),
}
}
func (p *WorkerPool) AddTask(taskFunc func() (interface{}, error)) {
task := NewTask(taskFunc)
p.tasks = append(p.tasks, task)
p.wp.Submit(task.Run)
}
func (p *WorkerPool) GetTasks() []*Task {
return p.tasks
}
func (p *WorkerPool) StopWait() {
p.wp.StopWait()
}
// a task wraps a function and its response
type Task struct {
f func() (interface{}, error)
Err error
Result interface{}
}
func NewTask(f func() (interface{}, error)) *Task {
return &Task{
f: f,
}
}
func (t *Task) Run() {
t.Result, t.Err = t.f()
}