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
|
# Setting up the environment
```ocaml
# #require "eio.mock";;
```
```ocaml
open Eio.Std
let test label v =
traceln "%s: forcing..." label;
match Eio.Lazy.force v with
| v ->
Fiber.check ();
traceln "%s: %d" label v
| exception ex ->
traceln "%s: %a" label Fmt.exn ex;
Fiber.check ()
```
# Tests
Two fibers request the value. It's only computed once:
```ocaml
# Eio_mock.Backend.run @@ fun () ->
let v = Eio.Lazy.from_fun ~cancel:`Restart (fun () ->
traceln "calculating...";
Fiber.yield ();
traceln "complete";
42
) in
Fiber.both
(fun () -> test "a" v)
(fun () -> test "b" v)
;;
+a: forcing...
+calculating...
+b: forcing...
+complete
+a: 42
+b: 42
- : unit = ()
```
The calculation fails. It's still only performed once:
```ocaml
# Eio_mock.Backend.run @@ fun () ->
let v = Eio.Lazy.from_fun ~cancel:`Restart (fun () ->
traceln "calculating...";
Fiber.yield ();
failwith "failed";
) in
Fiber.both
(fun () -> test "a" v)
(fun () -> test "b" v)
;;
+a: forcing...
+calculating...
+b: forcing...
+a: Failure("failed")
+b: Failure("failed")
- : unit = ()
```
## Cancellation
The first fiber cancels. What happens depends on the cancel mode:
```ocaml
let test_cancel cancel =
Eio_mock.Backend.run @@ fun () ->
let v = Eio.Lazy.from_fun ~cancel (fun () ->
traceln "calculating...";
Fiber.yield ();
traceln "complete";
42
) in
Fiber.both
(fun () ->
let x =
Fiber.first
(fun () -> test "a" v; assert false)
(fun () -> 5)
in
traceln "a: %d" x
)
(fun () -> test "b" v)
;;
```
In record mode, the second fiber sees the cancelled exception:
```ocaml
# test_cancel `Record;;
+a: forcing...
+calculating...
+b: forcing...
+a: Cancelled: Eio__core__Fiber.Not_first
+b: Cancelled: Eio__core__Fiber.Not_first
+a: 5
- : unit = ()
```
In protect mode, the first calculation succeeds:
```ocaml
# test_cancel `Protect;;
+a: forcing...
+calculating...
+b: forcing...
+complete
+b: 42
+a: 5
- : unit = ()
```
In restart mode, the second fiber restarts the calculation:
```ocaml
# test_cancel `Restart;;
+a: forcing...
+calculating...
+b: forcing...
+a: Cancelled: Eio__core__Fiber.Not_first
+calculating...
+a: 5
+complete
+b: 42
- : unit = ()
```
|