Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: should not be able to debit a negative value, so i changed int to unsigned int

...

Code Block
bgColor#ffcccc
bool flag = false;

void test() {
  while (!flag) {
    sleep(1000);
  }
}

void wakeup(){
  flag = true;
}

void debit(unsigned int amount){
  test();
  account_balance -= amount;
}

...

Code Block
bgColor#ffcccc
volatile bool flag = false;

void test() {
  while (!flag){
    sleep(1000);
  }
}

void wakeup(){
  flag = true;
}

void debit(unsigned int amount) {
  test();
  account_balance -= amount;
}

...

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

int account_balance;
pthread_mutex_t flag  = PTHREAD_MUTEX_INITIALIZER;

void debit(unsigned int amount) {
  pthread_mutex_lock(&flag);
  account_balance -= amount; /* Inside critical section */
  pthread_mutex_unlock(&flag);
}

...