Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Condition.await bug when cancelling #487

Merged
merged 1 commit into from
Apr 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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".
```