CSE 451
Operating Systems
Spring 1998
Quiz #4 : Solution
The code given doesnot guarantee mutual exclusion. The following sequence
of events can occur, resulting in both the threads entering the critical
section.
-
In the begining both flag[0] and flag[1] are FALSE
-
Thread 0 reads flag[1] and sees it is FALSE
-
Context switch to thread 1
-
Thread 1 reads flag[0] and sees it is FALSE
-
Thread 1 sets flag[1] and enters critical section
-
Context switch to thread 0
-
Thread 0 sets flag[0] and enters critical section
If the two lines in Enter_Critical_Section() are interchanged, then
a deadlock can occur.
-
In the begining both flag[0] and flag[1] are FALSE
-
Thread 0 sets flag[0] to TRUE
-
Context switch to thread 1
-
Thread 1 sets flag[1] to TRUE
-
Thread 1 checks flag[0], sees it is TRUE and waits in the while loop
-
Context switch to thread 0
-
Thread 0 checks flag[1], sees it is TRUE and waits in the while loop
-
Both the threads are waiting in the while loop and no progress can occur.
Extra Credit:
For the case of two threads, the following code guarantees mutual exclusion
and progress. See the text for the proof.
int flag[2]; /* flag array is initialized to FALSE */
int turn = 0;
Enter_Critical_Section(int my_thread_id, int other_thread_id)
{
flag[my_thread_id] = TRUE;
turn = other_thread_id;
while (flag[other_thread_id] == TRUE && turn
== other_thread_id)
/* do nothing, spin wait */;
}
Exit_Critical_Section(int my_thread_id, int other_thread_id)
{
flag[my_thread_id] = FALSE;
}