Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed example code to compy with C11. Added chaecks for the return codes of the Standard Library functions.

...

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

Noncompliant Code Example

...

Code Block
bgColor#ffcccc
langc
void *#include <threads.h>
#include <stdlib.h>

int function(void* dummy) {
  if (add_data() != 0) {
    return -1;	/* Indicate error */
  }
  print_data();
  free( tss_get(key));
  thrd_exit(0);
  return NULL0;
}

/* ... Other functions are unchanged */

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

Compliant Solution

...

Code Block
bgColor#ccccff
langc
void*#include <threads.h>
#include <stdlib.h>

enum { MAX_THREADS = 3 };

void destructor(void* data) {
  free(data);
  return NULL;
}

int main(void) {
  int i,result;
  thrd_t thread_id[maxMAX_threadsTHREADS];

  /* create the key before creating the threads */
  if ((result = tss_create( &key, destructor)) != thrd_success) {
    return EXIT_FAILURE;	/* HandleIndicate Errorerror */
  }

  /* ... */

  if ((result = tss_delete(key)) != thrd_success) {
    /* Handle Error */
  }
 ;

  return 0;
}

Risk Assessment

...