-
Notifications
You must be signed in to change notification settings - Fork 31
/
future.go
90 lines (69 loc) · 1.32 KB
/
future.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
package tachyon
import (
"sync"
"time"
)
type Future struct {
Task *Task
Start time.Time
Runtime time.Duration
result *Result
err error
wg sync.WaitGroup
}
func NewFuture(start time.Time, task *Task, f func() (*Result, error)) *Future {
fut := &Future{Start: start, Task: task}
fut.wg.Add(1)
go func() {
r, e := f()
fut.result = r
fut.err = e
fut.Runtime = time.Since(fut.Start)
fut.wg.Done()
}()
return fut
}
func (f *Future) Wait() {
f.wg.Wait()
}
func (f *Future) Value() (*Result, error) {
f.Wait()
return f.result, f.err
}
func (f *Future) Read() interface{} {
f.Wait()
return f.result
}
type Futures map[string]*Future
type FutureScope struct {
Scope
futures Futures
}
func NewFutureScope(parent Scope) *FutureScope {
return &FutureScope{
Scope: parent,
futures: Futures{},
}
}
func (fs *FutureScope) Get(key string) (Value, bool) {
if v, ok := fs.futures[key]; ok {
return v, ok
}
return fs.Scope.Get(key)
}
func (fs *FutureScope) AddFuture(key string, f *Future) {
fs.futures[key] = f
}
func (fs *FutureScope) Wait() {
for _, f := range fs.futures {
f.Wait()
}
}
func (fs *FutureScope) Results() []RunResult {
var results []RunResult
for _, f := range fs.futures {
f.Wait()
results = append(results, RunResult{f.Task, f.result, f.Runtime})
}
return results
}