Can one transaction update two different TVar
s in an atomic way? i.e. can I compose data structures out of lots of TVar
s to reduce contention? If so, could you provide an example?
Haskell: Updating two or more TVars atomically. Possible?
1k views Asked by Clinton At
2
There are 2 answers
0
On
A transaction is completely atomic; if it modifies multiple TVar
s, both changes will happen together, atomically, in isolation. Anything run in a single atomically
block is a single transaction. For example:
swap :: (Num a) => TVar a -> TVar a -> STM ()
swap v1 v2 = do
a <- readTVar v1
b <- readTVar v2
writeTVar v1 b
writeTVar v2 a
Here, swap a b
will atomically swap two TVar
s. The composability of atomic transactions in this way is one of the main benefits of STM.
Yes, you can update multiple TVars atomically in one transaction. That's sort of the whole point of STM. It wouldn't be very useful if you couldn't.
Here is a (somewhat silly) example of storing TVars in a data structure. It simulates a bunch of random concurrent transactions between accounts in a bank, where each account is just a
TVar Integer
. The account TVars are kept in a map from account IDs, which is itself kept in a TVar so that new accounts can be created on the fly.This should print a total balance of zero at the end if there were no race conditions during the transfers.