Versions Compared

Key

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

The C Standard, section subclause 5.1.2.3, paragraph 2 [ISO/IEC 9899:2011], says,

Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects. Value computation for an lvalue expression includes determining the identity of the designated object.

...

This compliant solution uses a Microsoft Windows critical section object to make operations involving account_balance atomic . [MSDN].

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

static volatile LONG account_balance;
CRITICAL_SECTION flag;

/* Initialize flag */
InitializeCriticalSection(&flag);
 
int debit(unsigned int amount) {
  EnterCriticalSection(&flag); 
  account_balance -= amount; /* Inside critical section */
  LeaveCriticalSection(&flag);
 
  return 0;
}

...

Bibliography

[ISO/IEC 9899:2011]Section 5.1.2.3, "Program Execution"
[MSDN] 
[Open Group 2004]Section 4.11, "Memory Synchronization"

...