-
Notifications
You must be signed in to change notification settings - Fork 2
/
eventloop.go
135 lines (123 loc) · 2.42 KB
/
eventloop.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package go_future
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
)
var (
once sync.Once
GlobalEventLoop *eventLoop
)
func InitGlobalEventLoop() Future {
once.Do(func() {
var queue []func() bool
var lock sync.Mutex
// event loop
go func() {
for work := range eventBus {
lock.Lock()
queue = append(queue, *work)
lock.Unlock()
}
}()
go func() {
for {
n := len(queue)
var retry []func() bool
for i := 0; i < n; i++ {
currentWork := queue[i]
if done := currentWork(); !done {
retry = append(retry, currentWork)
}
}
lock.Lock()
queue = queue[n:]
queue = append(queue, retry...)
lock.Unlock()
}
}()
GlobalEventLoop = &eventLoop{promiseQueue: make([]*Promise, 0)}
})
return GlobalEventLoop
}
type Future interface {
Async(fn func() (any, error)) *Promise
Run()
}
type eventLoop struct {
promiseQueue []*Promise
size int64
sync sync.Mutex
}
func (e *eventLoop) Run() {
//await all promises
e.awaitAll()
}
func (e *eventLoop) Async(fn func() (any, error)) *Promise {
resultChan := make(chan any)
errChan := make(chan error)
p := e.newPromise(resultChan, errChan)
go func() {
recoveryHandler := promiseRecovery(resultChan, errChan)
defer func() {
if r := recover(); r != nil {
switch x := r.(type) {
case error:
recoveryHandler(nil, x)
default:
recoveryHandler(nil, fmt.Errorf("%v", x))
}
}
}()
result, err := fn()
recoveryHandler(result, err)
}()
return p
}
func promiseRecovery(resultChan chan any, errChan chan error) func(result any, err error) {
return func(result any, err error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*1)
defer cancel()
if err != nil {
select {
case errChan <- err:
case <-ctx.Done():
}
return
}
select {
case resultChan <- result:
case <-ctx.Done():
}
}
}
func (e *eventLoop) awaitAll() {
init := true
outer:
for {
n := len(e.promiseQueue)
if init && n == 0 {
return
}
for i := n - 1; i >= 0; i-- {
e.sync.Lock()
p := e.promiseQueue[i]
e.sync.Unlock()
if p.handler {
<-p.done
}
if currentN := int(atomic.LoadInt64(&e.size)); i == 0 && !(currentN > n) {
close(eventBus)
break outer
}
}
// clean up memory (promise)
e.sync.Lock()
e.promiseQueue = e.promiseQueue[n:]
atomic.AddInt64(&e.size, int64(-n))
e.sync.Unlock()
init = false
}
}