-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworker_pool.go
More file actions
40 lines (34 loc) · 810 Bytes
/
worker_pool.go
File metadata and controls
40 lines (34 loc) · 810 Bytes
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
package workerpool
import (
"context"
"sync"
)
type WorkerPool struct {
taskQueue chan Task
resultChan chan Result
maxConcurrent int
wg *sync.WaitGroup
}
func NewWorkerPool(maxConcurrent int) *WorkerPool {
return &WorkerPool{
taskQueue: make(chan Task, 10),
resultChan: make(chan Result, 10),
maxConcurrent: maxConcurrent,
wg: &sync.WaitGroup{},
}
}
func (wp *WorkerPool) Start(ctx context.Context) {
for i := 0; i < wp.maxConcurrent; i++ {
worker := NewWorker(wp.taskQueue, wp.resultChan, wp.wg)
worker.Start(ctx)
}
resultWorker := NewResultWorker(wp.resultChan, wp.wg)
resultWorker.Start(ctx)
}
func (wp *WorkerPool) AddTask(task Task) {
wp.wg.Add(2) // task and result
wp.taskQueue <- task
}
func (wp *WorkerPool) Wait() {
wp.wg.Wait()
}