Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ffcccc
langc
/* 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;
}

...

Code Block
bgColor#ffcccc
langc
void *function(void* dummy) {
  add_data();
  print_data();
  free( tss_get(key));
  thrd_exit(0);
  return NULL;
}

/* ... Other functions are unchanged */

int main(void) {
  /* ... */
  if ((result = pthread_keytss_delete(key)) != thrd_success) {
    /* Handle Error */
  }
  return 0;
}

...

Code Block
bgColor#ccccff
langc
void* destructor(void* data) {
  free(data);
  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, destructor)) != thrd_success) {
    /* Handle Error */
  }

  /* ... */

  if ((result = pthread_keytss_delete(key)) != thrd_success) {
    /* Handle Error */
  }
  return 0;
}

...