Search code examples
cmultithreadingpthreadsmulticore

Private Variables in Threads


I'm a starter at using pthreads with C in Linux. I need to create and use private thread variables.

Let me explain exactly what I need with an example. In the following piece of code I create 4 threads, I would like each of them to create a private variable foo, so in total 4 foo variables, one for each thread. Each thread should only "see" it's own foo variable and not the others. For example, if thread 1 sets foo = 56 and then calls doStuff, doStuff should print 56. If thread 2 sets foo = 99 and then calls doStuff, doStuff should print 99. But if thread 1 calls again doStuff, 56 should be printed again.

void doStuff()
{
  printf("%d\n", foo); // foo is different depending on each thread
}

void *initThread(void *threadid)
{
  // initalize private thread variable (foo) for this thread
  int foo = something;

  printf("Hello World! It's me, thread #%ld!, %d\n", (long) threadid, x);
  doStuff();
}

int main()
{
   pthread_t threads[4];

   long t;
   for (t = 0; t < 4; t++){
     printf("In main: creating thread %ld\n", t);
     pthread_create(&threads[t], NULL, initThread, (void *) t);
   }

   pthread_exit(NULL); /* support alive threads until they are done */
}

Any ideas on how to do this (which is basically the idea of private thread variables) using pthreads?


Solution

  • I believe you're looking for the term Thread Local Storage. Check the documentation for pthread_get_specific, pthread_get_specific, pthread_create_key or use the __thread storage class specifier.

    Another alternative is to have a single global variable and use a mutex, or simply pass foo in as an argument.