Friday, September 2, 2011

How to use Thread Local Storage (TLS) in Pthreads?

To use TLS using Pthreads API...
  1. a key must be created using the pthread_key_create()
  2. data that needs to have thread-scope(e.g custom thread id) should be associated with the key using pthread_setspecific()
  3. Associated data can be retrieved later using pthread_getspecific() 
Following code demonstrates TLS usage...


#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

void * thread_func(void *);
void say_hello();

pthread_key_t thr_id_key;

void main(int argc, void ** argv)
{
pthread_t thread;
int * thread_id;
int i;

pthread_key_create(&thr_id_key, NULL);

for(i = 1; i <= 10; i++)
{
thread_id = (int *)malloc(sizeof(int));
*thread_id = i;
pthread_create(&thread, NULL,
thread_func, (void *)(thread_id));
}

pthread_exit(NULL);
}

void * thread_func(void * thread_id)
{
pthread_setspecific(thr_id_key, thread_id);

say_hello();

return NULL;
}

void say_hello()
{
printf("Thread [%d] says Hello!\n",
*((int *)pthread_getspecific(thr_id_key)));
}


As can be seen in the code, a key is common to all the threads in the process. Only the value it refers is private to a thread. If a key is no longer needed by all the threads, it can be deleted using pthread_key_delete(thr_id_key)

1 comment:

David Solt said...

Did you mean to pass in thread_id[i] to pthread_create?