MVar

A box that holds one value

An MVar a is a box that is either empty or holds one value. putMVar fills it and blocks while it is full; takeMVar empties it and blocks while it is empty. The pair is the whole synchronisation primitive of the language, and the rest of the module is built on it:

newEmptyMVar :: IO (MVar a) newMVar :: a -> IO (MVar a) takeMVar :: MVar a -> IO a putMVar :: MVar a -> a -> IO ()

A blocked thread costs the runtime a queue entry and no operating-system thread, so a program can have thousands of them waiting. The type says nothing about who fills the box or when, which is the part the program has to get right.

A handoff between threads

The program forks a worker for each number and takes the value back before forking the next, so the boxes are a handoff and the order is fixed by the takes. The counter at the end is a second use of an MVar: a value changed by modifyMVar_, which is take, change and put in one call.

module Main (main) where import Control.Concurrent (forkIO, newEmptyMVar, putMVar, takeMVar) import Control.Concurrent.MVar (modifyMVar_, newMVar, readMVar) import Control.Monad (forM_) main :: IO () main = do box <- newEmptyMVar forM_ [1, 2, 3 :: Int] $ \n -> do _ <- forkIO (putMVar box n) takeMVar box >>= print counter <- newMVar (0 :: Int) forM_ [1 .. 5 :: Int] $ \_ -> modifyMVar_ counter (pure . (+ 1)) readMVar counter >>= print

ghc -Wall -O1 -threaded -o handoff handoff.hs
./handoff

1
2
3
5

Each worker puts its number and the main thread takes it before the next fork, so the printed order is the order of the list. The counter is 5 because five increments ran, and readMVar takes and puts the value back, which is why it does not empty the box.

modifyMVar_ as a lock

modifyMVar_ takes the value, applies the function and puts the result back, all as one operation that holds the box. Two threads that increment the same counter through it cannot lose an update, because the second one blocks until the first has put the value back. That is a mutex, and it is the reason a shared counter is written with an MVar and not with an IORef.

The deadlock behind it

Two MVars and two threads that take them in opposite orders deadlock: each holds one and waits for the other. The runtime detects the situation when no thread can run and prints a message, but the program has already hung. The rules that avoid it are the usual ones of a lock, and the STM of the next but one lesson removes the problem by making the two reads one transaction.

The next lesson uses a channel, which is a queue of values with the same take and put but room for more than one, so a producer does not have to wait for a consumer between values.

Exercises

  1. Fill an MVar twice without a take in between and describe the block.
  2. Write a counter incremented by four threads and read it at the end.
  3. Replace modifyMVar_ with a manual take and put and explain the update that can be lost.
  4. Write the two-MVar deadlock and run it with a timeout.
  5. Explain what readMVar does that takeMVar does not.
  6. Use an MVar as a one-shot signal between two workers.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is an MVar a?

    Answer

    A box that is empty or holds one value

    One value, and take and put block while it is empty or full.

  2. What does takeMVar do when the box is empty?

    Answer

    Blocks until a value is put

    The blocking is the synchronisation: the thread waits in the runtime queue.

  3. What does modifyMVar_ do?

    Answer

    Takes the value, applies the function and puts it back atomically with respect to other users

    It is the safe read-modify-write, which is why a shared counter uses it.

  4. What does this program print? module Main (main) where import Control.Concurrent.MVar (newMVar, readMVar) import Control.Monad (forM_) import Control.Concurrent.MVar (modifyMVar_) main :: IO () main = do counter <- newMVar (10 :: Int) forM_ [1 .. 3 :: Int] $ \_ -> modifyMVar_ counter (pure . (+ 1)) readMVar counter >>= print

    Answer

    13

    Three increments on top of ten give thirteen.

  5. Why can two threads lose an update with a manual take and put?

    Answer

    Both can take the old value before either puts the new one back

    The take and the put are separate, so the critical section is not held.

  6. What does this program print? module Main (main) where import Control.Concurrent.MVar (newMVar, takeMVar) main :: IO () main = do box <- newMVar (7 :: Int) takeMVar box >>= print takeMVar box >>= print

    Answer

    7

    The first take empties the box and prints 7; the second then waits for a value nobody puts.

  7. What is a deadlock with two MVars?

    Answer

    Two threads each hold one box and wait for the other

    The opposite order of taking is the classic cause.

  8. What does this program print? module Main (main) where import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) main :: IO () main = do box <- newEmptyMVar putMVar box (2 :: Int) takeMVar box >>= print

    Answer

    2

    The value is put and taken back, and print shows it.

  9. What does a blocked thread cost?

    Answer

    A queue entry in the runtime, not an operating-system thread

    Green threads are cheap, which is why thousands of blocked ones are fine.

  10. What does readMVar do?

    Answer

    Takes the value and puts it straight back

    The put makes the value available again, so the box is not left empty.

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image