Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added error checks to pthread_*()

...

Code Block
bgColor#ccccff
#include <pthread.h>

volatile int account_balance;
pthread_mutex_t account_lock = PTHREAD_MUTEX_INITIALIZER;

void debit(int amount) {
  int result;
  if ((result = pthread_mutex_lock(&account_lock);)) != 0) {
    /* Handle Error */
  }
  account_balance -= amount;
  if ((result = pthread_mutex_unlock(&account_lock);)) != 0) {
    /* Handle Error */
  }
}

void credit(int amount) {
  if ((result = pthread_mutex_lock(&account_lock);) != 0) {
    /* Handle Error */
  }
  account_balance += amount;
  if ((result = pthread_mutex_unlock(&account_lock);) != 0) {
    /* Handle Error */
  }
}

Risk Assessment

Race conditions caused by multiple threads concurrently accessing and modifying the same data can lead to abnormal termination and denial-of-service attacks, or data integrity violations.

...