...
Declaring flag
as volatile solves the problem of reading stale data, but still does not provide atomicity guarantees needed for synchronization primitives to work correctly. The volatile
keyword does not promise to provide the guarantees needed for synchronization primitives.
Compliant
...
Solution
The compliant code example solution would involve using a mutex to protect critical sections.
Code Block | ||
---|---|---|
| ||
#include <pthread.h>
volatile int account_balance;
pthread_mutex_t flag = PTHREAD_MUTEX_INITIALIZER;
void debit(int amount) {
pthread_mutex_lock(&flag);
account_balance -= amount;//Inside critical section
pthread_mutex_unlock(&flag);
}
|
...