forked from asynkron/protoactor-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
futures.go
115 lines (95 loc) · 1.93 KB
/
futures.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
package actor
import (
"errors"
"log"
"sync"
"time"
)
var (
ErrTimeout = errors.New("timeout")
)
func NewFuture(timeout time.Duration) *Future {
fut := &Future{cond: sync.NewCond(&sync.Mutex{})}
ref := &futureProcess{f: fut}
id := ProcessRegistry.NextId()
pid, ok := ProcessRegistry.Add(ref, id)
if !ok {
log.Printf("[ACTOR] Failed to register future actorref '%v'", id)
log.Println(id)
}
fut.pid = pid
fut.t = time.AfterFunc(timeout, func() {
fut.err = ErrTimeout
ref.Stop(pid)
})
return fut
}
type Future struct {
pid *PID
cond *sync.Cond
// protected by cond
done bool
result interface{}
err error
t *time.Timer
}
// PID to the backing actor for the Future result
func (f *Future) PID() *PID {
return f.pid
}
// PipeTo starts a go routine and waits for the `Future.Result()`, then sends the result to the given `PID`
func (f *Future) PipeTo(pid *PID) {
go func() {
res, err := f.Result()
if err != nil {
pid.Tell(err)
} else {
pid.Tell(res)
}
}()
}
func (f *Future) ContinueWith(fun func(f *Future)) {
go func() {
f.Wait()
fun(f)
}()
}
func (f *Future) wait() {
f.cond.L.Lock()
for !f.done {
f.cond.Wait()
}
f.cond.L.Unlock()
}
func (f *Future) Result() (interface{}, error) {
f.wait()
return f.result, f.err
}
func (f *Future) Wait() error {
f.wait()
return f.err
}
// futureProcess is a struct carrying a response PID and a channel where the response is placed
type futureProcess struct {
f *Future
}
func (ref *futureProcess) SendUserMessage(pid *PID, message interface{}, sender *PID) {
ref.f.result = message
ref.Stop(pid)
}
func (ref *futureProcess) SendSystemMessage(pid *PID, message SystemMessage) {
ref.f.result = message
ref.Stop(pid)
}
func (ref *futureProcess) Stop(pid *PID) {
ref.f.cond.L.Lock()
if ref.f.done {
ref.f.cond.L.Unlock()
return
}
ref.f.done = true
ref.f.t.Stop()
ProcessRegistry.Remove(pid)
ref.f.cond.L.Unlock()
ref.f.cond.Signal()
}