有没有办法从另一个线程中止延续?如:
#lang racket
(define thd
(thread (λ ()
(call-with-continuation-prompt
(λ ()
(sleep 10)
(printf "Don't print me.\n"))
(default-continuation-prompt-tag))
(printf "Do print me.\n"))))
(magically-abort-another-threads-continuation thd)
我希望不必使用线程控制。 作为一个更具描述性的例子,我想要实现像这样的do-only-while-polite:
#lang racket
(define i-am-polite #t)
(define-syntax-rule (do-only-while-polite body ...)
(call-with-continuation-prompt
(λ ()
(define thd (current-thread))
(define politeness-checker-thd
(thread (λ ()
(let loop ()
(cond
[(not i-am-polite)
(magically-abort-another-threads-continuation thd)]
[else (sleep 0.1)
(loop)])))))
body ...
(thread-kill politeness-checker-thd))
(default-continuation-prompt-tag)))
(thread (λ ()
(do-only-while-polite
(printf "Hello.\n")
(sleep 1)
(printf "How are you doing?")
(sleep 1)
(printf "It's nice to meet you."))
(printf "Bye.")))
(sleep 1)
(set! i-am-polite #f)
答案 0 :(得分:1)
您可能正在寻找kill-thread
。
#lang racket
(define thd
(thread (λ ()
(printf "Do print me.\n")
(call-with-continuation-prompt
(λ ()
(sleep 10)
(printf "Don't print me.\n"))
(default-continuation-prompt-tag)))))
(kill-thread thd)
请注意,无法保证在线程被杀死之前及时调用此示例中的"Do print me.\n"
。需要在线程之间执行Synchronization来强制执行此操作。
答案 1 :(得分:0)
以下是使用break-thread
实现的问题中给出的示例。
#lang racket
(define i-am-polite #t)
(define-syntax-rule (do-only-while-polite body ...)
(with-handlers ([exn:break? void])
(define thd (current-thread))
(define politeness-checker-thd
(thread (λ ()
(let loop ()
(cond
[(not i-am-polite)
(break-thread thd)]
[else (sleep 0.1)
(loop)])))))
body ...
(kill-thread politeness-checker-thd)))
(thread (λ ()
(do-only-while-polite
(printf "Hello.\n")
(sleep 1)
(printf "How are you doing?\n")
(sleep 1)
(printf "It's nice to meet you.\n"))
(printf "Bye.\n")))
(sleep 1)
(set! i-am-polite #f)