#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5

void *PrintHello(void *threadid) {
  // Χρειαζόμαστε το cast για να πάρουμε την τιμή
  long tid = *((long *)(threadid));
  printf("Hello from thread #%ld!\n", tid);
  pthread_exit(NULL);
}

int main (int argc, char *argv[]) {
  pthread_t threads[NUM_THREADS]; // πίνακας από νήματα
  int rc; 
  long t;
  long thread_ids[NUM_THREADS]; // Πίνακας για την αποφυγή race condition

  for(t=0; t < NUM_THREADS; t++){
    printf("In main: creating thread %ld\n", t);
    
    // Αποθήκευση του t σε ξεχωριστή θέση μνήμης για κάθε νήμα
    thread_ids[t] = t; 
    
    rc = pthread_create(&threads[t], NULL, PrintHello, (void *)&thread_ids[t]);
    
    if (rc){
      printf("ERROR code from pthread_create() is %d\n", rc);
      exit(-1);
    }
  }

  // ΠΑΝΤΑ!!! Αλλιώς τερματίζουν και τα νήματα
  pthread_exit(NULL); 
}
