Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: made 1st NCCE more plausible

...

Code Block
bgColor#ffcccc
langc
#include <stdatomic.h>
 
/*
 * Sets index to point to index of maximum element in array
 * and value to contain maximum array value.
 */
void find_max_element(atomic_int array[], size_t *index, int *value);

void func(void) {
  static size_t index;
static int value;
static atomic_int array[];
  size_t index;
  int value;
void func(void) {
  find_max_element(array, &index, &value);
  /* ... */
  if (!atomic_compare_exchange_strong(array[index], value, 0)) {
    /* Handle error */
  }
}

...

  • index may have changed.
  • value may have changed (that is, the value of the value variable).
  • value may no longer be the maximum value in the array.

Compliant Solution (Mutex)

This compliant solution uses a mutex to prevent the data from being modified during the operation. Although this code is thread-safe, it is no longer lock-free.

Code Block
bgColor#ccccff
langc
#include <stdatomic.h>
#include <threads.h>
 
void func(void) {
 static atomic_int array[];
static  size_t index;
static  int value;
 static mtx_t array_mutex;

void func(void) {
  if (thrd_success != mtx_lock(&array_mutex)) {
    /* Handle error */
  }
  find_max_element(array, &index, &value);
  /* ... */
  if (!atomic_compare_exchange_strong(array[index], value, 0)) {
    /* Handle error */
  }
  if (thrd_success != mtx_unlock(&array_mutex)) {
    /* Handle error */
  }
}

...