Search code examples
multithreadinghaskellstm

Haskell STM and retry


When we run a STM expression which hits retry, the thread is blocked and the transaction is run once again if the entries are modified.

But I was wondering :

  • If we read a STM variable which, in that specific branch leading to retry, is not actually used , would updating it try to perform the transaction again ?

  • While the thread is blocked, is it really blocked ? or is it recycled in a thread pool to be used by other potentially waiting operations ?


Solution

    1. Yes. Reading STM variable will invoke stmReadTVar - see here. This will generate new entry in transaction record and it will be checked on commit. If you take a look here you will find that ReadTVarOp marked as an operation with side effect (has_side_effects = True) so I don't think compiler will eliminate it regardless will you use it result or not.
    2. As @WillSewell wrote Haskell uses green threads. You can even use STM in single-threaded runtime without worry that the actual OS thread will be blocked.