🎓 A1Learner
🔍
0 of 47 lessons completed

Haskell TVar Basics

A TVar is a changeable box that threads can share. It holds one value that transactions can read and change.

A new TVar holds its starting value

Create a TVar holding 42. Read it back from the main thread.

import Control.Concurrent.STM

main :: IO ()
main = do
  t <- newTVarIO (42 :: Int)
  v <- readTVarIO t
  print v

ModifyTVar prime doubles a value

Start with 21. Double it inside one transaction.

import Control.Concurrent.STM

main :: IO ()
main = do
  t <- newTVarIO (21 :: Int)
  atomically $ modifyTVar' t (* 2)
  v <- readTVarIO t
  print v

Read and write inside one transaction

Start with 41. Read the value inside a transaction and write back one more.

import Control.Concurrent.STM

main :: IO ()
main = do
  t <- newTVarIO (41 :: Int)
  atomically $ do
    v <- readTVar t
    writeTVar t (v + 1)
  result <- readTVarIO t
  print result

Example

import Control.Concurrent.STM

main :: IO ()
main = do
  t <- newTVarIO (10 :: Int)
  atomically $ modifyTVar' t (* 3)
  atomically $ modifyTVar' t (+ 12)
  v <- readTVarIO t
  print v

Key points

  • TVar: a changeable box shared between threads.
  • NewTVarIO: newTVarIO creates a TVar with a starting value.
  • ReadTVarIO: readTVarIO reads a TVar outside a transaction.
  • ModifyTVar': modifyTVar' changes a TVar by applying a function to its value.
  • WriteTVar: writeTVar sets a TVar to a new value inside a transaction.

In this example, a TVar starts at 10. The first transaction triples it to 30. The second transaction adds 12 to reach 42. The main thread reads the TVar back and prints 42.

Note

readTVar and writeTVar work inside a transaction, while readTVarIO works outside one.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which function reads a TVar outside a transaction?