Can one transaction update two different TVars in an atomic way? i.e. can I compose data structures out of lots of TVars to reduce contention? If so, could you provide an example?
Can one transaction update two different TVar s in an atomic way? i.e. can
Share
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.