How to interrupt something that works too long in OCaml 5.x

I want to run arbitrary code and kill it if it works longer than N seconds. Arbitrary means there is not any yield or sleep in the code to pass control to the scheduler.

The question was asked before on SO: Interrupt a call in OCaml - Stack Overflow but the solution was kind of unsatisfactory. The Thread.kill function is not really implemented. The solution that kind of worked for me, is to spawn a OS process per task and kill them on demand.

Did something changed in OCaml 5.x? Do I leave in the better world of the year 2024?

I don’t think that’s a good idea, whether OCaml supports it or not.
For example, what if the code in question acquired a lock and is midway through modifying a data structure?
Should we keep the lock, and will it be forever forbidden to acquire it again?
Should we release the lock and make the half-modified structure visible to other threads?
Function interruption has to cooperative to work in the general case.

1 Like