File tree 3 files changed +68
-0
lines changed
src/tests/encore/stdlib/Data
3 files changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ -- Promises are futures that you can fulfil by explictly calling a method that you pass a value.
2
+ module Promise
3
+
4
+ -- Create a promise, together with a future that can be
5
+ -- fulfilled using the promise:
6
+ -- Once you call fulfil(..) on the promise object, the
7
+ -- future returned by this call will be fulfilled.
8
+ fun mkPromise[t]() : (Fut[t], Promise[t])
9
+ val f = EMBED (Fut[t]) future_mk(_ctx, _enc__type_t); END
10
+ (f, new Promise(f))
11
+ end
12
+
13
+ -- This should be linear, but we're hitting issue #770 then
14
+ -- in the mean time, do not alias promises!
15
+ unsafe class Promise[t]
16
+ var f : Maybe[Fut[t]]
17
+
18
+ def init(f : Fut[t]): unit
19
+ this.f = Just(f)
20
+ end
21
+
22
+ def fulfil(v : t): unit
23
+ match this.f with
24
+ case Just(f) =>
25
+ EMBED (unit) future_fulfil(_ctx, #{f}, #{v}); END
26
+ this.f = Nothing
27
+ end
28
+ case Nothing => assertTrue(false, "Promise is already fulfilled!")
29
+ end
30
+ end
31
+ end
32
+
Original file line number Diff line number Diff line change
1
+ module Promise
2
+
3
+ import Data.Promise
4
+
5
+ active class Worker
6
+ val p: Promise[int]
7
+ var cnt: int
8
+ def init(var p: Promise[int]) : unit
9
+ this.p = p
10
+ this.cnt = 0
11
+ end
12
+
13
+ def work() : unit
14
+ this.cnt = this.cnt+1
15
+ if this.cnt == 3 then
16
+ this.p.fulfil(123)
17
+ end
18
+ end
19
+ end
20
+
21
+ active class Main
22
+ def main() : unit
23
+ val tpl = mkPromise[int]()
24
+ match mkPromise[int]() with
25
+ case (f, p) =>
26
+ val w = new Worker(p)
27
+ for i <- [1..100] do
28
+ w!work()
29
+ end
30
+ val x = get(f)
31
+ println("gotten {}", x)
32
+ end
33
+ end
34
+ end
35
+ end
Original file line number Diff line number Diff line change
1
+ gotten 123
You can’t perform that action at this time.
0 commit comments