/* global key to the thread-specific data */
tss_t key;
enum {max_threads = 3};
int *get_data() {
int *arr = malloc(2*sizeof(int));
if (arr == NULL) {
/* Handle Error */
}
arr[0] = rand();
arr[1] = rand();
return arr;
}
void add_data(void) {
int *data = get_data();
int result;
if ((result = tss_set( key, (void *)data)) != thrd_success) {
/* Handle Error */
}
}
void print_data() {
/* get this thread's global data from key */
int *data = tss_get(key);
/* print data */
}
void *function(void* dummy) {
add_data();
print_data();
thrd_exit(0);
return NULL;
}
int main(void) {
int i,result;
pthreadthrd_t thread_id[max_threads];
/* create the key before creating the threads */
if ((result = pthread_keytss_create( &key, NULL )) != thrd_success) {
/* Handle Error */
}
/* create threads that would store specific data */
for (i = 0; i < max_threads; i++) {
if ((result = pthreadthrd_create( &thread_id[i], NULL, function, NULL )) != thrd_success) {
/* Handle Error */
}
}
for (i = 0; i < max_threads; i++) {
if ((result = pthreadthrd_join(thread_id[i], NULL)) != thrd_success) {
/* Handle Error */
}
}
if ((result = pthreadtss_key_delete(key)) != thrd_success) {
/* Handle Error */
}
return 0;
}
|