Threads and Static Data

Regan Heath regan at netmail.co.nz
Thu Dec 13 01:56:21 PST 2007


Jérôme M. Berger wrote:
>  - My first point was to illustrate what thread-local storage is for
> as opposed to instance variables in the thread class. Another
> illustration would be to point to this Wikipedia page:
> http://en.wikipedia.org/wiki/Thread-local_storage

I think the short explaination is that thread local storage is required 
when you want a separate copy of any _global_ variable for each thread. 
  If you have no global varaibles, you don't need it.

'errno' described in the wikipedia page is the classic example.  It is a 
global variable that many unrelated[1] ANSI C functions will set on 
error.  If it was not global how would these functions access it in 
order to set it.  If it was not global how would you know where it was 
in order to check it.

errno and those ANSI functions are like static members of an "ANSI" 
class which is instantiated when your program runs.  Imagine now what 
would happen if they were non static members of that class.  Instead of 
having only one copy of errno you would have one per instance of "ANSI", 
meaning you could instantiate a different one for each thread you started.

Problem solved, not need for thread local storage or any other mechanism 
for ensuring separate copies of global variables per thread.

The same logic can be applied to any other library you care to name, if 
it has an errno style variable then _it_ will need to use thread local 
storage, if it doesn't it's not thread safe[3], period.

On the other hand if the library encapsulates all it's variables in a 
class or struct[2] then you are free to have a separate instance of the 
class or struct per thread, typically as a member of your thread class.

Regan

[1]unrelated in that they perform many and varied tasks, related in that 
they are all ANSI C functions and they all use errno.

[2]unless they are static members of a class, as this gives only one 
copy per process and again thread local storage has to be used, or it 
will never be thread safe[3].

[3]unless the variable is protected by synchronisation constructs like 
critical sections or mutexes.



More information about the Digitalmars-d mailing list