CSE 451

Operating Systems

Spring 1998


Quiz #4

Distributed :  4/28/98 (Tuesday)
Due            :  4/30/98 (Thursday -- in the beginning of the Section)

Consider the problem of synchronizing two threads which access a common resource. We need to construct a critical section which could be entered by only one thread at a time.  The two threads have ids 0 and 1.

Consider the following code which implements this:

int  flag[2];  /* flag array is initialized to FALSE */

Enter_Critical_Section(int my_thread_id, int other_thread_id)
{
     while (flag[other_thread_id] == TRUE) /* do nothing, spin wait */;
     flag[my_thread_id] = TRUE;
}

Exit_Critical_Section(int my_thread_id, int other_thread_id)
{
     flag[my_thread_id] = FALSE;
}

Each thread will access the resource with code like the following ...
Thread 0:

while (TRUE) {
    Enter_Critical_Section(0, 1);
    .... Use the resource .....
    Exit_Critical_Section(0, 1);
    ..... Do something else .....
}
 

Question:

What is wrong with the above code ?
If we interchange the two lines in Enter_Critical_Section(), does it solve the problem ? Why ?

Extra Credit:
Can you come up with an implementation of the above functions, such that they implement critical sections satisfactorily.
You should not use any special machine instructions etc. Assume that the operations, reading a word, writing a word etc. are atomic. But exchanging contents of two memory locations, or read and modifying a memory location etc. are not atomic. Also, try only for the case of two threads.
 
Note: Please be precise and to the point. I don't expect answers more than a few sentences.