Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 57 ยท Advanced types

Concurrency and Software Transactional Memory

Learn Haskell concurrency: lightweight threads with forkIO, MVar as a lock and channel, STM and TVar for safe shared state, async, and parallelism with par.

Haskell was designed with concurrency in mind. Its runtime schedules millions of very cheap green threads on a small pool of operating-system threads, and its type system helps you keep shared state under control. This lesson covers the tools you will meet most often: forkIO, MVar, software transactional memory (STM), the async library, and parallelism.

You should know IO basics and mutable state first. Real Haskell is not installed on this site, so every example here is read-only. Concurrent output is nondeterministic by nature, so where output order matters the comments say what is guaranteed.

Concurrency versus parallelism

These two words get mixed up:

  • Concurrency means structuring a program as several independent activities that may overlap in time, such as a server handling many clients. It is about design.
  • Parallelism means using several CPU cores to finish a computation sooner. It is about speed.

Haskell supports both. Concurrency uses IO and threads. Parallelism over pure code can use sparks and strategies without changing what the program means.

Concurrency toolbox

forkIO Start a lightweight thread.
MVar A box that is full or empty.
STM Atomic transactions on shared state.
async Wait for results safely.
1 / 2

Threads with forkIO

forkIO starts a new thread running an IO action and returns immediately with a ThreadId:

HASKELL
import Control.Concurrent

main :: IO ()
main = do
  _ <- forkIO (putStrLn "hello from a thread")
  putStrLn "hello from main"
  threadDelay 100000   -- microseconds: give the child time to finish

Two rules are important. First, when main returns, the program ends and all other threads are killed, which is why the example waits. Second, the order of the two lines is not guaranteed.

Sleeping is a poor way to wait. Use a synchronisation variable instead.

MVar: a box you can wait on

An MVar a is either empty or holds one value. takeMVar blocks while it is empty; putMVar blocks while it is full. That makes it both a lock and a one-slot channel.

HASKELL
import Control.Concurrent

main :: IO ()
main = do
  done <- newEmptyMVar
  _ <- forkIO $ do
    putStrLn "working..."
    putMVar done ()           -- signal completion
  takeMVar done               -- wait here until the signal arrives
  putStrLn "finished"

As a lock, an MVar that always holds a value protects a shared resource:

HASKELL
counter <- newMVar (0 :: Int)
modifyMVar_ counter (pure . (+ 1))   -- takes, updates, puts back

modifyMVar_ is safe even if an exception is thrown inside the update: it restores the value. Plain takeMVar followed by putMVar is not.

MVars have a weakness. Once you need two of them at once, for example moving money between two accounts, you must lock them in a consistent order, or two threads can wait on each other forever. That is a deadlock, and it is easy to write by accident.

STM: transactions instead of locks

Software transactional memory solves the multi-variable problem. You read and write TVars inside the STM monad, then run the whole block with atomically. The runtime makes the block behave as if it ran alone, all or nothing. If another thread changed something you read, the transaction silently retries.

HASKELL
import Control.Concurrent.STM

transfer :: TVar Int -> TVar Int -> Int -> STM ()
transfer from to amount = do
  balance <- readTVar from
  check (balance >= amount)          -- retry until enough money
  modifyTVar' from (subtract amount)
  modifyTVar' to   (+ amount)

main :: IO ()
main = do
  a <- newTVarIO 100
  b <- newTVarIO 0
  atomically (transfer a b 30)
  (,) <$> readTVarIO a <*> readTVarIO b >>= print   -- (70,30)

Key points:

  • STM actions cannot perform arbitrary IO. The type system forbids it, because a transaction may run more than once and a launched missile cannot be undone.
  • check and retry make the thread block until the data changes, then re-run the transaction. No polling, no condition variables.
  • orElse combines alternatives: try the first transaction, and if it retries, try the second.
  • Transactions compose. You can build transfer from smaller STM pieces and nothing is exposed halfway.

Keep transactions short. A long transaction touching hot variables retries often and wastes work. Do slow computation outside atomically and only commit the result inside it.

Besides TVar, the stm package offers TMVar, TChan, TQueue and TBQueue (a bounded queue) for passing messages between threads.

HASKELL
queue <- newTQueueIO
_ <- forkIO $ mapM_ (atomically . writeTQueue queue) [1 .. 5 :: Int]
xs <- replicateM 5 (atomically (readTQueue queue))
print xs   -- [1,2,3,4,5]

The async library

Raw forkIO leaves exceptions and results to you. The async package wraps threads in a handle you can wait on:

HASKELL
import Control.Concurrent.Async

main :: IO ()
main = do
  a1 <- async (fetchSize "https://example.org/a")
  a2 <- async (fetchSize "https://example.org/b")
  s1 <- wait a1            -- rethrows if the thread failed
  s2 <- wait a2
  print (s1 + s2)

  -- or in one step, running both concurrently:
  (x, y) <- concurrently (fetchSize "u1") (fetchSize "u2")
  print (x + y)

mapConcurrently runs an action over a list in parallel, and race returns whichever of two actions finishes first and cancels the other. withAsync guarantees the child is cancelled if the parent exits, so you do not leak threads.

Parallelism with par

For pure computation, the parallel package lets you mark work that may run on another core:

HASKELL
import Control.Parallel
import Control.Parallel.Strategies

fib :: Int -> Integer
fib n = if n < 2 then toInteger n else fib (n - 1) + fib (n - 2)

main :: IO ()
main = do
  let results = map fib [25 .. 30] `using` parList rseq
  print (sum results)

par a b sparks the evaluation of a and returns b; strategies such as parList package this pattern so you rarely write par directly. Because the code is pure, the result is identical to the sequential version, only faster. Two details matter in practice:

  • Compile with -threaded and run with +RTS -N to use all cores. Without them everything runs on one.
  • Laziness can defeat you. If you spark an unevaluated thunk that is cheap to build, nothing useful runs in parallel. Use rdeepseq or strictness to force real work.

Common pitfalls

  1. Forgetting to wait. Main exits and kills the workers.
  2. Unsynchronised IORef updates. modifyIORef is not atomic; use atomicModifyIORef' or an MVar/TVar.
  3. Deadlock with several MVars. Prefer STM, or lock in a fixed order.
  4. Lazy results hiding work. A value written into an MVar may still be a thunk; force it before sharing if you want the work done in the worker thread.
  5. Unbounded queues. A fast producer and slow consumer exhaust memory; use TBQueue.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to other threads when main returns?

    The program lives as long as the main thread. You must wait for workers, for example with an MVar or the async library.
  2. 2. Why can you not call putStrLn inside an STM transaction?

    STM actions can be retried, so irreversible side effects are excluded at the type level.
  3. 3. What does check (balance >= amount) do when the condition is false?

    check calls retry on a false condition: the thread sleeps until one of the TVars it read changes, then the transaction runs again.
  4. 4. Which is a good fit for parallel speed-up of pure code?

    Strategies such as parList spark pure evaluations that the runtime may spread across cores, without changing the result.

Summary

  • Haskell threads are cheap; forkIO starts one, and the program ends when main ends.
  • MVar is a blocking box usable as a lock or a one-slot channel; modifyMVar_ is exception-safe.
  • STM with TVar and atomically gives composable, deadlock-free updates to several variables; retry and check block until data changes.
  • async provides handles, concurrently, race and safe cancellation.
  • par and strategies add parallel speed to pure code; compile with -threaded and run with -N.
  • Keep transactions short and force lazy values when you want work done in a given thread.

Next: Parsing with Parser Combinators.