C/Tls

From Attie's Wiki
Revision as of 16:08, 14 February 2013 by Attie (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This is an example of Thread Local Storage with pthreads

Compile with gcc main.c -g -o main -lpthread

This is main.c:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
 
#define TC 5
 
pthread_key_t tKey;
 
void thread(int id) {
  int i;
 
  pthread_setspecific(tKey, &id);
 
  for (i = 0; i < 3; i++) {
    int *myVar;
 
    myVar = pthread_getspecific(tKey);
 
    printf("hello: %s(%d-%d)\n", __FUNCTION__, id, *myVar);
    usleep(100000);
  }
}
 
int main(int argc, char *argv[]) {
  int i;
  pthread_t tid[TC];
 
  pthread_key_create(&tKey, NULL);
 
  printf("hello: %s\n", __FUNCTION__);
 
  for (i = 0; i < TC; i++) {
    printf("starting %d...\n", i);
    pthread_create(&tid[i], NULL, (void *(*)(void*))thread, (void*)i);
  }
 
  for (i = 0; i < TC; i++) {
    pthread_join(tid[i], NULL);
  }
 
  return 0;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox