你怎么杀死core.async / thread?

时间:2016-06-02 17:07:51

标签: multithreading clojure terminate core.async

我有一些core.async/thread返回的线程涉及某个进程,我即将关闭。我没有关闭我的整个程序,只是这些线程。我该如何终止线程?

不推荐使用Java .stop类的Thread方法,但我很乐意使用它,除了core.async/thread不返回Thread,而是{ {1}}:

ManyToManyChannel

我在user=> (clojure.core.async/thread) #object[clojure.core.async.impl.channels.ManyToManyChannel 0x780e97c0 "clojure.core.async.impl.channels.ManyToManyChannel@780e97c0"] user=> (type *1) clojure.core.async.impl.channels.ManyToManyChannel 上找不到任何文档。这听起来像一个线程类型的奇怪名称,所以这里可能有一些我不理解的基本内容。但这是我目前天真,无意义的问题:你如何杀死ManyToManyChannel

ManyToManyChannel似乎对clojure.repl/thread-stopper没有影响。

1 个答案:

答案 0 :(得分:3)

你让线程自然终止。如果需要外部终止,则必须实现它。

(defn terminatable [input-ch terminate-ch]
   (thread
     (loop []
       (let [[v ch] (alts!! [input-ch terminate-ch])]
         (if (identical? ch input-ch)
           (if (some? v)
             (do (process-input v) (recur))
             ;; else input-ch has closed -> don't call recur,
             ;; thread terminates
             )
           ;; else we received sth. from terminate-ch,
           ;; or terminate-ch has closed -> don't call recur,
           ;; thread terminates
           )))))

然后通过外部终止     (close! terminate-ch)

最后,您可以通过从thread返回的频道中确定线程何时终止。

予。即

(take! (terminatable (chan) (doto (chan) close!)) 
       (fn [_] (println "Thread is terminated")))