为什么我们在Haskell中需要'seq'或'pseq'和'par'? [英] Why do we need 'seq' or 'pseq' with 'par' in Haskell?
问题描述
a`par` b`我想知道为什么我们需要标准示例代码的所有部分: pseq` a + b
为什么以下内容不够用?
a`par` b`par` a + b
上面的表达式看起来很具描述性:试着同时评估 a
和 b
并返回结果 a + b
。仅仅是效率的原因:第二个版本会两次而不是一次?
下面更简洁的版本如何?
a`par` a + b
为什么我们需要确保 b
在原始标准代码中的 a + b
之前被评估?
好的。我认为以下文章回答了我的问题: http://community.haskell.org/~ simonmar / papers / threadscope.pdf
总之,问题出在
a`par` b`par` a + b
和
a`par` a + b
缺乏评估排序。在这两个版本中,主线程都立即处理 a
(或者有时 b
),导致火花因为没有必要再开始一个线程来评估主线程已经开始评估什么了。
原始版本
a`par` b`pseq` a + b
确保主线程在 b
之前 a + b
(否则会开始评估 a
),从而给出了一个机会让spark a
实现成一个线程进行并行评估。
I'm trying to understand why we need all parts of the standard sample code:
a `par` b `pseq` a+b
Why won't the following be sufficient?
a `par` b `par` a+b
The above expression seems very descriptive: Try to evaluate both a
and b
in parallel, and return the result a+b
. Is the reason only that of efficiency: the second version would spark off twice instead of once?
How about the following, more succinct version?
a `par` a+b
Why would we need to make sure b
is evaluated before a+b
as in the original, standard code?
Ok. I think the following paper answers my question: http://community.haskell.org/~simonmar/papers/threadscope.pdf
In summary, the problem with
a `par` b `par` a+b
and
a `par` a+b
is the lack of ordering of evaluation. In both versions, the main thread gets to work on a
(or sometimes b
) immediately, causing the sparks to "fizzle" away immediately since there is no more need to start a thread to evaluate what the main thread has already started evaluating.
The original version
a `par` b `pseq` a+b
ensures the main thread works on b
before a+b
(or else would have started evaluating a
instead), thus giving a chance for the spark a
to materialize into a thread for parallel evaluation.
这篇关于为什么我们在Haskell中需要'seq'或'pseq'和'par'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!