Set a timer for a function Set a timer for a function unix unix

Set a timer for a function


Something like this might work for you:

exception Timeoutlet run_with_timeout t f x =    try        Sys.set_signal Sys.sigalrm (Sys.Signal_handle (fun _ -> raise Timeout));        ignore (Unix.alarm t);        f x;        ignore (Unix.alarm 0);        Sys.set_signal Sys.sigalrm Sys.Signal_default    with Timeout -> Sys.set_signal Sys.sigalrm Sys.Signal_default

Here's a session that shows how it works:

$ ocaml        OCaml version 4.00.1# #load "unix.cma";;# #use "rwt.ml";;exception Timeoutval run_with_timeout : int -> ('a -> 'b) -> 'a -> unit = <fun># run_with_timeout 2 Printf.printf "yes\n";;yes- : unit = ()# run_with_timeout 2 (fun () -> while true do () done) ();;- : unit = ()#

Your code would be something like this:

List.iter (run_with_timeout 10 f) data

(This code hasn't been thorougly tested but it shows a way that might work.)

Update

As the comments have shown, this code isn't suitable if f x might throw an exception (or if you're using alarms for some other purpose). I encourage gsg to post his/her improved solution. The edit seems to have been rejected.


This is based on Jeffrey's answer, with some modifications to improve exception safety:

exception Timeoutlet run_with_timeout timeout f x =  let old_handler = Sys.signal Sys.sigalrm    (Sys.Signal_handle (fun _ -> raise Timeout)) in  let finish () =    ignore (Unix.alarm 0);    ignore (Sys.signal Sys.sigalrm old_handler) in  try    ignore (Unix.alarm timeout);    ignore (f x);    finish ()  with Timeout -> finish ()   | exn -> finish (); raise exn