...
| Code Block |
|---|
|
int account_balance;
void debit(int amount) {
account_balance -= amount;
}
void credit(int amount) {
account_balance += amount;
}
|
Compliant Solution
| Wiki Markup |
This 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 {{pthread_mutex}} functions. In addition, the {{volatile}} keyword is used so prefetching does not occur (see \[[DCL34-C. Use volatile for data that cannot be cached]\]).
| Code Block |
|---|
|
#include <pthread.h>
volatile int account_balance;
pthread_mutex_t account_lock = PTHREAD_MUTEX_INITIALIZER;
void debit(int amount) {
pthread_mutex_lock(&account_lock);
account_balance -= amount;
pthread_mutex_unlock(&account_lock);
}
void credit(int amount) {
pthread_mutex_lock(&account_lock);
account_balance += amount;
pthread_mutex_unlock(&account_lock);
}
|
...