-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
executable file
·83 lines (69 loc) · 1.45 KB
/
Copy pathpool.go
File metadata and controls
executable file
·83 lines (69 loc) · 1.45 KB
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
package workerpool
import (
"context"
"sync"
)
type Pool struct {
workersCount int64
workers []*Worker
taskChan chan Task
errorChan chan error
stoppedChan chan bool
mu sync.Mutex
stopped bool
}
func NewPool(workersCount int64, capacity int64) *Pool {
pool := &Pool{
workersCount: workersCount,
workers: make([]*Worker, 0, workersCount),
taskChan: make(chan Task, capacity),
errorChan: make(chan error, capacity),
stoppedChan: make(chan bool),
mu: sync.Mutex{},
stopped: false,
}
go pool.start()
return pool
}
func (pool *Pool) start() {
var wg sync.WaitGroup
for id := int64(1); id <= pool.workersCount; id++ {
wg.Add(1)
ctx := context.Background()
worker := NewWorker(ctx, id, pool.taskChan, pool.errorChan)
pool.workers = append(pool.workers, worker)
go worker.Run(&wg)
}
wg.Wait()
pool.stoppedChan <- true
}
func (pool *Pool) Wait() {
close(pool.taskChan)
<-pool.stoppedChan
close(pool.errorChan)
close(pool.stoppedChan)
}
func (pool *Pool) Stopped() bool {
pool.mu.Lock()
defer pool.mu.Unlock()
return pool.stopped
}
func (pool *Pool) Stop() {
pool.mu.Lock()
defer pool.mu.Unlock()
for _, worker := range pool.workers {
worker.Stop()
}
pool.stopped = true
}
func (pool *Pool) AddTask(task Task) {
pool.mu.Lock()
defer pool.mu.Unlock()
if pool.stopped {
return
}
pool.taskChan <- task
}
func (pool *Pool) Errors() chan error {
return pool.errorChan
}