...
| Code Block | ||
|---|---|---|
| ||
#include <pthread.h>
#include <stdio.h>
#include<malloc.h>
#define MAX_NUMBER_OF_THREADS 3
/* function prototypes */
void destructor(void * data);
void* function();
void add_data();
void print_data();
/* global key to the thread specific data */
pthread_key_t key;
int main( void )
{
   int i;
   pthread_t thread_id[MAX_NUMBER_OF_THREADS];
   /* create the thread specific data key before creating the threads */
   pthread_key_create( &key, NULL );
   /* create threads that will use the key */
   for(i =0; i < MAX_NUMBER_OF_THREADS; i++){
       pthread_create( &thread_id[i], NULL, function, NULL );
   }
   for(i=0;i < MAX_NUMBER_OF_THREADS; i++){
       int ret = pthread_join(thread_id[i], NULL);
       printf("Join return value for thread[%d] = %d",i,ret);
   }
   pthread_key_delete(key);
}
/* Getting some random data */
int *get_data()
{
   int *arr = malloc(2*sizeof(int));
   *arr = rand();
   *(arr+1) = rand();
   return arr;
}
void *function(void)
{
   add_data();
   print_data();
   pthread_exit(NULL);
}
void add_data(void)
{
   int *data = get_data();
   printf("some data = %p\n",data);
   pthread_setspecific( key,
   (void *) data);
}
void print_data()
{
   /* get this thread's global data from
   * priority_key */
   int *data = pthread_getspecific(
   key );
   printf("thread id = %u, data[0] = %d, data[1] = %d \n",(size_t)pthread_self(),*data,*(data+1));
}
Â
|
Compliant Solution
| Code Block | ||
|---|---|---|
| ||
#include <pthread.h>
#include <stdio.h>
#include<malloc.h>
#define MAX_NUMBER_OF_THREADS 3
/* function prototypes */
void destructor(void * data);
void* function();
void add_data();
void print_data();
/* global key to the thread specific data */
pthread_key_t key;
void destructor(void * data){
   pthread_setspecific(key, NULL); // thread specific should be cleared (could be sensitive)
   free(data);
}
/* Getting some random data */
int *get_data(){
   int *arr = malloc(2*sizeof(int));
   *arr = rand();
   *(arr+1) = rand();
   return arr;
}
void *function()
{
   add_data();
   print_data();
   pthread_exit(NULL);
}
void add_data()
{
   int *data = get_data();
   printf("some data = %p\n",data);
   pthread_setspecific( key,
   (void *) data);
}
void print_data()
{
   /* get this thread's global data from key */
   int *data = pthread_getspecific(key);
   printf("thread id = %u, data[0] = %d, data[1] = %d \n",(size_t)pthread_self(),*data,*(data+1));
}
int main( void )
{
   int i;
   pthread_t thread_id[MAX_NUMBER_OF_THREADS];
   /* create the thread specific data key before creating the threads */
   pthread_key_create( &key, destructor );
   /* create thread that will use the key */
   for(i =0; i < MAX_NUMBER_OF_THREADS; i++){
       pthread_create( &thread_id[i], NULL, function, NULL );
   }
Â
   for(i=0;i < MAX_NUMBER_OF_THREADS; i++){
       int ret = pthread_join(thread_id[i], NULL);
       if(ret !=0){
           /* Handle Error */
       }
   }
   pthread_key_delete(key);
}
|