-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
134 lines (111 loc) · 2.19 KB
/
pool.go
File metadata and controls
134 lines (111 loc) · 2.19 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package promise
import (
"context"
"runtime"
"sync"
"sync/atomic"
)
type taskPoolConfig struct {
Workers int
QueueSize int
}
func defaultTaskPoolConfig() *taskPoolConfig {
workers := runtime.NumCPU() * 2
return &taskPoolConfig{
Workers: workers,
QueueSize: workers * 2,
}
}
type taskPool struct {
tasks chan func()
workers int32
mu sync.RWMutex
shutdown int32
workerCtx context.Context
workerCancel context.CancelFunc
workerWg sync.WaitGroup
}
func newTaskPool(config *taskPoolConfig) *taskPool {
if config == nil {
config = defaultTaskPoolConfig()
}
if config.Workers <= 0 {
config.Workers = runtime.NumCPU()
}
if config.QueueSize <= 0 {
config.QueueSize = config.Workers * 2
}
ctx, cancel := context.WithCancel(context.Background())
pool := &taskPool{
tasks: make(chan func(), config.QueueSize),
workers: int32(config.Workers),
workerCtx: ctx,
workerCancel: cancel,
}
pool.startWorkers(config.Workers)
return pool
}
func (p *taskPool) startWorkers(count int) {
for i := 0; i < count; i++ {
p.workerWg.Add(1)
go p.worker()
}
}
func (p *taskPool) worker() {
defer p.workerWg.Done()
for {
select {
case fn, ok := <-p.tasks:
if !ok {
return
}
if fn == nil {
continue
}
// Execute task with panic recovery
func() {
defer func() {
if r := recover(); r != nil {
// Prevent worker crash
}
}()
fn()
}()
case <-p.workerCtx.Done():
return
}
}
}
func (p *taskPool) Submit(executor func()) error {
if atomic.LoadInt32(&p.shutdown) == 1 {
return ErrManagerStopped
}
select {
case p.tasks <- executor:
if atomic.LoadInt32(&p.shutdown) == 1 {
return ErrManagerStopped
}
return nil
case <-p.workerCtx.Done():
return ErrManagerStopped
}
}
func (p *taskPool) Workers() int {
return int(atomic.LoadInt32(&p.workers))
}
func (p *taskPool) IsShutdown() bool {
return atomic.LoadInt32(&p.shutdown) == 1
}
func (p *taskPool) Close() {
if !atomic.CompareAndSwapInt32(&p.shutdown, 0, 1) {
return
}
p.workerCancel()
p.mu.Lock()
close(p.tasks)
p.mu.Unlock()
p.workerWg.Wait()
}
func (p *taskPool) WaitForShutdown() {
p.workerWg.Wait()
}