Multicore Programming in Haskell
Multicore Programming in Haskell
Haskell
Simon Marlow
Microsoft Research
A concurrent web server
• non-determinism
– threads interact in different ways depending on the
scheduler
– programmer has to deal with this somehow: locks,
messages, transactions
– hard to think about
– impossible to test exhaustively
• can we get parallelism without non-
determinism?
What Haskell has to offer
par a b == b
• Replacing “par a b” with “b” does not change
the meaning of the program
– only its speed and memory usage
– par cannot make the program go wrong
– no race conditions or deadlocks, guaranteed!
• par looks like a function, but behaves like an
annotation
How to use par
Place n queens on an n x n
board such that no queen
attacks any other, horizontally,
vertically, or diagonally
N queens
[1,3,1] [1,1]
[2,3,1]
[2,1] [1]
[3,3,1]
[4,3,1] [3,1] []
[5,3,1] [4,1]
[2]
[6,3,1]
...
...
...
N-queens in Haskell
nqueens :: Int -> [[Int]] A board is represented as a
nqueens n = subtree n [] list of queen rows
where
children :: [Int] -> [[Int]]
children b = [ (q:b) | q <- [1..n], children calculates the
safe q b ] valid boards that can
be made by adding
subtree :: Int -> [Int] -> [[Int]] another queen
subtree 0 b = [b]
subtree c b =
subtree calculates all
concat $
the valid boards
map (subtree (c-1)) $
starting from the given
children b
board by adding c
more columns
safe :: Int -> [Int] -> Bool
...
Parallel N-queens
...
Parallel N-queens
• We can do better...
How many sparks?
newList :: IO (List a)
Creates a new (empty) list
1 2 3 4
1 2d
2 3d
3 4
• Full STM
• Various “lazy delete” implementations:
– STM
– MVar, hand-over-hand locking
– CAS
– CAS (using STM)
– MVar (using STM)
Results
1000
100
CAS
CASusingSTM
Time(s) 10
LAZY
MLC
MLCusingSTM
1 STM
0.1
1 2 3 4 5 6 7 8
Processors
Results (scaling)
6
4
CAS
CASusingSTM
Speedup 3
LAZY
MLC
2
MLCusingSTM
STM
1
0
1 2 3 4 5 6 7 8
Procoessors
So what?
100
CAS
CASusingSTM
Time(s) 10 LAZY
MLC
MLCusingSTM
1 STM
???
0.1
1 2 3 4 5 6 7 8
Processors
And the winner is...
TVar (STM)
Built-in lock-free updates
(:) (:)
1 2
Lazy immutable = parallel
• Haskell: http://www.haskell.org/
• GHC: http://www.haskell.org/ghc
• Libraries: http://hackage.haskell.org/
• News: http://www.reddit.com/r/haskell