Best practice for sub-second timeout operation

Hi Everyone,

I am in need of a timeout function, that will interrupt the current computation after an x amount of time. This needs to have a sub-second resolution, so I cannot use Unix.alarm. I will also use this frequently, so forking the process all the time is also not an option. Ocaml multicore is also not an option for now. The best I came up with is to have two long-running processes communicate with each other over a socket to repeatedly set timeouts and send interrupts. lwt-parallel looks like a good library to implement this, but unfortunately it is only available for OCaml < 4.08.0 and I am using the new monad notations in 4.08.0 :frowning:

But I cannot be the first person to run into this issue. Does anyone have any experience with this problem? Is there a good implementation laying around somewhere?

Thanks!

The Unix.setitimer function (see the doc) takes a float for the timeout, so I think it may be able to deal with sub-second timeouts (but it’d be better to check if it works in practice).

Ah, I had seen that function, but I thought it was for measuring time. But I see I was wrong. Thanks! Hopefully this will work.

However, I immediately have a follow-up question: The docs state that Unix.setitimer is not implemented on Windows. Is there any known cross-platform solution?

I have confirmed that they work. Thanks for your answer!

If at some point you’re interested in a POSIX solution with no signal interrupt, select will do it also:

let wait n = ignore (Unix.select [] [] [] n)