基于core.async 遍历示例,我在下面创建了类似的代码,以使用多个通道处理一些 CPU 密集型作业,超时时间为 10 秒。但是在主线程返回后,CPU 使用率保持在 700% 左右(8 个 CPU 机器)。我必须在 emacs 中手动运行 nrepl-close 才能关闭 Java 进程。
是否有任何适当的方法可以杀死 (go..) 块产生的宏线程?我试过接近!每个chan,但它不起作用。我想确保主线程返回后Java进程的CPU使用率回到0。
(defn [] RETURNED-STR-FROM-SOME-CPU-INTENSE-JOB (do... (str ...)))
(let [n 1000
cs (repeatedly n chan)]
(doseq [c cs]
(go
(>! c (RETURNED-STR-FROM-SOME-CPU-INTENSE-JOB ))))
(dotimes [i n]
(let [[result source] (alts!! (conj cs (timeout 10000))) ] ;;wait for 10 seconds for each job
(if (list-contains? cs source) ;;if returned chan belongs to cs
(prn "OK JOB FINISHED " result)
(prn "JOB TIMEOUT")
)))
(doseq [i cs]
(close! i)) ;;not useful for "killing" macro thread
(prn "JOBS ARE DONE"))
;;Btw list-contains? function is used to judge whether an element is in a list
;;http://stackoverflow.com/questions/3249334/test-whether-a-list-contains-a-specific-value-in-clojure
(defn list-contains? [coll value]
(let [s (seq coll)]
(if s
(if (= (first s) value) true (recur (rest s) value))
false)))