#include <threads.h>
#include <stdlib.h>
/* 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) {
return arr; /* Indicate Error */
}
arr[0] = rand();
arr[1] = rand();
return arr;
}
int add_data(void) {
int *data = get_data();
int result;
if (data == NULL) {
return -1; /* Indicate error */
}
if ((result = tss_set( key, (void *)data)) != thrd_success) {
/* Handle Error */
}
return 0;
}
void print_data() {
/* get this thread's global data from key */
int *data = tss_get(key);
if (data != NULL) {
/* print data */
}
}
int function(void* dummy) {
if (add_data() != 0) {
return -1; /* Indicate error */
}
print_data();
thrd_exit(0);
return 0;
}
int main(void) {
int i,result;
thrd_t thread_id[MAX_THREADS];
/* create the key before creating the threads */
if ((result = tss_create( &key, NULL )) != thrd_success) {
/* Handle Error */
}
/* create threads that would store specific data */
for (i = 0; i < MAX_THREADS; i++) {
if ((result = thrd_create( &thread_id[i], function, NULL )) != thrd_success) {
/* Handle Error */
}
}
for (i = 0; i < MAX_THREADS; i++) {
if ((result = thrd_join(thread_id[i], NULL)) != thrd_success) {
/* Handle Error */
}
}
tss_delete(key);
return 0;
}
|