// Demonstrates basic use of pthread_create and pthread_join.
// Spawns multiple threads, each printing a short sequence of numbers.
// Threads are launched in order, but their execution interleaves
// unpredictably due to scheduling.
//
// Compile with: clang-15 -pthread <file>.c -o <program>
// don't forget the -pthread...
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREADS 4
#define LOOP_NUM 10


// Each thread prints LOOP_NUM numbers, tagged with its thread index.
void* thread_main(void* arg) {
  int* num = (int*) arg;  // cast void* argument to int*

  for (int i = 0; i < LOOP_NUM; i++) {
    printf("%*s[thread %d] %d\n", *num * 2, "", *num, i);
    // adding indenting based on i to make it pop (easier to see interleaving)
  }

  free(num);        // free dynamically allocated argument
  return NULL;      // pthreads require a void* return
}


int main(int argc, char** argv) {
  pthread_t thds[NUM_THREADS];  // array to store thread IDs

  // Create NUM_THREADS threads, each running thread_main()
  for (int i = 0; i < NUM_THREADS; i++) {
    int* num = (int*) malloc(sizeof(int));
    *num = i;
    if (pthread_create(&thds[i], NULL, &thread_main, num) != 0) {
      fprintf(stderr, "pthread_create failed\n");
    }
  }

  // Wait for all threads to complete.
  // Note: threads may finish in any order, but joins occur in order of creationn.
  for (int i = 0; i < NUM_THREADS; i++) {
    if (pthread_join(thds[i], NULL) != 0) {
      fprintf(stderr, "pthread_join failed\n");
    }
  }

  return EXIT_SUCCESS;
}
