[Haskell] thread-local variables (was: Re: Implicit Parameters)

Einar Karttunen ekarttun at cs.helsinki.fi
Sun Jul 30 05:35:42 EDT 2006


On 29.07 13:25, Frederik Eaton wrote:
> I think support for thread-local variables is something which is
> urgently needed. It's very frustrating that using concurrency in
> Haskell is so easy and nice, yet when it comes to IORefs there is no
> way to get thread-local behavior. Furthermore, that one can make
> certain things thread-local (e.g. with withArgs, withProgName) makes
> the solution seem close at hand (although I can appreciate that it may
> not be). Yet isn't it just a matter of making a Map with existentially
> quantified values part of the state of each thread, just as the
> program name and arguments are also part of that state?

Are thread local variables really a good idea in Haskell?

If variables are thread local how would this combinator work:

withTimeOut :: Int -> IO a -> IO a
withTimeOut tout op = mdo
  mv <- newEmptyMVar
  wt <- forkIO $ do try op >>= tryPutMVar mv >> killThread kt
  kt <- forkIO $ do threadDelay tout
                    e <- tryPutMVar mv $ Left $ DynException $ toDyn TimeOutException
                    if e then killThread wt else return ()
  either throw return =<< takeMVar mv


Would it change the semantics of the action as it is run in a
different thread (this is a must if there are potentially blocking FFI
calls). Now if the action changes the thread local state then
it behaves differently. Do we really want that?

Usually one can just add a monad that wraps IO/STM and provides the
variables one needs. This has the good side of making scoping
explicit.

- Einar Karttunen


More information about the Haskell mailing list