Explain why the following implementation the semaphore P and V operations in terms of futexes doesn't work.
void P(futex_t *f) {
/* f->val contains the value of the semaphore */
int v;
while (1) {
while ((v = f->val) > 0) {
/* semaphore is positive */
if (CAS(&f->val, v, v-1) == v) {
/* we were able to decrement it without
interference */
return;
}
/* try again while semaphore is still positive
}
/* semaphore is zero: wait for a V operation
futex_wait(f, 0);
}
}
void V(futex_t *f) {
if (atomic_inc(&f->val) == 0) {
/* semaphore was zero: there might be
waiting threads */
futex_wake(f);
}
return;
}