-
Notifications
You must be signed in to change notification settings - Fork 21
/
pool.go
55 lines (47 loc) · 991 Bytes
/
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
package gopool
import (
"sync"
)
type Pool struct {
// capacity represents the maximum number of workers the pool can have
capacity int
// running represents the number of workers that are currently running
running int
// workers represents a pool of workers that are executing tasks
workers WorkerStack
// lock represents a mutex to protect the workers slice
lock sync.Mutex
}
func (p *Pool) Submit(task Task) {
p.lock.Lock()
defer p.lock.Unlock()
if p.running < p.capacity {
worker := p.workers.Pop()
if worker == nil {
worker = &Worker{
pool: p,
task: make(chan Task),
}
}
worker.task <- task
worker.run()
p.running++
} else {
// TODO: handle the case when the pool is full
}
}
func (p *Pool) Running() int {
return p.running
}
func (p *Pool) Cap() int {
return p.capacity
}
func (p *Pool) Release() {
p.lock.Lock()
defer p.lock.Unlock()
for p.workers.Len() > 0 {
worker := p.workers.Pop()
close(worker.task)
}
p.running = 0
}