C/Tls
From Attie's Wiki
(Difference between revisions)
m (Created page with 'Compile with <code>gcc main.c -g -o main -lpthread</code> This is <code>main.c</code>: <source lang="c"> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define TC…') |
m |
||
Line 1: | Line 1: | ||
+ | This is an example of Thread Local Storage with pthreads | ||
+ | |||
Compile with <code>gcc main.c -g -o main -lpthread</code> | Compile with <code>gcc main.c -g -o main -lpthread</code> | ||
Revision as of 09:10, 28 February 2012
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; }