-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasypool.go
62 lines (55 loc) · 1.09 KB
/
easypool.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
59
60
61
62
package easypool
import (
"sync"
)
type WorkerPool struct {
queue chan func()
done chan struct{}
wg sync.WaitGroup
poolSize int
}
// NewPool creates a new WorkerPool with the specified size.
func NewPool(poolSize int) *WorkerPool {
return &WorkerPool{
poolSize: poolSize,
queue: make(chan func(), poolSize),
done: make(chan struct{}),
}
}
// AddToPool adds a function to be executed by the worker pool.
func (wp *WorkerPool) AddToPool(task func()) {
wp.wg.Add(1)
go func() {
defer wp.wg.Done()
wp.queue <- task
}()
}
// Launch the worker pool and executes the functions in the pool.
func (wp *WorkerPool) Execute() {
for i := 0; i < wp.poolSize; i++ {
wp.wg.Add(1)
go func() {
defer wp.wg.Done()
for {
select {
case task, ok := <-wp.queue:
if !ok {
return
}
task()
case <-wp.done:
return
}
}
}()
}
}
// Waits for all tasks in the worker pool to complete.
func (wp *WorkerPool) Wait() {
close(wp.queue)
wp.wg.Wait()
}
// Closes the worker pool gracefully.
func (wp *WorkerPool) Close() {
close(wp.done)
}