我对需要处理的两个非常大的数据集有两个不同的函数,最终归结为两个 bool 值。然后需要将这些值组合在一起以获得最终结果。我的问题是创建线程的最佳方法是什么,以便两个长函数可以同时运行。我的想法是这样的,
(def f (future longProcessOne(data_one)))
(def g (future longProcessTwo(data_two)))
(and @f @g)
但我一直在寻找更好的方法来解决这个问题。
最佳答案
您的方法是相当正常的 Clojure 代码。另一种选择是使用 promise ,或者如果您需要更复杂的处理,您可以考虑使用类似 lamina 的东西。或者如果您想生活在最前沿you could try core.async :
(ns async-example.core
(:require [clojure.core.async :refer :all])
(defn example []
(let [a (chan) ; a channel for a to report it's answer
b (chan) ; a channel for b to report it's answer
output (chan)] ; a channel for the reporter to report back to the repl
(go (<! (timeout (rand-int 1000))) ; process a
(>! a (rand-nth [true false])))
(go (<! (timeout (rand-int 1000))) ; process b
(>! b (rand-nth [true false])))
(go (>! output (and (<! a) (<! b)))) ; the reporter process
output)) ;return the channe that the result will be sent to
async-example.core> (<!! (go (<! (example))))
false
async-example.core> (<!! (go (<! (example))))
false
async-example.core> (<!! (go (<! (example))))
true
当然,这对于您的情况来说有点过分了,尽管无论如何它都非常有趣;-)
关于multithreading - 使用 Clojure 线程化长时间运行的进程并比较它们的返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17621344/