-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
65 lines (56 loc) · 1.15 KB
/
pool.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
package pool
type Pool struct {
PoolSize int
TaskSize int
TaskChan chan interface{}
ctrlChan chan struct{}
Task func(task interface{})
}
func (poolObj *Pool) init() {
for i:=0; i<poolObj.PoolSize; i++ {
go poolObj.worker()
}
}
func (poolObj *Pool) AddTask(task interface{}) {
poolObj.TaskChan <- task
}
func (poolObj *Pool) AdjustPoolSize(poolSize int) {
if poolSize > poolObj.PoolSize {
for i:= poolObj.PoolSize; i<poolSize; i++ {
go poolObj.worker()
}
poolObj.PoolSize = poolSize
} else if poolSize < poolObj.PoolSize {
for i:=poolSize; i<poolObj.PoolSize; i++ {
poolObj.ctrlChan <- struct{}{}
}
poolObj.PoolSize = poolSize
}
}
func (poolObj *Pool) worker() {
for {
stop := false
select {
case task := <- poolObj.TaskChan:
poolObj.Task(task)
case <- poolObj.ctrlChan:
stop = true
}
if stop {
break
}
}
}
/* Create Pool Instance
*/
func NewPool(poolSize int, taskSize int, worker func(interface{})) *Pool {
taskPool := & Pool{
PoolSize: poolSize,
TaskSize: taskSize,
TaskChan: make(chan interface{}, taskSize),
ctrlChan: make(chan struct{}),
Task: worker,
}
taskPool.init();
return taskPool
}