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
