Chapter 10. Software Transactional Memory
Software transactional memory (STM) is a technique for simplifying concurrent programming by allowing multiple state-changing operations to be grouped together and performed as a single atomic operation. Strictly speaking, “software transactional memory” is an implementation technique, whereas the language construct we are interested in is “atomic blocks.” Unfortunately, the former term has stuck, and so the language-level facility is called STM.
STM solves a number of problems that arise with conventional concurrency abstractions, which we describe here through a series of examples. For reference throughout the following sections, the types and operations of the STM interface are:
Control.Concurrent.STM
dataSTMa-- abstractinstanceMonadSTM-- among other thingsatomically::STMa->IOadataTVara-- abstractnewTVar::a->STM(TVara)readTVar::TVara->STMawriteTVar::TVara->a->STM()retry::STMaorElse::STMa->STMa->STMathrowSTM::Exceptione=>e->STMacatchSTM::Exceptione=>STMa->(e->STMa)->STMa
Running Example: Managing Windows
Imagine a window manager that manages multiple desktops. The user can move windows from one desktop to another, while at the same time, a program can request that its own window move from its current desktop to another desktop. The window manager uses multiple threads: one to listen for input from the user, a set of threads to listen for requests from the programs ...