为什么在Haskell中我们需要带“ par”的“ seq”或“ pseq”?
收藏

我试图理解为什么我们需要标准示例代码的所有部分:

a `par` b `pseq` a+b

为什么以下条件不够?

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?

以下更简洁的版本怎么样?

a `par` a+b

Why would we need to make sure b is evaluated before a+b as in the original, standard code?

最佳答案

好。我认为以下论文回答了我的问题:http://community.haskell.org/~simonmar/papers/threadscope.pdf

总而言之,问题在于

a `par` b `par` a+b 

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.

原始版本

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.

    公众号
    关注公众号订阅更多技术干货!