terminate_after ~seconds thunk
arranges to terminate the execution of thunk
on the current fiber after the specified timeout in seconds
.
Using terminate_after
one can attempt any blocking operation that supports cancelation with a timeout. For example, one could try to read
an Ivar
with a timeout
let peek_in ~seconds ivar =
match
Control.terminate_after ~seconds @@ fun () ->
Ivar.read ivar
with
| value -> Some value
| exception Control.Terminate -> None
or one could try to connect
a socket with a timeout
let try_connect_in ~seconds socket sockaddr =
match
Control.terminate_after ~seconds @@ fun () ->
Unix.connect socket sockaddr
with
| () -> true
| exception Control.Terminate -> false
using the Picos_io.Unix
module.
The optional callstack
argument specifies the number of callstack entries to capture with the Terminate
exception. The default is 0
.
As an example, terminate_after
could be implemented using Bundle
as follows:
let terminate_after ?callstack ~seconds thunk =
Bundle.join_after @@ fun bundle ->
Bundle.terminate_after ?callstack ~seconds bundle;
thunk ()