Re: [Haskell-cafe] Don't “accidentallyparallelize”
Sjoerd Visscher
sjoerd at w3future.com
Sat Sep 5 09:07:02 EDT 2009
This could be a way to parallelize code (which would prevent such
mistakes):
newtype Par a = Par { doPar :: a }
instance Functor Par where
fmap = liftA
instance Applicative Par where
pure = Par
Par f <*> Par x = Par $ f `par` x `pseq` f x
then instead of:
fun `par` arg1 `par` arg2 `pseq` fun arg1 arg2
you can write:
doPar $ fun <$> pure arg1 <*> pure arg2
Sjoerd
On Sep 5, 2009, at 2:39 PM, Brent Yorgey wrote:
> On Sat, Sep 05, 2009 at 11:18:24AM +0000, Gracjan Polak wrote:
>>
>> Hi all,
>>
>> In "DEFUN 2009: Multicore Programming in Haskell Now!"
>> (http://donsbot.wordpress.com/2009/09/05/defun-2009-multicore-programming-in-haskell-now/
>> ),
>> slide 30 I see:
>>
>> Don't “accidentally parallelize”:
>> – f `par` f + e
>
> This creates a spark (potential speculative execution) to evaluate
> 'f', but whether this actually gets instantiated in another thread
> depends on the order in which the main thread evaluates (f + e): if we
> get lucky and it decides to work on evaluating 'e' first, then another
> thread may get a chance to evaluate 'f' in parallel. But if the main
> thread decides to work on 'f' first then the spark to evaluate 'f'
> will never get run and we end up with a sequential computation.
>
>>
>> and that the correct way of achieving parallelism is:
>> – f `par` e `pseq` f + e
>
> This means: create a spark to evaluate 'f', then evaluate 'e', and
> then finally evaluate f + e. This ensures that the main thread will
> work on 'e' first so that the spark for 'f' has a chance to run in
> parallel.
>
>>
>> As a bonus question: what is the difference between `seq` and `pseq`?
>
> x `pseq` y guarantees to evaluate x before y. There is no such
> guarantee with x `seq` y; the only guarantee with `seq` is that x
> `seq` y will be _|_ if x is.
>
> -Brent
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
--
Sjoerd Visscher
sjoerd at w3future.com
More information about the Haskell-Cafe
mailing list