STM

A transaction over TVars

Software transactional memory replaces the lock with a transaction. A TVar a is a shared variable that can only be read and written inside atomically, and the runtime retries a transaction that read a variable another transaction changed:

newTVarIO :: a -> IO (TVar a) readTVar :: TVar a -> STM a writeTVar :: TVar a -> a -> STM () atomically :: STM a -> IO a

STM is a monad, so a transaction is a do block of reads and writes, and the whole block either commits as one or runs again. modifyTVar' is the read, the change and the write in one call, with the prime forcing the new value as in the earlier lessons.

Four threads and a counter

module Main (main) where import Control.Concurrent (forkIO) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Concurrent.STM import Control.Monad (forM_, replicateM) main :: IO () main = do counter <- newTVarIO (0 :: Int) dones <- replicateM 4 $ do done <- newEmptyMVar _ <- forkIO $ do forM_ [1 .. 1000 :: Int] $ \_ -> atomically (modifyTVar' counter (+ 1)) putMVar done () pure done mapM_ takeMVar dones readTVarIO counter >>= print

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

4000

atomically and modifyTVar'

Each of the four threads runs a thousand transactions of one increment. The runtime can run them at the same time and can abort one that conflicts, but the final count is 4000 on every run: a transaction that commits saw a consistent counter, and no update is lost. There is no lock in the program and no MVar around the counter; the synchronisation is in the runtime.

Why the count is exact

The guarantee is that a transaction sees a consistent snapshot and that a commit is atomic. Two increments that conflict are serialised by the runtime: one commits, the other notices that a variable it read has changed and runs again. The retry is invisible to the program, except in the cost, and it is the reason the code has no lock to forget to release.

The costs are real and worth knowing:

Exercises

  1. Add a second counter and increment both in one transaction.
  2. Change the number of threads to eight and explain the result.
  3. Replace the counter with a TVar [Int] and append the values, then sort them.
  4. Try atomically (putStrLn "x") and read the error.
  5. Explain why readTVarIO is fine at the end and wrong during the run.
  6. Compare this program with the MVar counter of the previous lesson.

Questions

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

  1. What can a transaction do?

    Answer

    Read and write TVars, and commit or retry as one step

    A transaction is pure STM over TVars; IO stays outside atomically.

  2. What does atomically do?

    Answer

    Runs the transaction and makes it visible as one atomic step

    It is the boundary between STM and IO and the commit point.

  3. Why is the count 4000 and not less?

    Answer

    A conflicting transaction is retried, so no increment is lost

    The runtime serialises conflicting commits and retries the loser.

  4. What does this program print? module Main (main) where import Control.Concurrent.STM main :: IO () main = do box <- newTVarIO (10 :: Int) atomically (modifyTVar' box (+ 5)) readTVarIO box >>= print

    Answer

    15

    The transaction adds five and the read shows the new value.

  5. Which monad is a transaction in?

    Answer

    STM

    readTVar and writeTVar return STM actions, and atomically runs them.

  6. What does this program print? module Main (main) where import Control.Concurrent.STM main :: IO () main = do a <- newTVarIO (1 :: Int) b <- newTVarIO (2 :: Int) atomically $ do x <- readTVar a writeTVar b x readTVarIO b >>= print

    Answer

    1

    The transaction copies the value of a into b.

  7. Can an IO action run inside a transaction?

    Answer

    No, the transaction is pure STM

    IO cannot be rolled back, so it is not allowed in STM.

  8. What does this program print? module Main (main) where import Control.Concurrent.STM main :: IO () main = do box <- newTVarIO (7 :: Int) atomically $ do n <- readTVar box writeTVar box (n * 2) readTVarIO box >>= print

    Answer

    14

    The transaction doubles the value once.

  9. What is the cost of a large transaction?

    Answer

    More variables touched means more retries under contention

    Conflict detection works on the variables read, so a wide transaction conflicts more.

  10. What does readTVarIO do?

    Answer

    Reads a TVar outside a transaction

    It is the IO read for a value nobody is writing, such as the final count.

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