multithreading - 使用 Clojure 线程化长时间运行的进程并比较它们的返回

标签 multithreading clojure

我对需要处理的两个非常大的数据集有两个不同的函数,最终归结为两个 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/

相关文章:

Android 线程和 Throwable

c++ - 通过引用 "std::lock_guard<mutex>"返回共享对象是否安全?

unit-testing - 如何测试 midje 抛出的异常

clojure 将协议(protocol)定义保存在与实现不同的命名空间中

loops - 在我的 Clojure 循环中什么也没有发生

c++ - 在 WTL 和 C++ 中从工作线程更新 CListViewCtrl

java - websphere中的多线程

java - 为什么此 Servlet 在其 "Thread Per Connection"策略中使用多个线程?

validation - clojure 的 Schema 中至少存在一个可选键

maven - Clojure 与同一库的不同主要版本的相互依赖性问题