Operating System question Answer this about a mutex lock imp
Operating System question: Answer this about a mutex lock implementation.
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.Solution
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;
}
The lock is to be held for a short duration - It makes more sense to use a spinlock as it may in fact be faster than using a mutex lock which requires suspending –and awakening - the waiting process.
The lock is to be held for a long duration - a mutex lock is preferable as this allows the other processing core to schedule another process while the locked process waits.
A thread may be put to sleep while holding the lock - a mutex lock is definitely preferable as you wouldn’t want the waiting process to be spinning while waiting for the other process to wake up.

