Understanding a rudimentary solution to Critical Section Problem

  • Thread starter Thread starter K29
  • Start date Start date
  • Tags Tags
    Section
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
K29
Messages
103
Reaction score
0
(Source: page 20 of this :http://www.ics.uci.edu/~bic/courses/JaverOS/ch2.pdf)

The problem is easily solved if we insist that p1 and p2 enter their critical sections alternately; one common variable, turn, can keep track of whose turn it is. This idea is implemented in our first algorithm below.
Code:
/* CS Algorithm: Try #1 */
int turn = 1;
cobegin
p1: while (1)
{
  while (turn==2) ; /*wait loop*/
  CS1; turn = 2; program1;
 }
//
p2: while (1)
{
  while (turn==1) ; /*wait loop*/
  CS2; turn = 1; program2;
 }
coend

Initially, turn is set to 1, which allows p1 to enter its CS. After exiting, the process sets turn
to 2, which now allows p2 to enter its CS, and so on. Unfortunately, if program1 were much longer than program2 or if p1 halted in program 1, this solution would hardly be satisfactory. One process well outside its critical section can prevent the other from entering its critical section, thus violating the requirement 1 stated above

The part I put in bold looks like nonsense.
Since program1 executes after the Critical Section and after turn gets set to 2, there is nothing stopping p2 from leaving its wait loop and entering its critical section, no matter what happens in program1. Looks like a perfectly fine solution to me.

Am I right? Am I not seeing something?(NOTE: p1 is the thread and program1 is the non-critical part of p1.)
 
Last edited:
Physics news on Phys.org
It looks OK for the most part. Each thread flips the flag immediately after exiting its critical section, thus allowing the other thread to enter its own critical section. As you noted, if either thread failed to flip the flag (i.e., died during its critical section phase) that would deadlock the other thread. So error-handling code in the critical section should ensure that, should the thread crash, the flag is flipped anyway.
 
And I guess it goes without saying that the code within the critical section should be kept as short as possible.