-
Notifications
You must be signed in to change notification settings - Fork 0
/
taskpool-const-goroutines.go
98 lines (84 loc) · 1.83 KB
/
taskpool-const-goroutines.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
package main
import (
"container/list"
// "fmt"
"os"
"runtime"
"strconv"
"sync"
)
type TaskPool struct {
tasks list.List
mutex sync.Mutex
workersActive int
maxWorkers int
stopSignal chan bool
}
func NewTaskPool() *TaskPool {
bindThreads := os.Getenv("OMP_PROC_BIND")
if bindThreads == "TRUE" {
runtime.LockOSThread()
}
numThreads, err := strconv.Atoi(os.Getenv("OMP_NUM_THREADS"))
if err != nil || numThreads < 1 {
numThreads = runtime.NumCPU()
}
// fmt.Println("setting to ", numThreads)
pool := &TaskPool{
maxWorkers: numThreads - 1,
}
pool.tasks.Init()
runtime.GOMAXPROCS(numThreads)
pool.stopSignal = make(chan bool, pool.maxWorkers)
return pool
}
func (pool *TaskPool) AddTask(task func()) {
pool.mutex.Lock()
if pool.workersActive < pool.maxWorkers {
pool.tasks.PushFront(task)
pool.mutex.Unlock()
} else {
pool.mutex.Unlock()
task()
}
}
func (pool *TaskPool) Start() {
for i := pool.maxWorkers; i > 0; i-- {
//fmt.Println("starting goroutine", i)
go func(id int) {
for {
pool.mutex.Lock()
if pool.tasks.Len() > 0 {
e := pool.tasks.Front()
pool.workersActive++
pool.tasks.Remove(e)
pool.mutex.Unlock()
// pick the list element's value and execute it
//fmt.Printf("Goroutine %d found task, executing\n", id)
e.Value.(func())()
pool.mutex.Lock()
pool.workersActive--
pool.mutex.Unlock()
} else {
pool.mutex.Unlock()
select {
case <-pool.stopSignal:
//fmt.Println("quitting goroutine ", i)
return
default:
//fmt.Println("doing nothing ", i)
runtime.Gosched()
}
}
}
}(i)
}
}
func (pool *TaskPool) Stop() {
pool.mutex.Lock()
defer pool.mutex.Unlock()
// Send a stop signal to each goroutine
for n := 0; n < pool.maxWorkers; n++ {
pool.stopSignal <- true
}
}