tags:

views:

112

answers:

4

Is thread local storage used anywhere else other than making global and static variables local to a thread?Is it useful in any new code that we write?

+4  A: 

TLS can certainly be useful in new code. If you ever want a global variable which needs to be specific to each thread, (like errno in C/C++), thread-local-storage is the way to go.

Charles Salvia
java.text.DateFormat is a good example. You can reuse it, but it is not thread safe, so one good way to work with DateFormat safely without creating a new one each time is to store it in a ThreadLocal.
cjstehno
A: 

These days errno is typically put in thread-local storage.

There are some situations (eg: shared libraries like DLLs that require startup code) where using thread-local storage can be a problem.

T.E.D.
A: 

Thread specific singleton objects? A multi-threaded web server where each thread is handling one request, there is quite a good amount of possibility of some TLS data (like request URL or some database connections, essentially some resources intended to be used at any point during request handling if required) so that they can be easily accessed anywhere in the code when required.

Shailesh Kumar
omfg the S word... :(
Matt Joiner
A: 

I've only needed it for thread-specific error handling, and optimization (in C):

__thread int cpfs_errno;
static __thread struct Cpfs *g_cpfs;

In this example, this saves me passing a context pointer of struct Cpfs * through dozens of functions in which it never changes.

Matt Joiner