第 2 部分 · 高级特性
并发与线程
并发与线程
探索 Racket 的线程、通道和并发编程模型。
线程基础
#lang racket ;; 创建线程 (thread (lambda () (sleep 2) (displayln "Hello from thread!"))) (displayln "Main thread continues...")
线程通信——通道
;; 创建通道 (define ch (make-channel)) ;; 发送线程 (thread (lambda () (channel-put ch "message from worker"))) ;; 接收 (channel-get ch) ; => "message from worker"
线程邮箱
每个线程都有一个邮箱用于接收消息:
(define worker (thread (lambda () (let loop () (match (thread-receive) ['stop (void)] [msg (displayln (format "Got: ~a" msg)) (loop)]))))) (thread-send worker "hello") (thread-send worker "world") (thread-send worker 'stop)
同步事件
;; sync 等待多个事件中的第一个 (sync (handle-evt (alarm-evt 5) (lambda (_) "timeout")) (handle-evt (thread-receive-evt) (lambda (msg) msg)))
并行计算
;; places:共享内存的并行 (place p (channel-put p (heavy-computation))) ;; futures:自动并行 (future (lambda () (compute-primes 1000)))
小结
Racket 提供了多种并发原语。线程和通道适合协作式并发,sync/evt 适合事件驱动,places 和 futures 适合 CPU 密集型并行。