I'd like to run an expression in racket speculatively, hoping for (but not particularly expecting) a result. My code has a hard time limit. Is there an easy way to run some racket code for a few seconds, then reliably kill it and execute fallback code before the deadline hits?
Yes, an easy way to do this is using the engine library. For example:
#lang racket
(require racket/engine)
(define e (engine
(λ (_)
;; just keep printing every second
(let loop ()
(displayln "hi")
(sleep 1)
(loop)))))
;; run only for 2 seconds
(engine-run 2000 e)
Instead of specifying a time, you can also specify an event object so that the thread stops running when the event triggers.
You can create a "worker" thread to do the work, and another "watcher" thread to kill the worker.
This is described in the More: Systems Programming section of the docs.
The simplest, first cut may be sufficient for your calculation:
(define (accept-and-handle listener)
(define-values (in out) (tcp-accept listener))
(define t (thread
(lambda ()
(handle in out)
(close-input-port in)
(close-output-port out))))
; Watcher thread:
(thread (lambda ()
(sleep 10)
(kill-thread t))))
However if you're dealing with other resources read on to learn about custodians.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With