clojure (with-timeout … macro)

前端 未结 3 716
-上瘾入骨i
-上瘾入骨i 2021-02-09 01:50

I\'m looking for a macro that will throw an exception if an expression takes longer than X seconds to complete.

3条回答
  •  情歌与酒
    2021-02-09 02:48

    I'm not sure this is possible without running the expression in a separate thread. The reason being, if the thread is busy processing the expression, you can't inject code to throw an exception.

    A version with a monitor thread that throws an exception if the expression takes too long is definitely possible, however, the exception thrown would be from the monitor thread, not the thread in which the expression is running. Then, there'd be no way of stopping it short of sending that thread an interrupt, which it might ignore if you haven't coded for it in the expression.

    If it's acceptable to have a version which runs the expression in a separate thread, let me know and I can post some sample code. Otherwise, your best bet sound like it would be to write the main loop/recursion of the expression in such a way that it checks to see how long it has taken at every iteration and throws an exception if it's exceeded the bound. Sorry if that's not quite what you need...

提交回复
热议问题