#include <threads.h>
#include <stdlib.h>
/* global key to the thread-specific data */
tss_t key;
enum {max MAX_threadsTHREADS = 3 };
int *get_data() {
int *arr = malloc(2*sizeof(int));
if (arr == NULL) {
return arr; /* HandleIndicate Error */
}
arr[0] = rand();
arr[1] = rand();
return arr;
}
voidint 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 */
}
}
voidint *function(void* dummy) {
if (add_data() != 0) {
return -1; /* Indicate error */
print}
print_data();
thrd_exit(0);
return NULL0;
}
int main(void) {
int i,result;
thrd_t thread_id[maxMAX_threadsTHREADS];
/* 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 < maxMAX_threadsTHREADS; i++) {
if ((result = thrd_create( &thread_id[i], function, NULL )) != thrd_success) {
/* Handle Error */
}
}
for (i = 0; i < maxMAX_threadsTHREADS; i++) {
if ((result = thrd_join(thread_id[i], NULL)) != thrd_success) {
/* Handle Error */
}
}
if ((result = tss_delete(key)) != thrd_success) {
/* Handle Error */;
}
return 0;
}
|