Skip to content

Make Lwt compatible with CPS. - #206

Closed
aantron wants to merge 1 commit into
ocsigen:masterfrom
aantron:master
Closed

aantron wants to merge 1 commit into
ocsigen:masterfrom
aantron:master

Conversation

@aantron

@aantron aantron commented Jan 6, 2016

Copy link
Copy Markdown
Collaborator

Adds a version of on_any that performs tail calls on f and g. The following test program:

let repeat : int -> (unit -> unit) -> unit = fun limit k ->
  let rec loop n =
    if n >= limit then k ()
    else Lwt.on_any Lwt.return_unit (fun () -> loop (n + 1)) ignore
  in
  loop 0

let () = repeat 100000 ignore

Fails with a stack overflow, when compiled and run as:

ocamlfind opt -linkpkg -package lwt test.ml && ulimit -s 128 && ./a.out

This is because Lwt.on_any wraps the calls to f and g in exception handlers, resulting in a growing stack. Replacing Lwt.on_any with Lwt.on_any_unsafe fixes the problem.

I am working with CPS code, and this helps to interface it to Lwt. I think this can also be accomplished by exposing a function in Lwt that can tail-call a function on the completion of any given thread. I could then use that function together with a reference to get the same result. I think the solution in the current diff is more sensible, however.

Comment thread src/core/lwt.mli Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The no seems superfluous.

This change adds a variant of on_any, on_any_unsafe, such that the
calls to f and g in on_any_unsafe t f g are tail calls. This makes the
new function suitable for converting between continuation-passing style
and Lwt code.
@aantron

aantron commented Jan 7, 2016

Copy link
Copy Markdown
Collaborator Author

Oops, fixed.

I am not sure what the best name for this function is, or what to focus on in the documentation.

@aantron

aantron commented Mar 30, 2016

Copy link
Copy Markdown
Collaborator Author

@aantron

aantron commented Dec 6, 2016

Copy link
Copy Markdown
Collaborator Author

It's possible to get tail calls of f and g in what would otherwise be Lwt.on_any t f g like so:

match Lwt.state t with
| Lwt.Return v -> f v
| Lwt.Fail exn -> g exn
| Lwt.Sleep -> Lwt.on_any t f g
  (* Can't get tail calls on a sleeping thread anyway, use Lwt.wakeup_later to
     control stack growth for sleeping threads. *)

So this is closed as not necessary right now.

Will add some kind of mention of this in the API documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants