logo

Crowdly

Consider the following lock and unlock functions from class that puts threads to...

✅ The verified answer to this question is available below. Our community-reviewed solutions help you understand the material better.

Consider the following lock and unlock functions from class that puts threads to sleep instead of spin-waiting. Identify the bug(s) in the code. Assume TestAndSet runs atomically.

void lock(lock_t *m) {

while (TestAndSet(&m->guard, 1) == 1)

; // acquire guard lock by spinning

if (m->flag == 0){

m->flag = 1; // lock is acquired

m->guard = 0;

} else {

queue_add(m->q, gettid());

m->guard = 0;

park();

}

}

void unlock(lock_t *m) {

while (TestAndSet(&m->guard, 1) == 1)

; // acquire guard lock by spinning

if (queue_empty(m->q))

m->flag = 0; // let go of lock; no one wants it

else

unpark(queue_remove(m->q)); // hold lock (for next thread!)

m->guard = 0;

}

More questions like this

Want instant access to all verified answers on moodle31.upei.ca?

Get Unlimited Answers To Exam Questions - Install Crowdly Extension Now!