This repository was archived by the owner on Jan 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathschedule.go
121 lines (104 loc) · 1.7 KB
/
schedule.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
109
110
111
112
113
114
115
116
117
118
119
120
121
package sync2
// WARNNING: UNTESTED
import (
"sync"
)
type Signal struct {
s chan byte
lock sync.Mutex
}
func NewSignal() *Signal {
return &Signal{
s: make(chan byte, 1),
}
}
func (s *Signal) Wait() {
<-s.s
}
func (s *Signal) Notify() {
s.lock.Lock()
if len(s.s) == 0 {
s.s <- 0
}
s.lock.Unlock()
}
// Task Schedule By scale, each user has his scale
type Task interface {
Execute()
}
type TaskFunc func()
func (f TaskFunc) Execute() {
f()
}
type Queue struct {
sync.Mutex
tasks []Task
}
func (q *Queue) Enqueue(t Task) bool {
q.Lock()
defer q.Unlock()
if len(q.tasks) == cap(q.tasks) {
return false
}
q.tasks = append(q.tasks, t)
return true
}
func (q *Queue) Dequeue() Task {
q.Lock()
defer q.Unlock()
if l := len(q.tasks); l == 0 {
return nil
} else {
t := q.tasks[l-1]
q.tasks = q.tasks[:l-1]
return t
}
}
type Scheduler struct {
cond *Signal
queues map[uint32]*Queue
}
func New() *Scheduler {
return &Scheduler{
cond: NewSignal(),
queues: make(map[uint32]*Queue),
}
}
func (s *Scheduler) AddTask(id uint32, t Task) (success bool) {
if q := s.queues[id]; q != nil {
if success = q.Enqueue(t); !success {
for _, q = range s.queues {
if q.Enqueue(t) {
success = true
s.cond.Notify()
break
}
}
} else {
s.cond.Notify()
}
}
return
}
func (s *Scheduler) GetTask() Task {
for _, q := range s.queues {
if t := q.Dequeue(); t != nil {
return t
}
}
return nil
}
func (s *Scheduler) AddQueue(id uint32, capacity int) {
s.queues[id] = &Queue{tasks: make([]Task, 0, capacity)}
}
func (s *Scheduler) Run() {
go func() {
for {
if t := s.GetTask(); t != nil {
t.Execute()
} else {
s.cond.Wait()
}
}
}()
}