Haskell Concurrency
GHC's runtime has excellent support for concurrency. Its threads are lightweight: they are scheduled by the runtime rather than the operating system, so a program can run hundreds of thousands of them. Immutable data means threads can share values freely, and the few mutable variables they need come with safe primitives: MVar, Chan and Software Transactional Memory (STM).
Note: Thread scheduling is not deterministic, so the examples here are written to print in a fixed order: each thread's result is collected and printed by the main thread, rather than threads printing whenever they finish.
forkIO and MVar
forkIO :: IO () -> IO ThreadId starts an action in a new thread and returns immediately. An MVar a is a box that is either empty or holds one value. takeMVar waits until the box is full and empties it; putMVar waits until it is empty and fills it. That makes it a simple way to wait for a result:
import Control.Concurrent
slowSquare :: Int -> Int
slowSquare n = sum (replicate n n) -- n * n, the slow way
main :: IO ()
main = do
box <- newEmptyMVar
_ <- forkIO $ do
let r = slowSquare 3000
r `seq` putMVar box r -- compute in the worker thread, then deliver
putStrLn "main thread keeps going..."
result <- takeMVar box -- blocks until the worker has finished
print resultmain thread keeps going...
9000000
Without the seq, the worker would put an unevaluated thunk into the box, and the main thread would end up doing the work when it prints. With laziness, "where is this computed?" is a real question.
Many workers, results in order
A common pattern: start one thread per task, give each its own MVar, then collect the results in a fixed order:
import Control.Concurrent
import Control.Monad (forM, forM_)
isPrime :: Int -> Bool
isPrime n = n > 1 && all (\d -> n `mod` d /= 0) (takeWhile (\d -> d * d <= n) [2 ..])
countPrimes :: (Int, Int) -> Int
countPrimes (lo, hi) = length (filter isPrime [lo .. hi])
main :: IO ()
main = do
let ranges = [(1, 25000), (25001, 50000), (50001, 75000), (75001, 100000)]
boxes <- forM ranges $ \range -> do
box <- newEmptyMVar
_ <- forkIO (putMVar box $! countPrimes range)
return (range, box)
totals <- forM boxes $ \(range, box) -> do
n <- takeMVar box
putStrLn (show range ++ ": " ++ show n ++ " primes")
return n
putStrLn ("total: " ++ show (sum totals))(1,25000): 2762 primes
(25001,50000): 2371 primes
(50001,75000): 2260 primes
(75001,100000): 2199 primes
total: 9592
putMVar box $! x evaluates x before storing it. Compiled with -threaded and run with +RTS -N, the four threads run on four CPU cores in parallel.
MVar as a lock: shared counters
An MVar holding a value also works as a lock-protected variable. modifyMVar_ takes the value, applies a function, and puts the result back, so concurrent updates never get lost:
import Control.Concurrent
import Control.Monad (forM_, replicateM_)
main :: IO ()
main = do
counter <- newMVar (0 :: Int)
done <- newEmptyMVar
let workers = 10
forM_ [1 .. workers] $ \_ -> forkIO $ do
replicateM_ 1000 (modifyMVar_ counter (return . (+ 1)))
putMVar done ()
replicateM_ workers (takeMVar done) -- wait for all workers
final <- readMVar counter
print final10000
Each of the 10 threads adds 1000, and the final value is always exactly 10000.
Channels
A Chan is an unbounded FIFO queue between threads: producers writeChan, consumers readChan (blocking when it is empty):
import Control.Concurrent
import Control.Concurrent.Chan
import Control.Monad (forM_, replicateM)
main :: IO ()
main = do
jobs <- newChan
results <- newChan
-- one worker thread processes jobs in the order they arrive
_ <- forkIO $ forM_ [1 .. 5 :: Int] $ \_ -> do
job <- readChan jobs
writeChan results (job, length job)
forM_ ["parse", "typecheck", "optimise", "codegen", "link"] (writeChan jobs)
out <- replicateM 5 (readChan results)
mapM_ print out("parse",5)
("typecheck",9)
("optimise",8)
("codegen",7)
("link",4)
With a single worker, the order of results matches the order of jobs.
Software Transactional Memory
Locks are hard to compose: two correct locked operations combined can deadlock. STM (the stm package, bundled with GHC) replaces locks with transactions. Code in the STM monad reads and writes TVars; atomically runs it as one indivisible step, retrying automatically if another thread interfered:
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad (forM_, replicateM_, when)
transfer :: TVar Int -> TVar Int -> Int -> STM Bool
transfer from to amount = do
balance <- readTVar from
if balance < amount
then return False
else do
modifyTVar' from (subtract amount)
modifyTVar' to (+ amount)
return True
main :: IO ()
main = do
alice <- newTVarIO 500
bob <- newTVarIO 500
done <- newEmptyMVar
-- 100 transfers of 3 in each direction, from two threads at once
forM_ [(alice, bob), (bob, alice)] $ \(a, b) -> forkIO $ do
replicateM_ 100 (atomically (transfer a b 3))
putMVar done ()
replicateM_ 2 (takeMVar done)
total <- atomically ((+) <gt; readTVar alice <*> readTVar bob)
print total -- money is never created or lost
ok <- atomically (transfer alice bob 10000)
print ok
balances <- mapM readTVarIO [alice, bob]
print balances1000
False
[500,500]
The final balances are deterministic here (each direction moves the same total), but even under arbitrary interleavings the invariant "total = 1000" can never be observed broken, because each transfer is atomic. STM also offers retry to wait until a condition becomes true, and orElse to try alternatives.
| Tool | Use it for |
|---|---|
forkIO |
start a lightweight thread |
MVar |
hand over one result, or a simple lock-protected variable |
Chan |
a queue between producers and consumers |
TVar + atomically |
shared state that several values must change together |
async package (Hackage) |
high-level async/wait, concurrently, mapConcurrently |
Tip: In real projects, the
asyncpackage is the usual starting point:mapConcurrently countPrimes rangesreplaces the whole MVar bookkeeping above and propagates exceptions properly.
Test yourself
What does takeMVar do when the MVar is empty?
- Returns
Nothing - Blocks until another thread puts a value
- Throws an exception immediately
- Returns a default value
Why use putMVar box $! result instead of putMVar box result?
- It is faster to type
- To evaluate the result in the worker thread instead of passing a thunk
$!makes the MVar strict forever- There is no difference
What does atomically guarantee for an STM transaction?
- It runs on one core
- Its reads and writes take effect as one indivisible step
- It never blocks
- It runs before all other threads