forked from dop251/goja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.go
83 lines (74 loc) · 1.17 KB
/
scheduler.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
package loop
import (
"sync/atomic"
)
type Worker interface {
Serve()
}
type funcWorker struct {
f func()
}
func (f funcWorker) Serve() {
if f.f != nil {
f.f()
}
}
func NewWorker(f func()) Worker {
return funcWorker{
f: f,
}
}
type Scheduler interface {
Go(w Worker)
Stop()
}
var defaultScheduler Scheduler = goScheduler{}
type goScheduler struct{}
func (goScheduler) String() string {
return `DefaultScheduler`
}
func (goScheduler) Go(w Worker) {
go w.Serve()
}
func (g goScheduler) Stop() {}
type asyncScheduler struct {
stoped int32
stop chan struct{}
ch chan Worker
}
func NewScheduler(idle int) Scheduler {
if idle < 1 {
return defaultScheduler
}
scheduler := &asyncScheduler{
stop: make(chan struct{}),
ch: make(chan Worker),
}
for i := 0; i < idle; i++ {
go scheduler.serve()
}
return scheduler
}
func (a *asyncScheduler) serve() {
for {
select {
case <-a.stop:
return
case w := <-a.ch:
w.Serve()
}
}
}
func (a *asyncScheduler) Go(w Worker) {
select {
case <-a.stop:
case a.ch <- w:
default:
go w.Serve()
}
}
func (a *asyncScheduler) Stop() {
if a.stoped == 0 && atomic.SwapInt32(&a.stoped, 1) == 0 {
close(a.stop)
}
}