logo

Crowdly

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

✅ Перевірена відповідь на це питання доступна нижче. Наші рішення, перевірені спільнотою, допомагають краще зрозуміти матеріал.

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;

}

Більше питань подібних до цього

Хочете миттєвий доступ до всіх перевірених відповідей на moodle31.upei.ca?

Отримайте необмежений доступ до відповідей на екзаменаційні питання - встановіть розширення Crowdly зараз!