How does TVar work? From what I've read it attempts to run all transactions immediately upon receiving them, however, a transaction completing invalidates other currently running transactions, which must then restart. Is this how TVar works?
If this was the case, if there were transactions 1ms long transactions occurring every 100ms, would that mean that a transaction that takes 200ms to process would never complete?
As long as two transactions access distinct
TVars
, they can both be committed simultaneously without invalidating each other.Just to make it clear when a transaction is invalidated, let's consider the following scenario:
t :: TVar Int
is initialized to0
and is read viareadTVar t
at the beginning of a transactionA
.B
is started in which awriteTVar t 1
is executed. Assume thatB
commits beforeA
. The STM system will check whether there are any inconsistencies and conclude that it is safe forB
to commit at this point, so nowwriteTVar t 1
becomes effective.A
to be invalidated since the old value0
oft
was read at the beginning ofA
. (IfA
was allowed to commit, we would get a violation of atomicity.)The original paper [1] on Haskell's STM system (see Sec 6.5) answers your question:
[1] Tim Harris, Simon Marlow, Simon Peyton Jones, and Maurice Herlihy. ACM Conference on Principles and Practice of Parallel Programming 2005 (PPoPP'05).