1

有没有办法从另一个线程中止延续?如:

#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)
4

2 回答 2

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"在此示例中会在线程被杀死之前及时调用。 需要在线程之间进行同步以强制执行此操作。

于 2012-11-06T07:07:41.443 回答
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)
于 2012-11-07T23:54:54.897 回答