-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadPool.go
87 lines (75 loc) · 1.31 KB
/
ThreadPool.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
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
package comtools
import (
"checkManager/logger"
"sync"
"time"
)
type State int
const (
Start State = iota
Stop
Pause
Continue
)
type ThreadPool struct {
tasks chan func() error
numOfWorks int
total int
results chan error
state State
IsFinish bool
StopFlag bool
}
// 初始化
func (t *ThreadPool) Init(number int, total int) {
t.tasks = make(chan func() error, total)
t.results = make(chan error, total)
t.numOfWorks = number
t.total = total
t.state = Start
}
func (t *ThreadPool) worker(wg *sync.WaitGroup) {
defer wg.Done()
//for {
// task, ok := <-t.tasks
// if !ok {
// break
// }
for task := range t.tasks {
switch t.state {
case Pause:
time.Sleep(time.Second)
continue
case Stop:
break
case Continue, Start:
result := task()
t.results <- result
default:
logger.GetIns().Debug("error state:%d", t.state)
}
}
}
// 开门接客
func (t *ThreadPool) Start() {
// 开启Number个goroutine
var wg sync.WaitGroup
for i := 0; i < t.numOfWorks; i++ {
wg.Add(1)
go t.worker(&wg)
}
wg.Wait()
close(t.results)
}
// 关门送客
func (t *ThreadPool) Stop() {
close(t.tasks)
close(t.results)
}
// 添加任务
func (t *ThreadPool) AddTask(task func() error) {
t.tasks <- task
}
func (t *ThreadPool) ChangeState(state State) {
t.state = state
}