Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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 lock

Explanation / 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;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote