I'm applying the peterson solution for protecting memory of the critcal section.

Each child process should contain a local variable that keeps track of the number of times it interrupts the other child while it is in its critical section. The process should display this value before terminating.

I'm having trouble counting the number of interrupts for these 2 child procsses. When i run the whole program it prints out 0 which I can expect to happen sometimes but not all the time. I figured I could use flag or turn to clarify if a child process is waiting to enter the critical section. Any help is greatly appreciated.

/*----------------------------------------------------------------------*
 * This function increases the value of shared variable "total"
 *  by one all the way to 100000
 *----------------------------------------------------------------------*/

void process1 ()
{
  int k = 0;
  int numInt = 0;

  while (k < 100000)
    {
      flag[0] = TRUE;
      turn = 1;

      while(flag[1] && turn == 1);

      if(turn == 0)
        numInt++;
      total->value = total->value + 1;


      flag[0] = FALSE;
      k++;
    }
  printf ("From process1 total = %d\n", total->value);
  printf("Process2 interrupted %d times in critical section by Process 1.\n", numInt);
}

/*----------------------------------------------------------------------*
 * This function increases the vlaue of shared memory variable "total"
 *  by one all the way to 100000
 *----------------------------------------------------------------------*/

void process2 ()
{
  int k = 0;
  int numInt = 0;

  while (k < 100000)
    {
     flag[1] = TRUE;
     turn = 0;

     while(flag[0] && turn == 0);


     if(turn == 1)
        numInt++;
     total->value = total->value + 1;


    flag[1] = FALSE;
    k++;
    }

  printf ("From process2 total = %d\n", total->value);
  printf("Process1 interrupted %d times in critical section by Process 2.\n", numInt);

}

The whole purpose of critical sections is to block out other threads while inside the code bounded by critical section. If other threads were allowed in then the critical section concept would be useless. Critical sections are pieces of code that are shared among threads -- I see no such thing in the code you posted.

What you are looking for is implementation of a mutex. Mutex's, not critical sections, are used to synchronize access to a single object among two or more threads. main() should create the mutex and each thread access it. If you are compiling for MS-Windows then you need to call the win32 api CreateMutex()

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.