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.
- readTVarIO reads outside a transaction when the value is only being displayed; it is safe at the end, when no thread writes.
- The four MVars are not part of the counter: they are how the main thread waits for the workers, as in the forkIO lesson.
- A transaction can read several TVars and write several, and the group commits together, which is the property a lock cannot give without care.
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:
- A transaction that touches many variables is retried more often, so a large transaction is slower than a small one under contention.
- An IO action cannot be inside a transaction; the transaction is pure STM and the IO happens around it.
- retry and orElse, the next lesson, are how a transaction waits for a condition instead of spinning.
Exercises
- Add a second counter and increment both in one transaction.
- Change the number of threads to eight and explain the result.
- Replace the counter with a TVar [Int] and append the values, then sort them.
- Try atomically (putStrLn "x") and read the error.
- Explain why readTVarIO is fine at the end and wrong during the run.
- 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.
-
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.
-
What does
atomicallydo?Answer
Runs the transaction and makes it visible as one atomic step
It is the boundary between STM and IO and the commit point.
-
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.
-
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 >>= printAnswer
15
The transaction adds five and the read shows the new value.
-
Which monad is a transaction in?
Answer
STMreadTVar and writeTVar return STM actions, and atomically runs them.
-
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 >>= printAnswer
1
The transaction copies the value of a into b.
-
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.
-
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 >>= printAnswer
14
The transaction doubles the value once.
-
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.
-
What does
readTVarIOdo?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