I’m seeking some help. I’d like to write a function:
val timeout: fn: (unit -> ‘a) -> tout: float -> ‘a option
such that ‘timeout’ will try evaluate the ‘fn’ function and outputs:
-) ‘Some res’, if the evaluation of ‘fn’ was finished before ‘tout’ seconds (note that ‘fn’ should be able to start other threads or use the ‘Unix.system’ call), or
-) None, if the evaluation took more than ‘tout’ second (in which case it should be stopped at that point).
Now I had the idea that it should be pretty simple to write it using Ocaml threads library by simply starting two threads: one that will simply wait for ‘tout’ seconds and then communicate (using Events library) the fact that the timeout has occurred and the other one that will evaluate the ‘fn’ function and communicate back its results. The problem is that upon receiving result from one of the threads the other one should be terminated. At that point I discovered, to my disappointment, that if try to use the ‘Threads.kill’ routine I get an exception informing that it’s not implemented. Now, letting the clock thread continue is acceptable but the computation expensive thread struggling with ‘fn’ function should absolutely stop after the timeout.
Any ideas how to fix that? Or maybe there is a simpler solution to my goal?
Would such function be interesting for ExtLib?
Thank you in advance for any help,
Department of Mathematics and Computer Science
The difference between impossible and possible lies in determination