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 ?


  • 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.
  • 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.

  • 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.

    链接地址: http://www.djcxy.com/p/81462.html

    上一篇: STM被阻挡的确切原因是什么?

    下一篇: Haskell STM并重试