;; Returns the value of (thunk), timing out
;; after 'seconds' seconds and returning the given default
;; if the thunk takes too long to run.
(define (timeout-exec seconds thunk default)
(call-in-nested-thread (lambda ()
(define mainthread (current-thread))
(define execthread
(thread (lambda ()
(thread-send mainthread (thunk)))))
(define watchdog
(thread (lambda ()
(sleep seconds)
(and (thread-running? execthread)
(begin (kill-thread execthread)
(thread-send mainthread default))))))
(thread-receive))))