[Haskell] thread-local variables

Einar Karttunen ekarttun at cs.helsinki.fi
Sun Aug 6 06:52:16 EDT 2006

On 05.08 19:56, Frederik Eaton wrote:
> That doesn't answer the question: What if my application has a need
> for several different sets of parameters - what if it doesn't make
> sense to combine them into a single monad? What if there are 'n'
> layers? Is it incorrect to say that the monadic approach requires code
> size O(n^2)?

Well designed monadic approach does not require O(n^2). But if you
want to design code in a way that requires O(n^2) code size you
can do it.

Parallel layers require O(layers).
Nested layers hiding the lower layer need O(layers).

This is not a problem in practice and makes refactoring very easy.

> > And don't have any static guarantees that you have done all the proper
> > initialization calls before you use them.
> Well, there are a lot of things I don't have static guarantees for. 
> For instance, sometimes I call the function 'head', and the compiler
> isn't able to verify that the argument isn't an empty list. If I
> initialize my TLS to 'undefined' then I'll get a similar error
> message, at run time. For another example, I don't use monadic regions
> when I do file IO. I can live with that.

The problem is with refactoring and taking a piece of code and
reusing it somewhere else - and trying to figure out what does
it need.

> > ... Also if we have two pieces of the same per-thread state that we
> > wish to use in one thread (e.g. db-connections) then the TLS
> > approach becomes quite hard.
> No harder than the monadic approach, in my opinion.

In the monadic approach adding a second db connection would involve:
1) add a line to the state record
2) add a db2query = withPart db2 . flip query
3) no changes elsewhere

If the DB API uses a TLS parameter of type "Proxy DBH" how would
you implement this in a nice manner for the TLS case?

> You've redefined 'fork'. If I want a library which works with other
> libraries, that will not be an option. The original purpose of my
> posting to this thread was to ask for two standard functions which
> would let me define thread-local variables in a way which is
> interoperable with other libraries, to the same extent as 'withArgs'
> and 'withProgName' are.

All libraries which may fork may use a preallocated thread pool.
Thus they might not work with TLS. withArgs and withProgName are
global and not very thread-friendly.

- Einar Karttunen

More information about the Haskell mailing list