About the granularity of Deferred.any and Async scheduler

19 views
Skip to first unread message

Mark Li

unread,
Aug 20, 2014, 12:21:25 PM8/20/14
to ocaml...@googlegroups.com
For the code below:

let test () =
  Deferred.any 
  [after (sec 0.5) >>| (fun () -> print_endline "0.5s comes first")
  ;after (sec 0.501) >>| (fun () -> print_endline "What?!")
  ]

let () = test () |> don't_wait_for

let () = never_returns (Scheduler.go ())

The result I get varies. 
Sometimes I get:
0.5s comes first
What?!

But sometimes I only get:
0.5s comes first

I am a beginner. Would someone please tell me the reason?

Thanks a lot!

Malcolm Matalka

unread,
Aug 20, 2014, 1:05:20 PM8/20/14
to ocaml...@googlegroups.com
[any] does not stop any deferreds from being evaluated it just returns
when the first one is.

Perhaps you want something like [choice]

let choice1 = choice (after (sec 0.5)) (fun () -> `First) in
let choice2 = choice (after (sec 0.501) (fun () -> `Second) in
choose [choice1; choice2]
>>= function
| `First -> something
| `Second -> something_else

David House

unread,
Aug 21, 2014, 8:00:18 AM8/21/14
to ocaml...@googlegroups.com
Mark, are you sure that that is your entire program, and you're not calling shutdown/exit anywhere?

If I run your program, I predictably get both lines of output, and then the program waits forever, because you never call shutdown.

However, if you were calling shutdown after the Deferred.any became deferred, then there would be a race condition between the "What?!" printing and the program shutting down. So sometimes you would get "What?!" printed, and sometimes not.

Malcolm, your first sentence is true (and the thing you suggest seems like the right remedy), but I'm not sure how that applies in this case.


--
You received this message because you are subscribed to the Google Groups "ocaml-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ocaml-core+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Mark Li

unread,
Aug 21, 2014, 8:04:28 AM8/21/14
to ocaml...@googlegroups.com
Sorry David and Malcolm, I forgot to type 'exit 0'. The original program has line 'let () = don't_wait_for (test () >>= fun () -> exit 0)'

Mark Li

unread,
Aug 21, 2014, 8:05:23 AM8/21/14
to ocaml...@googlegroups.com
Thanks, Malcolm. I should use 'Deferred.choose'.
Reply all
Reply to author
Forward
0 new messages