#include #include #include #include //dummy structures typedef int ThrStat; typedef int ThrBuffer; //global variables, shared among threads pthread_key_t thr_stat, thr_buffer; void *threadf(void *x); void func(); void free_data(void *x); int main() { pthread_t t1, t2; //memory for handles of created threads //main thread – initialization of ‘keys’, basis for thread specific data pthread_key_create(&thr_stat, free_data); pthread_key_create(&thr_buffer, free_data); //initially, value NULL is associated with each key for all threads pthread_create(&t1, NULL, threadf, (void *) 1); pthread_create(&t2, NULL, threadf, (void *) 2); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0; } //worker thread - initialization void *threadf(void *x) { ThrStat *stat; ThrBuffer *buffer; stat = malloc(sizeof(ThrStat)); //stat - local variable buffer = malloc(sizeof(ThrBuffer)); //buffer - local variable *stat = (int) x; *buffer = *stat * 10; //associate stat with key thr_stat for current thread only!!! pthread_setspecific(thr_stat, stat); pthread_setspecific(thr_buffer, buffer); usleep(100000); func(); return NULL; } //worker thread – in some function void func() { ThrStat *s; ThrBuffer *b; //get data associated with keys s = pthread_getspecific(thr_stat); b = pthread_getspecific(thr_buffer); //use ‘s’ and ‘b’ printf("stat=%d, buffer=%d\n", *s, *b); } void free_data(void *x) { //printf("Releasing data %p\n", x); if (x) free(x); }