#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/*Fehlerbeendigung für alle Threads*/
void checkResults(string, val) {
    if (val) {
      printf("Failed with %d at %s", val, string);
      exit(1);
    }
}

void *theThread(void *parm)
{
  printf("Thread: Anfang\n");
  while (1) {
     printf("Thread: In der Schleife und wartet auf Anfrage\n");
     pthread_testcancel();
     sleep(1);
                   }
  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t thread;
  int rc=0;
  void *status;

  printf("Beginne Test - %s\n", argv[0]);

  printf("Create/startet einen thread\n");
  rc = pthread_create(&thread, NULL, theThread, NULL);
  checkResults("pthread_create()\n", rc);

  printf("Wir warten ein bißchen bis wir unseren Thread wieder beenden\n");
  sleep(3);
  rc = pthread_cancel(thread);
  checkResults("pthread_cancel()\n", rc);

  printf("Wir warten bis unser Thread fertig ist und die Ressourcen freigibt\n");
  rc = pthread_join(thread, &status);
  checkResults("pthread_join()\n", rc);

  printf("Thread zeigt an das er fertig ist\n");
  if (status != PTHREAD_CANCELED) {
           printf("Unexpected thread status\n");
           }

  printf("Main completed\n");
  return 0;
}