Question

CPU often provides atomic instructions for lock implementations. For example, x86’s xchg instruction atomically exchanges the...

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)

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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);
}
Add a comment
Know the answer?
Add Answer to:
CPU often provides atomic instructions for lock implementations. For example, x86’s xchg instruction atomically exchanges the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT