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

Einar Karttunen ekarttun at cs.helsinki.fi
Mon Jul 31 08:09:59 EDT 2006


On 31.07 03:18, Frederik Eaton wrote:
> I don't think it's necessarily such a big deal. Presumably the library
> with the worker threads will have to be invoked somewhere. One should
> just make sure that it is invoked in the appropriate environment, for
> instance with the database connection already properly initialized.
> 
> (*) One might even want to change the environment a little within each
> thread, for instance so that errors get logged to a thread-specific
> log file.

So we have the following:
1) the library is initialized and spawns worker thread Tw
2) application initializes the database connection and it
   is associated with the current thread Tc and all the children
   it will have (unless changed)
3) the application calls the library in Tc passing an IO action
   to it. The IO action refers to the TLS thinking it is in
   Tc where it is valid.
4) the library runs the callback code in Tw where the TLS state is
   invalid. This is even worse than a global variable in this case.

Of course one can argue that the application should first initialize
the database handle. But if the app uses worker threads (spawned
before library initialization) then things will break if a library
uses TLS and callbacks and they end up running in threads created
before the library initialization.

- Einar Karttunen



More information about the Haskell mailing list