Assuming that the instruction XCHG(int*var1, int*var2) can be used to atomically
ID: 3838759 • Letter: A
Question
Assuming that the instruction XCHG(int*var1, int*var2) can be used to atomically swap two integer pointer variables (e.g. before XCHG: *y = 0 and *z = 1 and after XCHG: *y = 1 and *z = 0), write the bodies of lock() and unlock() to illustrate how the XCHG can be used to provide mutual exclusion. #define N 10000 int bolt = 0; int shared = 0; void lock(int * key); void unlock(int * key); void increment(void) {int key = 1; while(1) {lock (& key); shared = shared + N; unlock (&key;);}} void decrement(void) {int key = 1; while(1) {lock(&key;); shared = shared - N; unlock(&key;);}} void lock(int * key) {//you can access the actual value of key by using *key} void unlock(int * key) {//you can access the actual value of key by using *key}Explanation / Answer
The lock() and unlock() function is defined below,
Void lock (int *key)
{
int *var = &bolt;
while(bolt==1);
XCHG (*var, *key);
}
Void unlock (int *key)
{
int *var = &bolt;
while(bolt==0);
XCHG (*var, *key);
}
Explanation:
Bolt variable is being used to maintain the mutual exclusion between increment and decrement functions.
When the bolt is 1, no process can use the shared resources. XCHG is been used to make swap the value of bolt with the key value.