Consider how to implement a mutex lock using an atomic hardw
Solution
Consider how to implement a mutex lock using an atomic hardware instruction. Assume that the following structure defining the mutex lock is available:
 typedef struct {
 int available;
 } lock;
 (available == 0) indicates that the lock is available, and a value of 1 indicates that the lock is unavailable. Using this struct, illustrate
 how the following functions can be implemented using the test and set() and compare and swap() instructions:
 • void acquire(lock *mutex)
 • void release(lock *mutex)
 Be sure to include any initialization that may be necessary.
// program for implementing the above problem
Test and Set:
 -------------
 typedef struct
 {
 int available;
 }lock;
 
 void init(lock *mutex)
    {
    // available==0 -> lock is available, available==1 -> lock unavailable
    mutex->available=0;
    }
int test_And_Set(int *target)
    {
 int rv = *target;
 *target = true;
 return rv
    }
void acquire(lock *mutex)
    {
    while(test_and_set(&mutex->available,1)==1);
 }
 void release(lock *mutex)
    {
    mutex->available=0;
    }   
Compare and Swap:   
 -----------------
 int compare_and_Swap(int *ptr,int expected,int new)
    {
 int actual = *ptr;
 if(actual == expected)
    *ptr = new;
 return actual;
    }
void acquire(lock *mutex)
    {
    while(compare_and_swap(&mutex->available,0,1)==1);
    }
 void release(lock *mutex)
    {
         mutex->available=0;
    }


