liveBook · Manning

TVar

As explained in Functional Design and Architecture: Examples in Haskell

A TVar is a transactional mutable variable used by Haskell's software transactional memory mechanisms.

A TVar is a transactional mutable variable for shared state in Haskell software transactional memory (STM). It separates a concurrent data model from the transactions that modify it, allowing independent parts of a structure to be accessed without unnecessary blocking. section 9.2.1

Use TVars through STM operations rather than unrestricted IO mutation:

  • Create a variable with newTVar. section 9.2.1
  • Read and update it with readTVar and writeTVar inside an STM transaction. section 9.2.1
  • Run the completed transaction with atomically, which provides atomic execution. section 9.2.1
  • Use retry when a precondition is false; STM blocks the transaction and resumes it after a relevant TVar changes. section 9.2.2

Bounding concurrent processes

A runtime can store its current process count in a TVar. An increase transaction reads the count, retries when the maximum is reached, and otherwise writes the incremented value. A completion handler decrements the same TVar. This replaces manually paired MVar operations and polling with sequential-looking, race-free coordination. section 9.2.2

Thread-safe domain state

A meteor-reporting channel can use TVar [Meteor]. Its STM operation reads the current list and writes the new meteor at the front; LangL can expose that operation through evalStmAtomically. section 9.2.3

type TVar a
 
newTVar   :: STM (TVar a)
readTVar  :: TVar a -> STM a
writeTVar :: TVar a -> a -> STM ()

The compact interface shows the essential TVar lifecycle: create transactional state, read it within STM, and write it within STM. section 9.2.1

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Defines the core operations, atomic execution, retry behavior, and domain integration, while deferring deeper STM usage subtleties.
Examples
Demonstrates process counting, meteor reporting, transactional queues, and dining-philosophers fork coordination.
What it assumes
Assumes Haskell concurrency concepts while contrasting TVars with IORefs and MVars and establishing STM’s data-behavior split.
What you can do after
Apply TVars through atomically and retry to construct thread-safe shared state and blocking resource coordination.
How it connects
Connects TVars to STM, transactions, TQueue, MVar, IORef, concurrency, and Free monads.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.