Thread variables in C?

Caporegime
Joined
12 Mar 2004
Posts
29,962
Location
England
I need to know how to implement thread local storage in C using pthreads. How do I assign a variable to the created threads? I know that there is a " __thread" keyword, I'm just not totally sure how to use it. Can I just type " __thread int data = 0;" before the thread is created?
 
You don't assign variables to a specific thread.


Code:
int foo(int someparam) {
   __thread int myThreadVariable=10;
   myThreadVariable+=someparam;
   ... do some more processing ...
   return processingResult;
}

So your threads would enter foo() and each thread would have it's own myThreadVariable. Initially each thread would have it's myThreadVariable set to 10 however as each thread could enter the foo() function with a different someparam value thus by the time it enters ...do some more processing... the value of myThreadVariable will be different for each thread.
 
Back
Top Bottom