-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool.go
58 lines (54 loc) · 1.09 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
package pool
import (
"sync/atomic"
"time"
)
// WorkerPool - use Results to get job result
type WorkerPool struct {
worker uint
remain uint64
queue chan WorkerPoolJob
Results chan WorkerPoolJob
}
// WorkerPoolJob - need to implement the Do() method
type WorkerPoolJob interface {
Do()
}
// NewWorkerPool - create workers pool and do job
func NewWorkerPool(jobs []WorkerPoolJob, worker uint, duration time.Duration) *WorkerPool {
count := len(jobs)
pool := &WorkerPool{
worker: worker,
remain: uint64(count),
queue: make(chan WorkerPoolJob, count),
Results: make(chan WorkerPoolJob, count),
}
if count <= 0 {
close(pool.queue)
close(pool.Results)
return pool
}
for _, job := range jobs {
pool.queue <- job
}
for count := uint(0); count < pool.worker; count++ {
go func() {
for {
job, ok := <-pool.queue
if !ok {
return
}
job.Do()
pool.Results <- job
if atomic.AddUint64(&pool.remain, ^uint64(0)) == 0 {
close(pool.queue)
close(pool.Results)
}
if duration > 0 {
time.Sleep(duration)
}
}
}()
}
return pool
}