<html>
<head>
<meta content="text/html; charset=windows-1252"
http-equiv="Content-Type">
</head>
<body bgcolor="#FFFFFF" text="#000000">
As far as I can tell there's nothing wrong with your code. My
hypothesis is that Haskell optimizes call to sumEuler 5000 by
calling it only once in one thread. Here's why I think so:<br>
<br>
The program I used for debugging this is:<br>
<blockquote>import Control.Concurrent.Async (async, wait)<br>
import System.IO.Unsafe (unsafePerformIO)<br>
<br>
sumEuler :: Int -> Int<br>
sumEuler = sum . map euler . mkList<br>
where<br>
mkList n = seq (unsafePerformIO (putStrLn
"Calculating")) [1..n-1]<br>
euler n = length (filter (relprime n) [1..n-1])<br>
where<br>
relprime x y = gcd x y == 1<br>
<br>
p :: Int -> IO Int<br>
p b = return $! sumEuler b<br>
<br>
p5000 :: IO Int<br>
p5000 = return $ sumEuler 5000<br>
<br>
main :: IO ()<br>
main = do<br>
a <- async $ p5000<br>
b <- async $ p5000<br>
av <- wait a<br>
bv <- wait b<br>
print (av,bv)<br>
</blockquote>
The two main modification are adding a debugging message
"Calculating" when a list [1..(n-1)] is evaluated. The second one is
making p into a function. Notice that it uses strict application ($!
- check how it works with simple $). I will use that function in
further examples.<br>
<br>
Running this program with "time ./Test 2 +RTS -ls -N2" gives me: <br>
<blockquote>Calculating<br>
(7598457,7598457)<br>
<br>
real 0m3.752s<br>
user 0m3.833s<br>
sys 0m0.211s<br>
<br>
</blockquote>
Just to be sure I have almost the same time when doing only one
computation with:<br>
<blockquote>main :: IO ()<br>
main = do<br>
a <- async $ p5000<br>
av <- wait a<br>
print av<br>
</blockquote>
So it seems like the value returned by p5000 is computed only once.
GHC might be noticing that p5000 will always return the same value
and might try cache it or memoize it. If this hypothesis is right
then calling sumEuler with two different values should run in two
different threads. And indeed it is so:<br>
<blockquote>main :: IO ()<br>
main = do<br>
a <- async $ p 5000<br>
b <- async $ p 4999<br>
av <- wait a<br>
bv <- wait b<br>
print (av,bv)<br>
</blockquote>
Gives:<br>
<blockquote>Calculating<br>
Calculating<br>
(7598457,7593459)<br>
<br>
real 0m3.758s<br>
user 0m7.414s<br>
sys 0m0.064s<br>
<br>
</blockquote>
So it runs in two threads just as expected. The strict application
($!) here is important. Otherwise it seems that the async thread
returns a thunk and the evaluation happens in print (av, bv) which
is evaluated in a single thread. Also the fact that p5000 is a top
level binding is important. When I do:<br>
<blockquote>main :: IO ()<br>
main = do<br>
a <- async $ p 5000<br>
b <- async $ p 5000<br>
av <- wait a<br>
bv <- wait b<br>
print (av,bv)<br>
</blockquote>
I get no optimization (GHC 7.6.3).<br>
<br>
Best,<br>
Greg<br>
</body>
</html>