forked from cschleiden/go-workflows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
future.go
63 lines (47 loc) · 895 Bytes
/
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
package sync
type Future[T any] interface {
// Get returns the value if set, blocks otherwise
Get(ctx Context) (T, error)
}
type SettableFuture[T any] interface {
Future[T]
// Set stores the value and provided error
Set(v T, err error)
HasValue() bool
}
type FutureInternal[T any] interface {
Future[T]
Ready() bool
}
func NewFuture[T any]() SettableFuture[T] {
return &future[T]{}
}
type future[T any] struct {
hasValue bool
v T
err error
}
func (f *future[T]) Set(v T, err error) {
f.v = v
f.err = err
f.hasValue = true
}
func (f *future[T]) HasValue() bool {
return f.hasValue
}
func (f *future[T]) Get(ctx Context) (T, error) {
for {
cr := getCoState(ctx)
if f.hasValue {
cr.MadeProgress()
if f.err != nil {
return *new(T), f.err
}
return f.v, nil
}
cr.Yield()
}
}
func (f *future[T]) Ready() bool {
return f.hasValue
}