-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
103 lines (87 loc) · 2.13 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package nodejs
import (
"context"
"runtime"
"sync"
"sync/atomic"
"time"
)
type Pool struct {
q chan *Process
factory *Factory
maxProcs uint64
procs uint64
cond *sync.Cond
lk sync.Mutex
}
// NewPool returns a pool of nodejs processes generated by the factory. The pool will
// always generate at least queueSize processes in memory and will start new ones as
// they are taken. Passing queueSize <=0 will use the number of CPUs.
func (f *Factory) NewPool(queueSize, maxProcs int) *Pool {
if queueSize <= 0 {
queueSize = runtime.NumCPU()
}
if maxProcs <= 0 {
maxProcs = runtime.NumCPU()
}
p := &Pool{
maxProcs: uint64(maxProcs),
q: make(chan *Process, queueSize),
factory: f,
}
p.cond = sync.NewCond(&p.lk)
go p.run()
return p
}
// TakeIfAvailable returns a [Process] if any is available, or nil if not
func (pool *Pool) TakeIfAvailable() *Process {
select {
case res := <-pool.q:
return res
default:
return nil
}
}
// Take returns a [Process] from the pool and will wait until one is available,
// unless the context is cancelled.
func (pool *Pool) Take(ctx context.Context) (*Process, error) {
select {
case res := <-pool.q:
return res, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// TakeTimeout will return a [Process] taken from the pool if any is available
// before the timeout expires.
func (pool *Pool) TakeTimeout(t time.Duration) (*Process, error) {
ctx, cancel := context.WithTimeout(context.Background(), t)
defer cancel()
return pool.Take(ctx)
}
func (pool *Pool) run() {
pool.lk.Lock()
defer pool.lk.Unlock()
for {
if atomic.LoadUint64(&pool.procs) > pool.maxProcs {
// too many running, wait
pool.cond.Wait()
continue
}
newProc, err := pool.factory.New()
if err != nil {
time.Sleep(10 * time.Second)
continue
}
// ensure procs is updated if needed
atomic.AddUint64(&pool.procs, 1)
newProc.cleanup = append(newProc.cleanup, pool.procsSubOne)
// add to queue
pool.q <- newProc
}
}
func (pool *Pool) procsSubOne() {
// sub 1 from pool.procs & wake up cond just in case
atomic.AddUint64(&pool.procs, ^uint64(0))
pool.cond.Broadcast()
}