Created
September 1, 2026 05:16
-
-
Save nikhilm/126757fd5b37f6b02451c96c26dcf4c1 to your computer and use it in GitHub Desktop.
blocked racket thread GCed
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
| #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