How to interrupt ocaml program on user input

Viewed 87

I have a program that can indefinitely look for an optimal solution to my problem. I let the user decide the time it can run to find a solution and once this time is spent, the program stop, create some log files, print some debug data and show the best solution found.

Now, I'd like to allow the user to stop the program earlier by prompting some message in the terminal if he doesn't want to wait until the end.

I found how to do it in python thanks to this answer, and was thinking if it would be possible to have the same architecture in OCaml.

Ideally, I would have 2 threads :

(* ___ Main thread ___ *)
start_program_thread();
Printf.printf "prompt `kill` to stop the program%!";
let rec aux() = match input_line() with 
  | "kill" -> (* user_didnt_stop set to false *)
  | _ -> aux()
in aux()


(* __________________________ *)


(* ___ Program thread ___ *)
while user_didnt_stop && Sys.time() -. start_time < max_time do
 (* search for optimal solution *)
done;
create_log_files();
send_debug_datas();
show_best_solution()

Can this be achieved with the Thread lib ?

Would it be possible to allow the program thread to print things without breaking the main program ?

I'm working with OCaml 4.12.0 with the diskuv-ocaml windows install

1 Answers

The input_line function blocks in the operating system so in order to unblock it, you have to use the corresponding facilities of your operating system or, alternatively, stick to the non-blocking IO. You can definitely use the Unix module to implement that but it is hard and tedious to do this in a potable way. The good news is that someone already did it. There are plenty of solutions in OCaml, starting from using non-blocking asynchronous-style IO, like Lwt or Async, or using specialized readline-like libraries.

Related