-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbroadcast_pond.go
86 lines (79 loc) · 1.27 KB
/
broadcast_pond.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
package pipe
import (
"runtime"
"sync/atomic"
"time"
)
type pond struct {
idleCount atomic.Int32
tasks chan func()
dispatch chan func()
}
var selectorPond = newPond()
func newPond() *pond {
b := new(pond)
b.tasks = make(chan func())
b.dispatch = make(chan func())
go b.loop()
return b
}
func (b *pond) loop() {
var ticker *time.Ticker
var tickerC <-chan time.Time
var cancelC chan func()
var total int32
for {
select {
case task := <-b.tasks:
if ticker == nil {
ticker = time.NewTicker(time.Second * 5)
tickerC = ticker.C
}
if b.idleCount.Load() == 0 {
total += 1
go b.worker(task)
continue
}
fails := 0
INNER:
for {
if fails == 10 {
go b.worker(task)
break INNER
}
select {
case b.dispatch <- task:
break INNER
default:
runtime.Gosched()
fails++
}
}
case <-tickerC:
if total != 0 {
cancelC = b.dispatch
} else {
ticker.Stop()
ticker = nil
tickerC = nil
}
case cancelC <- nil:
total -= 1
if b.idleCount.Load() < total/2 {
cancelC = nil
}
}
}
}
func (b *pond) worker(task func()) {
task()
b.idleCount.Add(1)
for task = range b.dispatch {
b.idleCount.Add(-1)
if task == nil {
return
}
task()
b.idleCount.Add(1)
}
}