Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Fixing up a CS and wordsmithing

...

This compliant solution uses a mutex to make credits and debits atomic operations. All credits and debits will now affect the account balance, so an attacker cannot exploit the race condition to steal money from the bank. The mutex is created with the mtx_init() function. Note that the The presence of the mutex makes declaring account_balance volatile unnecessary.

...

This compliant solution uses an atomic variable to synchronize credit and debit operations. All credits and debits will now affect the account balance, so an attacker cannot exploit the race condition to steal money from the bank. The atomic integer does not need to be initialized because default (zero) initialization of an atomic object with static or thread-local storage is guaranteed to produce a valid state. The += and -= operators behave atomically when used with an atomic variable.

Code Block
bgColor#ccccff
langc
#include <stdatomic.h>

atomic_int account_balance;

void debit(int amount) {
  atomic_fetch_sub(&account_balance, -= amount);
}

void credit(int amount) {
  atomic_fetch_add(&account_balance, += amount);
}

Noncompliant Code Example (Double-Fetch)

...