Keep pthread variables local
Is there a way while using pthread.h
on a Linux GCC to keep variables local to the thread-function:
int i = 42; // global instance of i
int main() {
pthread_t threads[2];
long t;
pthread_create(&threads[t], NULL, ThreadFunction, (void *) t;
pthread_create(&threads[t], NULL, ThreadFunction2, (void *) t;
}
I wonder whether there is a parameter at the POSIX function creating the new thread and keeping the variables local:
void *ThreadFunction(void *threadid)
{
int i=0;
i++; // this is a local instance of i
printf("i is %d", i); // 开发者_如何学JAVAas expected: 1
}
void *ThreadFunction2(void *threadid)
{
i += 3; // another local instance -> problem
}
Where afterwards i
is 42. Even if I have defined an i
previously I want this i
not to be within my threads.
In gcc, you can make a global variable thread-local by using the __thread
specifier:
__thread int i = 42;
Don't do that. There are better solutions, depending on you want to do.
Global variables are always available in the whole compilation unit (or even more compilation units if you use external declarations). This has nothing to do with threads, it's the default behavior of C/C++. The recommended solution is not to use globals - globals are evil. If you still need to use globals, you may want to prefix them, such as g_i
. Another solution is to put your thread functions into another compilation unit (c file).
The sample code is wrong (by itself) and has undefined behavior. You are trying to read an uninitialized variable t
four times - two times to index an array and two times in a cast expression - and depending on the (undefined) meaning of &threads[t]
, the function pthread_create
may cause more UB.
Besides, its obviously not the code you have used because the pthread_create
functions are lacking closing parentheses.
Regarding the variable i
: declaring a new variable i
(i.e. int i = 0
) in the local scope hides any possible i
's in the more broad scope - so there should not be any problems using i
locally as a variable name inside the function.
phtread has a notion of thread local storage, and gcc offers an easy interface to it with a __thread
storage class. Such variables suffer from all the problems of global variables, and then some more. But sometimes they are handy as all other solutions are worse in context.
精彩评论