Last active
June 1, 2022 23:26
-
-
Save Skyb0rg007/a4f76d2ad38f5946c6896e45511589d7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local | |
structure Cont = SMLofNJ.Cont | |
structure IntervalTimer = SMLofNJ.IntervalTimer | |
structure S = Signals | |
in | |
(* `withTimeout t f` calls `f ()` and returns `SOME x` where `x` is the result of the function call. | |
* If `f ()` takes longer than `t` to execute, `withTimeout` instead returns `NONE` *) | |
fun withTimeout t f = | |
let | |
val result = ref NONE | |
val oldhandler = ref NONE | |
fun restore () = | |
(IntervalTimer.setIntTimer NONE | |
; S.setHandler (S.sigALRM, Option.valOf (!oldhandler))) | |
fun makeHandler k = S.HANDLER (fn _ => (restore (); k)) | |
in | |
Cont.callcc (fn k => | |
(oldhandler := SOME (S.setHandler (S.sigALRM, makeHandler k)) | |
; IntervalTimer.setIntTimer (SOME t) | |
; result := SOME (f ()) | |
; ignore (restore ()))) | |
; !result | |
end | |
val _: Time.time -> (unit -> 'a) -> 'a option = withTimeout | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment