Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Racket run thread for fixed amount of time

Tags:

timeout

racket

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?

like image 763
So8res Avatar asked Jun 22 '13 16:06

So8res


2 Answers

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.

like image 65
Asumu Takikawa Avatar answered Nov 24 '22 00:11

Asumu Takikawa


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.

like image 43
Greg Hendershott Avatar answered Nov 24 '22 01:11

Greg Hendershott