Concurrent Haskell extends Haskell 98 with explicit concurrency. Its two main underlying concepts are: A primitive type MVar α implementing a bounded/single-place asynchronous channel, which is either empty or holds a value of type α. The ability to spawn a concurrent thread via the forkIO primitive. Built atop this is a collection of useful concurrency and synchronisation abstractions such as unbounded channels, semaphores and sample variables. Haskell threads have very low overhead: creation, context-switching and scheduling are all internal to the Haskell runtime. These Haskell-level threads are mapped onto a configurable number of OS-level threads, usually one per processor core. Software Transactional Memory The software transactional memory (STM) extension to GHC reuses the process forking primitives of Concurrent Haskell. STM however: avoids MVars in favour of TVars. introduces the retry and orElse primitives, allowing alternative atomic actions to be composed together. STM monad The STM monad is an implementation of software transactional memory in Haskell. It is implemented in GHC, and allows for mutable variables to be modified in transactions. Traditional approach Consider a banking application as an example, and a transaction in it—the transfer function, which takes money from one account, and puts it into another account. In the IO monad, this might look like: type Account = IORef Integer transfer :: Integer -> Account -> Account -> IO () transfer amount from to = do fromVal <- readIORef from -- (A) toVal <- readIORef to writeIORef from (fromVal - amount) writeIORef to (toVal + amount) This causes problems in concurrent situations where multiple transfers might be taking place on the same account at the same time. If there were two transfers transferring money from account from, and both calls to transfer ran line (A) before either of them had written their new values, it is possible that money would be put into the other two accounts, with only one of the amounts being transferred being removed from account from, thus creating a race condition. This would leave the banking application in an inconsistent state. A traditional solution to such a problem is locking. For instance, locks can be placed around modifications to an account to ensure that credits and debits occur atomically. In Haskell, locking is accomplished with MVars: type Account = MVar Integer credit :: Integer -> Account -> IO () credit amount account = do current <- takeMVar account putMVar account (current + amount) debit ::