-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdispatcher.go
More file actions
101 lines (84 loc) · 1.76 KB
/
dispatcher.go
File metadata and controls
101 lines (84 loc) · 1.76 KB
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
// Copyright 2017 Granitic. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license that can be found in the LICENSE file at the root of this project.
package timer
import (
"errors"
)
type HashDispatcher struct {
mask int
count int
table []Dispatcher
}
func NewHashDispatcher(args ...Dispatcher) Dispatcher {
length := len(args)
if 0 != (length & (length - 1)) {
panic(errors.New("NewTimingWheel illegal length"))
}
obj := &HashDispatcher{
mask: length - 1,
table: make([]Dispatcher, length),
}
copy(obj.table, args)
return obj
}
func (h *HashDispatcher) Start() {
for _, v := range h.table {
if nil != v {
v.Start()
}
}
}
func (h *HashDispatcher) Stop() {
for _, v := range h.table {
if nil != v {
v.Stop()
}
}
}
func (h *HashDispatcher) Dispatch(fn func()) {
h.count++
h.table[h.count&h.mask].Dispatch(fn)
}
type QueueDispatcher struct {
request chan func()
dispatcher Dispatcher
length int
}
func NewQueueDispatcher(length int, dispatcher Dispatcher) Dispatcher {
return &QueueDispatcher{
length: length,
dispatcher: dispatcher,
}
}
func (q *QueueDispatcher) Start() {
if nil != q.request {
panic(errors.New("once start"))
}
q.dispatcher.Start()
q.request = make(chan func(), q.length)
go q.run()
}
func (q *QueueDispatcher) Stop() {
close(q.request)
q.dispatcher.Stop()
}
func (q *QueueDispatcher) Dispatch(fn func()) {
q.request <- fn
}
func (q *QueueDispatcher) run() {
for fn := range q.request {
q.dispatcher.Dispatch(fn)
}
q.request = nil
}
type SimpleDispatcher struct{}
func NewSimpleDispatcher() Dispatcher {
return &SimpleDispatcher{}
}
func (s *SimpleDispatcher) Start() {
}
func (s *SimpleDispatcher) Stop() {
}
func (s *SimpleDispatcher) Dispatch(fn func()) {
fn()
}