Accessing tuple elements in parallel
In this recipe, we will cover how to access elements of a tuple in parallel.
How to do it…
- Import the built-in package as follows:
import Control.Parallel.Strategies
- Evaluate the expression in a tuple in parallel. We perform this task twice with different strategies to demonstrate how strategies are easily swapped to change the parallel nature of the code as follows:
main = do let (a, b) = withStrategy (parTuple2 rseq rseq) (task1, task2) print $ seq (a+b) "done 1" let (a, bs) = withStrategy (parTuple2 rseq rdeepseq) (task1, tasks) print $ seq (a + sum bs) "done 2"
- Define time-consuming tasks as follows:
task1 = 8^8^8 :: Integer task2 = 8^8^8 :: Integer tasks = [10^10..10^10+10000] :: [Integer]
- Compile the code with the
threaded
andrtsopts
flags enabled, as follows:$ ghc -O2 --make Main.hs -threaded -rtsopts
- Run it by specifying the number of cores as follows:
$ ./Main +RTS -N2
There's more…
When dealing with tuples...