Skip to content

Commit

Permalink
Merge pull request #487 from talex5/fix-cond
Browse files Browse the repository at this point in the history
Fix Condition.await bug when cancelling
  • Loading branch information
talex5 authored Apr 14, 2023
2 parents 1277485 + 4fac85f commit 9656b89
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib_eio/condition.ml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ type t = Broadcast.t

let create () = Broadcast.create ()

let lock_protected m =
Cancel.protect (fun () -> Eio_mutex.lock m)

let await_generic ?mutex t =
match
Suspend.enter_unchecked (fun ctx enqueue ->
Expand All @@ -21,10 +24,10 @@ let await_generic ?mutex t =
)
)
with
| () -> Option.iter Eio_mutex.lock mutex
| () -> Option.iter lock_protected mutex
| exception ex ->
let bt = Printexc.get_raw_backtrace () in
Option.iter Eio_mutex.lock mutex;
Option.iter lock_protected mutex;
Printexc.raise_with_backtrace ex bt

let await t mutex = await_generic ~mutex t
Expand Down
35 changes: 35 additions & 0 deletions tests/condition.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,38 @@ Cancellation while waiting:
+x = 0
- : unit = ()
```

### Cancelling while the mutex is held

`await` must always re-acquire the lock, and that lock operation must be non-cancellable:

```ocaml
# Eio_mock.Backend.run @@ fun () ->
Switch.run @@ fun sw ->
Fiber.fork ~sw
(fun () ->
traceln "Forked fiber locking";
Eio.Mutex.lock mutex;
try
Eio.Condition.await cond mutex;
assert false;
with Eio.Cancel.Cancelled _ as ex ->
traceln "Forked fiber unlocking";
Eio.Mutex.unlock mutex;
raise ex
);
Eio.Cancel.protect
(fun () ->
traceln "Main fiber locking";
Eio.Mutex.lock mutex;
Switch.fail sw (Failure "Simulated error");
Fiber.yield ();
traceln "Main fiber unlocking";
Eio.Mutex.unlock mutex;
)
+Forked fiber locking
+Main fiber locking
+Main fiber unlocking
+Forked fiber unlocking
Exception: Failure "Simulated error".
```

0 comments on commit 9656b89

Please sign in to comment.