Many modern computer systems provide special hardware instructions that allow us
ID: 3573450 • Letter: M
Question
Many modern computer systems provide special hardware instructions that allow us either to test and modify the content of a word or to swap the contents of two words atomically. The following shows the hardware instruction compare_and_swap()and to use it in a code to solve a critical section problem. int compare_and_swap(int *value, int expected, int new_value) { int temp = *value; if (*value == expected) *value = new_value; return temp; } int lock = 0; int main(){ ... while (compare_and_swap(&lock, 1, 0) != 0) /* Line P */ ; /* do nothing */ /* critical section */ lock = 0; /* remainder section */ } But the above code fails to solve the critical section problem properly. Explain how it fails by showing a scenario step by step
Explanation / Answer
int compare_and_swap(int *value, int expected, int new_value)
{
int temp = *value;
if (*value == expected)
*value = new_value;
return temp;
}
int lock = 0;
int main()
{
while (compare_and_swap(&lock, 1, 0) != 0)
/* Line P */ ;
/* do nothing */
/* critical section */
lock = 0;
/* remainder section */
}
code analysis:
step 1:
lock = 0
int compare_and_swap(int *value, int expected, int new_value)
{
int temp = *value;//temp = 0
if (*value == expected) //*value != 1
*value = new_value; //swap didn't happen
return temp; //return 0
}
now 0 ! =0 results in false in while loop.
this code spins endlessly in the while loop probably the correct implementation would be
do { while (compare_and_swap(&lock, 0, 1) != 0)
; /* do nothing */
/* critical section */
lock = 0;
/* remainder section */
} while (true);
int compare and swap(int *value, int expected, int new_value) {
int temp = *value;
if (*value == expected)
*value = new_value;
return temp;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.