previous
 next 
CS 3733 Operating Systems Notes: Critical Sections
(change semester)

Critical Section: A section of code which must be executed mutually exclusively in time, such as the modification of a shared variable.
Solutions to the critical section problem must satisfy the following:
Bounded Waiting Definition


Here is an algorithm that does not solve the critical section problem:
Assume that turn is a shared vairable, initialized to 0 or 1.
Process 0:                        Process 1:
---------                         ---------
while(TRUE) {                     while(TRUE) {
   while (turn != 0) ;               while (turn != 1) ;
       critical seciton                  critical section
   turn = 1;                         turn = 0;
       remainder section                 remainder section
}                                 }
Bad Critical Section Problem Solution


Here is a correct solution known as Peterson's solution.
It uses three shared integer variables, turn and flag[2].
Process 0 loop:                   Process 1 loop:
--------------                    --------------
flag[0] = 1;                      flag[1] = 1;
turn = 1;                         turn = 0;
while (flag[1]==1 && turn==1);    while (flag[0]==1 && turn==0);
    critical section                  critical section
flag[0] = 0;                      flag[1] = 0;
    remainder section                 remainder section
Peterson's Solution Mutual Exclusion

will interchange the first two lines of Process 0.
Next Notes

Back to CS 3733 Notes Table of Contents