You have already figured out how to return either the successful result, or a “this timed out” default after 10 seconds.
So now the remaining question is: After the 10 seconds, how can you kill the now orphaned task so that it doesn’t consume system resources?
Julia only supports cooperative multithreading.
You cannot interrupt the task. This is not supported by the julia runtime. Interrupting (preempting) a thread is supported by hardware, but the julia runtime cannot recover from arbitrary points.
So instead, your task has to regularly poll something to figure out whether it is supposed to give up.
If the code is executing something you wrote, yield
is a thing, If you are in a tight loop, you can check an atomic boolean. You can also poll the current time and check whether enough time has passed.
If the code is doing IO / waiting for something, then schedule(task, InterruptException(), error=true)
does the job – once the task reaches a yield point, either from yield()
or waiting on a lock or IO, it will receive the exception (and if it is currently waiting on something, then it gets immediately woken up with the exception).
If the code is executing a tight loop that is outside of your control, without any yield points – possibly in some C library – then you are out of luck.
The appropriate approach is then to create a new process, and kill it on timeout. If the child process spawns further processes, you might need a cgroup
on linux to kill it for good, no idea about windows.
This is not a particularly unique limitation of the julia runtime. Cf eg https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html. pthreads et al don’t safely support that either.