5.15 Consider how to implement a mutex lock using an atomic hardware instruction
ID: 3558969 • Letter: 5
Question
5.15 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 cempare_and_swap () instructions: void acquire(lock ?mutex) void release (lock ?mutex) Be sure to include any initialization that may be necessary. Implement a mutex lockExplanation / Answer
Test and Set :
typedef struct { int available; } lock;
void init(lock *mutex) {
// available=0 -> lock is available, available=1 -> lock is unavailabe
mutex->available = 0;
}
void acquire(lock *mutex) {
while (mutex->available == 1) // TEST the available
; // spin-wait (do nothing)
mutex->available = 1; // now SET it!
}
void release(lock *mutex) {
mutex->available = 0;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.