CPU often provides atomic instructions for lock implementations. For example, x86’s xchg instruction atomically exchanges the contents of two memory addresses. Implement a spin lock with this instruction, assuming xchg has been provided as a library function
// xchg sets the memory (addr) to newval, and returns the old value.
extern int xchg (int *addr, int newval);
struct spinlock { unsigned int locked;
};
{
}
void spinlock_release (struct spinlock *lock)
{
void spinlock_acquire (struct spinlock *lock)
}
Please don't forget to give thumbs up if you are satisfied with answers.
spinlock_acquire (struct spinlock *lock)
Criticsl Section
spinlock_acquire (struct spinlock *lock) // See below for code
Idea is if lock is available then, acquire the lock and enter into critical section. This can be done using xchg (int *addr, int newval) fuction. xchg (int *addr, int newval) will assign 1 to locked using pointer and return old value of locked.
If old value of locked was 0 then while loop in spinlock_acquire (struct spinlock *lock) will be broken and process will enter in critical section.
If old value of locked was 1,then it indicates that there is already one process P2 in critical section so the process P1 will continue to spinlock and will only enter in critical section when process P2 in critical section will release the lock.
Process P2 after completing critical section will run spinlock_acquire (struct spinlock *lock) and this will now set locked to zero and thus now P1 can enter in critical section.
struct spinlock
{
unsigned int locked;
}
void spinlock_acquire (struct spinlock *lock)
{
while(1)
{
if( xchg(&lock->locked, 1) == 0)
break;
}
}
void spinlock_acquire (struct spinlock *lock)
{
xchg(&lock->locked, 0);
}
CPU often provides atomic instructions for lock implementations. For example, x86’s xchg instruction atomically exchanges the...