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); // as 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.
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).