#include <pthread.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int flag[2];
int turn;

void P0()
{
  flag[1] =1;
  while(1)
    {  flag[0] = 1;
       turn = 1;
       while (flag[1]==1 && turn==1)
         {  /*do nothing*/;  }
       printf("A");
       fflush (stdout);
       flag[0] = 0;  /* critical section */
    }
}

void P1()
{
  while (1)
    {  flag[1] = 1;
       turn =0;
       while (flag[0]==1 && turn ==0)
         {  /*do nothing*/;  }
       printf("B");
       fflush (stdout);
       flag[1] = 0;  /* critical section */
    }
}

int  main(void)
{
  flag[0] = 0;
  flag[1] = 0;

  //struct sched_param sparam;
  //int policy;
  //pthread_attr_t attr;

  pthread_t p0thread, p1thread;
  pthread_attr_t *pthread_attr_default = NULL;

  pthread_create(&p0thread, pthread_attr_default,
                 (void*)&P0, NULL);

  pthread_create(&p1thread, pthread_attr_default,
                 (void*)&P1, NULL);

/*
Der hier folgende Codeteil ist nicht notwendig, man kann aber so
das Scheduling der Threads beeinflussen

  pthread_attr_init(&attr);
  pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

  pthread_getschedparam (p1thread, &policy, &sparam);
  sparam.sched_priority = 11;
  policy = SCHED_RR;
  pthread_setschedparam (p0thread, policy, &sparam);

  pthread_getschedparam (p0thread, &policy, &sparam);
  policy = SCHED_RR;
  sparam.sched_priority = 11;
  pthread_setschedparam (p1thread, policy, &sparam);

Ende vom überflüssigen Code
*/

  pthread_join(p1thread, NULL);
  pthread_join(p0thread, NULL);

  exit(0);
}
