cmultithreadingpthreadssleepwind-river-workbench

Sleep() terminates thread in WindRiver


I have to write a little programm in C with WindRiver, which creates three threads:

To kill a thread, I want to wait to make sure it is created, so I found that I could use sleep() to let another thread takes over and let it create itself. But they all die with the sleep.

I came up with this code:

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

#define NUM_THREAD 3

int theRandomNumber = 0;

void *RandomNumber (void *threadid){
    int id = (int) threadid;
    //srand();
    theRandomNumber = rand() % 50; 
    printf("Thread %d: Random: %d \n", id, theRandomNumber);
    pthread_exit(NULL);
    return 0;
}

void *CheckNumber (void *threadid){
  int id = (int) threadid;
  printf("Thread #%d is active and going to sleep now\n", id);
  sleep(1000);
  //here he dies without annoucing anything or something
  printf("Thread #%d is active again and back from sleep\n", id);
  if (id == 1){
      if (theRandomNumber >= 25){
          pthread_cancel(2);
          printf("THREAD %d: Thread #2 is closed \n", id);
      }
  }
  else{
      if (theRandomNumber < 25){
          pthread_cancel(1);
          printf("THREAD %d: Thread #1 is closed \n", id);
      }
  }
  return 0;
}


int main (int argc, char *argv[]){
  pthread_t threads[NUM_THREAD];
  int t = 0;

  printf("in main: create thread #%d \n", t);
  pthread_create (&threads[t], NULL, RandomNumber, (void *) t++);

  printf("in main: create thread #%d \n", t);
  pthread_create (&threads[t], NULL, CheckNumber, (void *) t++);

  printf("in main: create thread #%d \n", t);
  pthread_create (&threads[t], NULL, CheckNumber, (void *) t++);
}

The part with the Randomnumber works fine, I left it out here but I can post it on request.

After a thread reaches the sleep(), it's getting terminated.

Console Log:

in main: create thread #0
in main: create thread #1
in main: create thread #2
Thread #0: Random: 8
Thread #1 is active and going to sleep now
Thread #2 is active and going to sleep now

Nothing happens after sleep. Any ideas?


Solution

  • Leave main() by calling pthread_exit(), to only exit the "main" thread, else ending main() ends the process and with this all its remaining threads.

    Alternatively let main() join all threads via calling pthread_join() on each PThread-id returned by the calls to pthread_create().