The atomic fetch-and-set instruction unconditionally sets the memory location to and fetches the old value of in without allowing any intervening access to the memory location . Consider the following implementation of and functions on a binary semaphore .
void P (binary_semaphore *s) {
unsigned y;
unsigned *x = &(s->value);
do {
fetch-and-set x, y;
} while (y);
}
void V (binary_semaphore *s) {
S->value = 0;
}
Which one of the following is true?
View worked solution
Answer: A
To determine which statement is true, let us analyze the behavior of the fetch-and-set instruction and the implementation of the and functions.
1. Analysis of the Implementation
fetch-and-set x, y: This atomic instruction sets the memory location (which points tos->value) to and stores its old value in .- Function (Locking):
- If
s->valueis initially (semaphore is free),fetch-and-setsets it to and returns . The loop conditionwhile (y)becomes false, and the process successfully enters the critical section. - If
s->valueis initially (semaphore is locked),fetch-and-setsets it to (no change) and returns . The loop conditionwhile (y)remains true, causing the process to busy-wait (spin-lock).
- If
- Function (Unlocking): It unconditionally resets
s->valueto , allowing another waiting process to acquire the lock.
2. Evaluating the Options
- Option A: If context switching is disabled while a process is executing , and the semaphore is already locked (
s->value == 1), the process will enter thedo-whileloop and spin indefinitely. Since context switching is disabled, the CPU cannot switch to the process holding the lock to let it execute and release it. This leads to a permanent deadlock. Thus, the implementation may not work if context switching is disabled in . This statement is true. - Option B: Normal load/store operations are non-atomic. Using them instead of
fetch-and-setwould lead to race conditions, failing to guarantee mutual exclusion. Thus, this statement is false. - Option C & D: The code correctly implements a binary semaphore using a spin-lock mechanism, and the implementation is correct. Thus, these statements are false.
Free practice · Your answers on this page are not saved.
