-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread_pool.go
64 lines (57 loc) · 1.14 KB
/
thread_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
package main
import (
"container/list"
"log"
"sync"
"time"
)
type ThreadPool struct {
size, running int
list *list.List
m sync.Mutex
}
func NewThreadPool(size int) *ThreadPool {
tp := &ThreadPool{
size: size,
list: list.New(),
}
return tp
}
func (tp *ThreadPool) onStop() {
tp.m.Lock()
tp.running--
tp.m.Unlock()
tp.run()
}
func (tp *ThreadPool) run() {
tp.m.Lock()
defer tp.m.Unlock()
if tp.list.Len() > 0 && tp.running < tp.size {
f := tp.list.Remove(tp.list.Front()).(func())
tp.running++
go func() {
f()
tp.onStop()
}()
}
}
func (tp *ThreadPool) Submit(f func()) {
tp.list.PushBack(f)
tp.run()
}
func main() {
var wg sync.WaitGroup
tp := NewThreadPool(4)
for i := 0; i < 16; i++ {
wg.Add(1)
(func(id int) {
log.Printf("Subtmitted job %d", id)
tp.Submit(func() {
time.Sleep(3 * time.Second)
log.Printf("Hello from job %d", id)
wg.Done()
})
})(i)
}
wg.Wait()
}