-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patheventloop.go
More file actions
132 lines (119 loc) · 2.29 KB
/
Copy patheventloop.go
File metadata and controls
132 lines (119 loc) · 2.29 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package liblpc
import (
"container/list"
"context"
"github.com/gen-iot/std"
"io"
"sync/atomic"
)
type EventLoop interface {
io.Closer
RunInLoop(cb func())
Notify()
Run(ctx context.Context)
Break()
Poller() Poller
}
type evtLoop struct {
poller Poller
notify LoopNotify
cbQ *list.List
lock *SpinLock
closeFlag int32
stopFlag int32
endRunSig chan struct{}
}
func NewEventLoop() (EventLoop, error) {
poller, err := DefaultPollerCreator(1024) // todo use system default poller
if err != nil {
return nil, err
}
return NewEventLoop2(poller, DefaultLoopNotifyCreator)
}
func NewEventLoop2(poller Poller, builder LoopNotifyBuilder) (EventLoop, error) {
var err error = nil
l := new(evtLoop)
//
l.poller = poller
//
l.notify, err = builder(l, l.processPending)
if err != nil {
std.CloseIgnoreErr(l.poller)
return nil, err
}
l.notify.Update(true)
//
l.cbQ = list.New()
l.lock = NewSpinLock()
l.closeFlag = 0
l.stopFlag = 0
l.endRunSig = make(chan struct{})
return l, nil
}
func (this *evtLoop) RunInLoop(cb func()) {
if atomic.LoadInt32(&this.stopFlag) == 1 {
cb()
return
}
this.lock.Lock()
this.cbQ.PushBack(cb)
this.lock.Unlock()
this.Notify()
}
func (this *evtLoop) Notify() {
this.notify.Notify()
}
func (this *evtLoop) processPending() {
this.lock.Lock()
ls := this.cbQ
this.cbQ = list.New()
this.lock.Unlock()
for ls.Len() != 0 {
front := ls.Front()
val := front.Value.(func())
ls.Remove(front)
val()
}
}
func (this *evtLoop) Break() {
if atomic.LoadInt32(&this.stopFlag) == 1 {
return
}
atomic.StoreInt32(&this.stopFlag, 1)
this.Notify()
}
func (this *evtLoop) Close() error {
<-this.endRunSig
if atomic.CompareAndSwapInt32(&this.closeFlag, 0, 1) {
_ = this.poller.Close()
_ = this.notify.Close()
}
return nil
}
func (this *evtLoop) Poller() Poller {
return this.poller
}
func (this *evtLoop) Run(ctx context.Context) {
if atomic.LoadInt32(&this.stopFlag) == 1 {
panic("loop already finished!, don't reuse it")
}
if ctx != nil {
go func() {
select {
case <-ctx.Done():
this.Break()
case <-this.endRunSig:
// workaround if user never fill `ctx`
return
}
}()
}
for {
if atomic.LoadInt32(&this.stopFlag) == 1 {
break
}
_ = this.poller.Poll(-1)
}
this.processPending()
close(this.endRunSig)
}