[Haskell-cafe] STM and `orElse` on a few thousand TMVars

Simon Marlow simonmar at microsoft.com
Tue Dec 6 08:29:54 EST 2005

On 06 December 2005 10:02, Joel Reymont wrote:

> Is it efficient to wait on a few thousand TMVars?

That depends... while waiting your thread consumes no CPU at all (of
course), and simply waiting on all those TVars only imposes a small
constant overhead on anyone updating one of the TVars (a TMVar is just a
TVar).  However, checking all those TVars is O(n), and this happens
twice each time you wake up: once to find which TVar was modified, and
once again to go back to sleep on all of them.

I'm not sure what you're using all those TMVars for, but it sounds like
it might be better to multiplex them all into a single channel, or
> How would I write something like that, assuming that my TMVars were
> in a list.

perhaps something along the lines of

  foldr orElse (return ()) . map takeTMVar

it depends what you want to return.


More information about the Haskell-Cafe mailing list