-
Notifications
You must be signed in to change notification settings - Fork 6
/
pool.go
79 lines (67 loc) · 1.29 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package gohive
import (
"errors"
"fmt"
"sync/atomic"
)
const (
OPEN = iota
CLOSED
)
type Pool struct {
poolChan chan Runner
quitChan chan bool
state int32
size int
availableWorkers int32
}
func NewFixedPool(size int) *Pool {
pool := &Pool{
poolChan: make(chan Runner),
quitChan: make(chan bool),
state: OPEN,
size: size,
}
for i := 0; i < size; i++ {
go pool.worker()
pool.availableWorkers++
}
return pool
}
func (p *Pool) Close() error {
if atomic.CompareAndSwapInt32(&p.state, OPEN, CLOSED) {
for i := 0; i < p.size; i++ {
p.quitChan <- true
}
fmt.Println("pool is closed.")
return nil
}
return errors.New("error: cannot close an already closed pool")
}
func (p *Pool) IsPoolClosed() bool {
return atomic.LoadInt32(&p.state) == CLOSED
}
func (p *Pool) Submit(r Runner) error {
if r == nil {
return errors.New("cannot submit nil Runner")
}
if atomic.LoadInt32(&p.state) == CLOSED {
return errors.New("cannot submit, pool is closed")
}
p.poolChan <- r
return nil
}
func (p *Pool) worker() {
defer fmt.Println("closing...")
Loop:
for {
select {
case r := <-p.poolChan:
atomic.AddInt32(&p.availableWorkers, -1)
r.Run()
atomic.AddInt32(&p.availableWorkers, 1)
case <-p.quitChan:
break Loop
}
}
}