package picos
Install
Dune Dependency
Authors
Maintainers
Sources
sha256=544804c0bde4b29764f82f04e7defed7c06bc43e5a6ce3f7fdc326cb54a7f066
sha512=4c93427e477fb52374a554a8b9c4c92836a9b5899161275d1473269ab526a1f59177209140631ed763a55be375855dea12f076e18bf4124522414986c0e257be
doc/picos.structured/Picos_structured/Finally/index.html
Module Picos_structured.Finally
Source
Syntax for avoiding resource leaks.
A pair of release and acquire functions.
finally release acquire
is equivalent to (release, acquire)
.
let@ resource = finally release acquire in scope
calls acquire ()
to obtain a resource
, evaluates scope
, and calls release resource
whether scope
returns normally or raises an exception.
Here is a sketch of a server that recursively forks a fiber to accept and handle a client:
Bundle.join_after @@ fun bundle ->
let rec accept () =
let@ client =
finally Unix.close @@ fun () ->
Unix.accept ~cloexec:true socket |> fst
in
(* fork to accept other clients *)
Bundle.fork bundle accept;
(* handle this client... omitted *)
in
Bundle.fork bundle accept
There is also a way to move
resources to allow forking fibers to handle clients without leaks.
A moveable
either contains a resource or is empty as the resource has been moved.
let^ moveable = finally release acquire in scope
calls acquire ()
to obtain a resource and stores it as a moveable
resource. Then, at the end of scope
, awaits that the resource is moved out of the moveable
or release
s the resource in case of cancelation.
move moveable
creates a pair of release and acquire functions where the acquire operation takes the resource from the moveable
and the release operation releases the resource.
Here is a sketch of a server that accepts in a loop and forks fibers to handle clients:
Bundle.join_after @@ fun bundle ->
while true do
(* loop to accept clients *)
let^ client =
finally Unix.close @@ fun () ->
Unix.accept ~closexec:true socket |> fst
in
(* fork to handle this client *)
Bundle.fork bundle @@ fun () ->
let@ client = move client in
(* handle client... omitted *)
done
Another alternative to avoiding leaks is to recursively fork fibers to accept and handle a client.