Fairly new Haskell user here, I'm trying to find the sum of integers 1 to n using threads. I'm aware there are formulas to do this, but I want to play around with threads so I'm more comfortable with optimizing. I'm using GHC version 8.6.5 to compile with -O2 and, for the parallel one, -threaded.
Single-core code:
main = do
putStrLn "Running: "
let n = 10^9
let a = sum [1..n `rem` 4]
let b = sum [1 + n `rem` 4..n `rem` 2]
let c = sum [1 + n `rem` 2..3 * n `rem` 4]
let d = sum [1 + 3 * n `rem` 4..n]
let total = (d + c + b + a)
putStrLn $ "The sum is " ++ (show total)
Parallel code:
import Control.Parallel
main = do
putStrLn "Running: "
let n = 10^9
let a = sum [1..n `rem` 4]
let b = sum [1 + n `rem` 4..n `rem` 2]
let c = sum [1 + n `rem` 2..3 * n `rem` 4]
let d = sum [1 + 3 * n `rem` 4..n]
let total = a `par` b `par` c `pseq` (d + c + b + a)
putStrLn $ "The sum is " ++ (show total)
(Only changes are the import and let total = ...)
The single-core one takes 40.730s. Parallel one is run with -N4 and takes 38.549s. It doesn't seem that all 4 sums are running in parallel as intended, though the summary says 2 sparks were converted. What is really going on with the sums and how can I fix it?