forked from lesismal/nbio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
taskpool.go
108 lines (98 loc) · 1.92 KB
/
taskpool.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
104
105
106
107
108
// Copyright 2020 lesismal. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package taskpool
import (
"runtime"
"sync/atomic"
"unsafe"
"github.com/soar4/nbio/logging"
)
// TaskPool .
type TaskPool struct {
concurrent int64
maxConcurrent int64
chQqueue chan func()
chClose chan struct{}
caller func(f func())
}
// fork .
func (tp *TaskPool) fork(f func()) bool {
if atomic.AddInt64(&tp.concurrent, 1) < tp.maxConcurrent {
go func() {
defer atomic.AddInt64(&tp.concurrent, -1)
tp.caller(f)
for {
select {
case f = <-tp.chQqueue:
if f != nil {
tp.caller(f)
}
default:
return
}
}
}()
return true
}
return false
}
// Go .
func (tp *TaskPool) Go(f func()) {
if tp.fork(f) {
return
}
atomic.AddInt64(&tp.concurrent, -1)
select {
case tp.chQqueue <- f:
case <-tp.chClose:
}
}
// Stop .
func (tp *TaskPool) Stop() {
atomic.AddInt64(&tp.concurrent, tp.maxConcurrent)
close(tp.chClose)
}
// New .
func New(maxConcurrent int, chQqueueSize int, v ...interface{}) *TaskPool {
tp := &TaskPool{
maxConcurrent: int64(maxConcurrent - 1),
chQqueue: make(chan func(), chQqueueSize),
chClose: make(chan struct{}),
}
tp.caller = func(f func()) {
defer func() {
if err := recover(); err != nil {
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
logging.Error("taskpool call failed: %v\n%v\n", err, *(*string)(unsafe.Pointer(&buf)))
}
}()
f()
}
if len(v) > 0 {
if caller, ok := v[0].(func(f func())); ok {
tp.caller = func(f func()) {
defer atomic.AddInt64(&tp.concurrent, -1)
caller(f)
}
}
}
go func() {
for {
select {
case f := <-tp.chQqueue:
if tp.fork(f) {
continue
}
if f != nil {
tp.caller(f)
}
case <-tp.chClose:
return
}
}
}()
return tp
}