Thread Local Storage Template

Mikola Lysenko mclysenk at mtu.edu
Tue Sep 12 07:21:05 PDT 2006


Stewart Gordon wrote:
> 
> I can see that this idea in itself might have some practical uses, I'm 
> just trying to think what they are....
> 
> Is there a particular reason that the whole code is duplicated between 
> TLS_UsePthreads and TLS_UseWinAPI, rather than versioning only what's 
> different?
> 
> Stewart.
> 

There are plenty of uses for thread local storage.  Particularly if you 
want to have some sort of static variable that must be unique to each 
thread without modifying the code for the thread object.

For example, StackThreads has a static getRunning method that returns 
the currently executing context.  Each thread may be executing a 
different context, so there needs to be some mechanism for directly 
associating each context with each thread.  Adding a member to each 
thread is not only impractical, but also illegal.  You could avoid using 
getRunning by passing the running context around as a parameter, but 
this becomes very confusing very quickly.

Thread local storage simplifies things.  By placing the current context 
in thread local storage, it is trivial to determine which context is 
currently executing in a given thread.

Here are some other examples:
http://plonetest.haiku-os.org/node/53
http://www.c-sharpcorner.com/Code/2003/March/UseThreadLocals.asp

Besides the places where it simplifies design, several algorithms can 
benefit by reducing synchronization costs with technique.  There are 
many well known memory allocators that require a separate pool for each 
thread.  By avoiding the overhead of acquiring a common lock, the level 
of contention is reduced and overall system throughput is increased.

As for where to place the version statements, this is a purely aesthetic 
choice.  In support of the style, std.thread does things the same way.



More information about the Digitalmars-d-announce mailing list