2012-11-06 11 views
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) 

我希望不必使用線程控制。 作爲一個更具描述性的例子,說我想要做的實現只-而禮貌是這樣的:

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

回答

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需要完成以執行此操作。

+0

我給出的例子很粗糙。我所希望的是一種從另一個動態地控制線程流的方法,而不必產生額外的線程並使用kill-thread等。但也許使用線程是方式。 – vagn

+0

線程可以通過通道相互通信,因此可以通過其他方式間接管理控制流。 – dyoo

+0

我期望['break-thread'](http://docs.racket-lang.org/reference/threads.html#%28def._%28%28quote._~23~25kernel%29._break-線程%29%29)是一個更好的匹配,但是是的,一些適當的溝通比這更好,而且有些嘗試使用延續。 –

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) 
相關問題