haskell - 如何在 Haskell 中产生并发计算?

如果我有一个函数,它执行四次非常长的计算,并返回一个包含四次计算结果的列表,但每个计算不依赖于另一个计算,那么如何在 Haskell 中“并行化”它?

为了更好地解释我的问题,下面是我所想到的 Clojure 示例:

(defn some-function [arg1 arg2 arg3 arg4]
  let [c1 (very-long-computation arg1)
       c2 (very-long-computation arg2)
       c3 (very-long-computation arg3)
       c4 (very-long-computation arg4)]
    [c1 c2 c3 c4])

您可以生成三个额外的线程,例如:

(defn some-function [arg1 arg2 arg3 arg4]
  let [c1 (future (very-long-computation arg1))
       c2 (future (very-long-computation arg2))
       c3 (future (very-long-computation arg3))
       c4 (very-long-computation arg4)] ; no need to wrap c4 in a future
    [@c1 @c2 @c3 c4])

类似于 Haskell 中的内容是否等效?

someFunction :: (a -> a -> a ->a) -> [a]
  do c1 <- rpar (very-long-computation arg1)
     c2 <- rpar (very-long-computation arg2)
     c3 <- rpar (very-long-computation arg3)
     c4 <- (very-long-computation arg4)
     rseq c1
     rseq c2
     rseq c3
     return (c1, c2, c3, c4)

我需要 rpar/rseq c4 吗?

rpar/rseq 是进行此类并发计算的方法吗?

如果我不 rseq,稍后当我尝试访问返回列表中的返回值时,程序会等待吗?

这是透明的还是您需要执行类似 Clojure 中使用“@”时发生的“deref”之类的操作?

最佳答案

您很可能正在寻找 async包裹。例如,如果您想对这三个计算进行竞赛并选择第一个完成的计算:

someFunction :: IO a
someFunction = do
    c1 <- async $ veryLongComputation1
    c2 <- async $ veryLongComputation2
    c3 <- async $ veryLongComputation3
    (_, a) <- waitAny $ [c1, c2, c3]
    return a

或者您可以在特定的async线程上使用wait,并通过stm共享状态。对于此类事情来说,这是一个非常有用的包。您在 OP 中要求的精​​确版本如下所示:

someFunction :: IO (a, b, c, d)
someFunction = do
    c1 <- async $ veryLongComputation1
    c2 <- async $ veryLongComputation2
    c3 <- async $ veryLongComputation3
    v4 <- veryLongComputation4
    -- wait for all the results and return them as a tuple
    wait $ (,,,) <$> c1 <*> c2 <*> c3 <*> (return v4)

这当然假设c1、c2、c3都是副作用,并且您对结果不感兴趣。 waitpoll 为您获取值。

我还强烈推荐 Simon Marlow 所著的《Haskell 中的并行和并发编程》一书。

https://stackoverflow.com/questions/23353898/

相关文章:

r - 如何使用 ggplotly 绘制 3D 图形?

asp.net-mvc - EF 核心和 Azure

google-chrome-extension - 卸载 Chrome 扩展时打开新窗口

laravel-5 - "entrust"命名空间中没有定义命令

gcc - ARM ;内联汇编;使用暂存器;

xslt-2.0 - XSL :FO avoid Space between Table Cells

amazon-web-services - CloudFormation 模板中元数据部分的用途是什

grails - 如何在grails中自定义spring security插件登录页面

r - 添加一列,其中包含具有最大频率的对象的值

solr - Sitecore 和 SolrCloud 开启重建