// Demonstrates how all threads share an address space
// 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...

#define _GNU_SOURCE
#include <unistd.h>
#include <sys/types.h> // necessary for tid
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREADS 50
#define LOOP_NUM 100

int sum_total = 0;

void *loop_incr(void *arg) {
  for (int i = 0; i < LOOP_NUM; i++) {
    sum_total++;
  }
  printf("Thread ID: %d with sum total of %d.\n", gettid(), sum_total); 
  return NULL;
}


int main(int argc, char** argv) {
  pthread_t thds[NUM_THREADS];  // array of thread ids

  // create threads to run thread_main()
  for (int i = 0; i < NUM_THREADS; i++) {
    if (pthread_create(&thds[i], NULL, &loop_incr, NULL) != 0) {
      fprintf(stderr, "pthread_create failed\n");
    }
  }

  // wait for all non-main threads to finish
  for (int i = 0; i < NUM_THREADS; i++) {
    if (pthread_join(thds[i], NULL) != 0) {
      fprintf(stderr, "pthread_join failed\n");
    }
  }

  printf("The ultimate sum total is %d\n", sum_total);
  return EXIT_SUCCESS;
}
