Front logic function

How does the par function work? His signature:

 par :: a -> b -> b. 

But this is strange. Why is this not so:

par :: (a -> b) -> a -> b

(get the function, execute it in a new thread and return the result)?

Another question is regular haskell multithreading?

enter image description here

+6
source share
3 answers

par for speculative parallelism, and relies on laziness.

You assume that the unappraised a should be calculated while you are busy working on b .

Later in your program, you can call a again and it will be ready.

Here is an example. We want to add 3 numbers together. Each road number to calculate. We can compute them in parallel, and then add them together:

 main = a `par` b `par` c `pseq` print (a + b + c) where a = ack 3 10 b = fac 42 c = fib 34 fac 0 = 1 fac n = n * fac (n-1) ack 0 n = n+1 ack m 0 = ack (m-1) 1 ack mn = ack (m-1) (ack m (n-1)) fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) 
+9
source

Because we do not execute functions in Haskell. We evaluate the values, how we control the activity of the processor. What par xy does mainly: when evaluating the result of y runtime also pre-evaluates x , although it itself has not yet requested it.

Please note that this is not the most convenient way to write parallel code. Check out newer alternatives such as Eval monad . You can read the book by Simon Marlowe .

+4
source

In addition to the previous answers, it is worth noting that a and b will be evaluated only in the weak head normal form (WHNF) (i.e., using the outermost reduction or constructor), so it would be useful to force with deepseq .

In terms of the operational semantics of par , a spark is created that is a pointer to thunk (invaluable calculation) and added to the spark pool. It is very cheap, and it is possible to have millions of sparks. Creating a theme is advisory; the runtime system may decide not to turn a into a stream and prune superfluos parallelism, ignoring the spark or adding the parent spark in the parent.

The displayed image may indicate a problem with your code, where the thread running on CPU2 has significantly less load disbalance.

+1
source

Source: https://habr.com/ru/post/970084/


All Articles