package picos
Install
dune-project
Dependency
Authors
Maintainers
Sources
sha256=343a8b4759239ca0c107145b8e2cc94c14625fecc0b0887d3c40a9ab7537b8da
sha512=db22b0a5b3adc603c0e815c9011c779f892b9ace76be018b2198d3e24a7d96727c999701025fe5a5fd07d0b452cb7286fc50c939aba0e4dce809941e9ebc12a6
doc/picos.structured/Picos_structured/Finally/index.html
Module Picos_structured.FinallySource
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_fd =
finally Unix.close @@ fun () ->
Unix.accept ~cloexec:true server_fd
|> fst
in
(* fork to accept other clients *)
Bundle.fork bundle accept;
(* handle this client... omitted *)
in
Bundle.fork bundle acceptThere 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 releases 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_fd =
finally Unix.close @@ fun () ->
Unix.accept ~closexec:true server_fd
|> fst
in
(* fork to handle this client *)
Bundle.fork bundle @@ fun () ->
let@ client_fd = move client_fd in
(* handle client... omitted *)
doneAnother alternative to avoiding leaks is to recursively fork fibers to accept and handle a client.