Ex1. Deadlock 1 // assume all the variables are initialized correctly 2 double balance[2]; // 0 for alice, 1 for bob 3 smutex_t mtx[2]; // 0 for alice, 1 for bob 4 5 bool 6 transfer(int from, int to, double trans) { 7 smutex_lock(&mtx[from]); 8 smutex_lock(&mtx[to]); 9 10 bool result = false; 11 if (balance[from] > trans) { 12 balance[from] = balance[from] - trans; 13 balance[to] = balance[to] + trans; 14 result = true; 15 } 16 17 smutex_unlock(&mtx[to]); 18 smutex_unlock(&mtx[from]); 19 return result; 20 } Ex2. Monitor 1 class BankAccount { 2 // assume all the variables are initialized correctly 3 private: 4 scond_t condv; 5 smutex_t mtx; 6 double balance; 7 8 public: 9 bool withdraw(double amount); 10 void deposit(double amount); 11 void payTax(double amount); 12 }; 13 14 bool 15 BankAccount::withdraw(double amount) { 16 smutex_lock(&mtx); 17 bool ret = false; 18 if (balance >= amount) { 19 balance -= amount; 20 ret = true; 21 } 22 smutex_unlock(&mtx); 23 return ret; 24 } 25 26 void 27 BankAccount::deposit(double amount) { 28 // your code here 29 30 31 32 } 33 34 void 35 BankAccount::payTax(double amount) { 36 // your code here 37 38 39 40 } Ex3. Priority inversion 1 smutex_t res; 2 3 void 4 highPriority() { 5 ... // do something 6 smutex_lock(&res); 7 ... // handle resource 8 smutex_unlock(&res); 9 printf("A "); 10 } 11 12 void 13 mediumPriority() { 14 ... // do something 15 printf("B "); 16 } 17 18 void 19 lowPriority() { 20 smutex_lock(&res); 21 ... // handle resource 22 smutex_unlock(&res); 23 ... // do something 24 printf("C "); 25 } Ex4. Reader writer lock 1 struct sharedlock { 2 int value; // when the lock is created, value is initialized to 0 3 }; 4 5 void 6 reader_release(struct sharedlock* lock) { 7 atomic_decrement(&lock->value); 8 } 9 10 void 11 writer_acquire(struct sharedlock* lock) { 12 while(cmpxchg_val(&lock->value, 0, -1) != 0) {} 13 } 14 15 void 16 writer_release(struct sharedlock*) { 17 cmpxchg_val(&lock->value, -1, 0); 18 } Ex5. Break sequential consistency 1 int a = 0, b = 0; 2 void 3 foo() { 4 a = 1; 5 b = 1; 6 } 7 8 void 9 bar() { 10 while (b == 0); 11 printf("%d", a); 12 } Question: Can the output be 0?