Skip to content

Instantly share code, notes, and snippets.

@nikhilm
Created September 1, 2026 05:16
Show Gist options
  • Select an option

  • Save nikhilm/126757fd5b37f6b02451c96c26dcf4c1 to your computer and use it in GitHub Desktop.

Select an option

Save nikhilm/126757fd5b37f6b02451c96c26dcf4c1 to your computer and use it in GitHub Desktop.
blocked racket thread GCed
#lang racket/base
(define (timeout-evt msec)
; alarm-evt is roughly equivalent to WithDeadline. Translate a relative timeout to a deadline.
(alarm-evt (+ (current-inexact-monotonic-milliseconds) msec) #t))
(struct print-service (print-ch))
(define (make-print-service)
(define (server-loop print-ch)
(let loop ()
(define req (channel-get print-ch))
(printf "Got print request: ~a~n" req)
(sleep 3)
(loop)))
(define print-ch (make-channel))
(define th (thread (λ () (server-loop print-ch))))
(define wk (make-weak-box th))
(thread (λ ()
(let loop ()
(if (weak-box-value wk)
(begin
(printf "service thread still not GCed~n")
(sleep 0.5)
(loop))
(printf "Seems like service thread GCed!!~n")))))
(print-service print-ch))
(define (print-evt service msg)
(channel-put-evt (print-service-print-ch service) msg))
; If we wanted to offer a blocking interface, we can trivially abstract the sync call below.
; However, that would defeat the point of composable events.
(define (print-now service msg)
(sync (print-evt service msg)))
(module+ main
(define service (make-print-service))
(for ([i (in-range 2)])
(sync (print-evt service "Hello World")
(handle-evt
(timeout-evt 2000)
(λ (_) (printf "Printer seems to be down on attempt ~v!~n" i)))))
(set! service #f)
(for ([i (in-range 3)])
(collect-garbage)
(sleep 3))
(printf "Main exiting~n"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment