#include <stdio.h>
#include <pthread.h>

pthread_t th[2];
pthread_mutex_t mutex;

void thread1(void *name)
{
 int i;
 int x;
 for(i=0; i<10; i++)
  {
   printf("Thread : %ld -> locking\n",pthread_self());
 /*Mutex setzen*/
   if(pthread_mutex_lock(&mutex) == 0)
    {
     /*Kritischer Codabschnitt*/
     /*Tu was kritisches*/
     sleep(1);
    }
   else
    {
      printf("locking -> fehlgeschlagen\n");
      exit(0);
    }
 /*Mutex wieder aufheben*/
   if(pthread_mutex_unlock(&mutex) == 0)
     printf("Thread : %ld ->unlock\n",pthread_self());
   else
    {
      printf("Konnte locking von Thread %ld nicht mehr aufheben\n",pthread_self());
      exit(0);
    }
  }
 pthread_exit((void *) 0);
}


void thread2(void *name)
{
 int i;
 for(i=0; i<10; i++)
  {
   printf("Thread : %ld -> locking\n",pthread_self());
 /*Mutex setzen*/
   if(pthread_mutex_lock(&mutex)==0)
    {
     /*Kritischer Codabschnitt*/
     /*Tu was kritisches*/
     sleep(1);
    }
   else
    {
      printf("locking -> fehlgeschlagen\n");
      exit(0);
    }
 /*Mutex wieder aufheben*/
   if(pthread_mutex_unlock(&mutex) == 0)
     printf("Thread : %ld ->unlock\n",pthread_self());
   else
    {
      printf("Konnte locking von Thread %ld nicht mehr aufheben\n",pthread_self());
      exit(0);
    }
   }
 pthread_exit((void *) 0);
}


int main()
{
  pthread_t th[2];
  int i;

  /*einen Mutex erzeugen*/
  pthread_mutex_init(&mutex, NULL);

  if(pthread_create(&th[0], NULL, (void *)&thread1, (void *)NULL) != 0)
    {
      fprintf(stderr, "Fehler beim Erzeugen eines Threads.!?!?!\n");
      exit(0);
    }

  if(pthread_create(&th[1], NULL, (void *)&thread2, (void *)NULL) != 0)
    {
      fprintf(stderr, "Fehler beim Erzeugen eines Threads.!?!?!\n");
      exit(0);
    }

  pthread_join(th[0], NULL);
  pthread_join(th[1], NULL);

  return 0;
}