Skip to content

Commit 0080913

Browse files
committed
Fix wakeup state machine
1 parent 34c8798 commit 0080913

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

lib/picos_select/picos_select.ml

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,10 @@ type return_on =
2626
}
2727
-> return_on
2828

29+
type phase = Continue | Select | Waking_up | Process
30+
2931
type state = {
30-
phase : [ `Select | `Continue | `Process ] Atomic.t;
32+
phase : phase Atomic.t;
3133
mutable state : [ `Initial | `Starting | `Alive | `Stopping | `Stopped ];
3234
mutable exn_bt : Exn_bt.t;
3335
mutable pipe_inn : Unix.file_descr;
@@ -47,7 +49,7 @@ let exit_exn_bt = Exn_bt.get_callstack 0 Exit
4749
let key =
4850
Picos_domain.DLS.new_key @@ fun () ->
4951
{
50-
phase = Atomic.make `Continue;
52+
phase = Atomic.make Continue;
5153
state = `Initial;
5254
exn_bt = exit_exn_bt;
5355
pipe_inn = Unix.stdin;
@@ -74,11 +76,11 @@ let[@poll error] [@inline never] transition s into =
7476

7577
let rec wakeup s from =
7678
match Atomic.get s.phase with
77-
| `Process ->
79+
| Process | Waking_up ->
7880
(* The thread will process the fds and timeouts before next select. *)
7981
()
80-
| `Continue ->
81-
if Atomic.compare_and_set s.phase `Continue `Process then
82+
| Continue ->
83+
if Atomic.compare_and_set s.phase Continue Process then
8284
(* We managed to signal the wakeup before the thread was ready to call
8385
select and the thread will notice this without us needing to write to
8486
the pipe. *)
@@ -87,8 +89,8 @@ let rec wakeup s from =
8789
(* Either the thread called select or another wakeup won the race. We
8890
need to retry. *)
8991
wakeup s from
90-
| `Select ->
91-
if Atomic.compare_and_set s.phase `Select `Continue then
92+
| Select ->
93+
if Atomic.compare_and_set s.phase Select Waking_up then
9294
if s.state == from then
9395
(* We are now responsible for writing to the pipe to force the thread to
9496
exit the select. *)
@@ -149,7 +151,7 @@ let rec process_timeouts s =
149151

150152
let rec select_thread s timeout rd wr ex =
151153
if s.state == `Alive then
152-
if Atomic.compare_and_set s.phase `Continue `Select then
154+
if Atomic.compare_and_set s.phase Continue Select then
153155
begin
154156
try
155157
Unix.select
@@ -162,9 +164,9 @@ let rec select_thread s timeout rd wr ex =
162164

163165
and select_thread_continue s rd wr ex (rd_fds, wr_fds, ex_fds) =
164166
begin
165-
match Atomic.exchange s.phase `Continue with
166-
| `Select | `Process -> ()
167-
| `Continue ->
167+
match Atomic.exchange s.phase Continue with
168+
| Select | Process | Continue -> ()
169+
| Waking_up ->
168170
let n = Unix.read s.pipe_inn s.byte 0 1 in
169171
assert (n = 1)
170172
end;

0 commit comments

Comments
 (0)