Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 548
nicolas Avatar asked Dec 28 '25 13:12

nicolas


2 Answers

  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.
like image 96
schernichkin Avatar answered Jan 01 '26 09:01

schernichkin


Re. 1: as I understand your question, yes that is correct; your entire STM transaction will have a consistent view of the world including branches composed with orElse (see: https://ghc.haskell.org/trac/ghc/ticket/8680). But I'm not sure what you mean by "but my transaction actually depends on the value of just 1 variable"; if you do a readTVar then changes to that var will be tracked.

Re. 2: you can think of green threads as lumps of saved computation state that are stored in a stack-like thing and popped off, run for a bit, and put back onto the stack when they can't make further progress for the time being ("blocked") or after they've run for long enough. The degree to which this happens in parallel depends on the number of OS threads you tell the runtime to use (via +RTS -N). You can have a concurrent program that uses thousands of green threads but is only run with a single OS thread, and that's perfectly fine.

like image 27
jberryman Avatar answered Jan 01 '26 08:01

jberryman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!