// Remember to compile with -pthread

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

#define NUM_THREADS 4
#define LOOP_NUM 500

void *thread_main(void *arg) {
  int *num = (int*)arg;

  for (int i = 0; i < LOOP_NUM; i++) {
    printf("[cthread: %d] %d\n", *num, i);
  }

  free(num);
  return NULL;
}

int main(int argc, char** argv) {
  pthread_t thds[NUM_THREADS];

  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");
    }
  }

  for (int i = 0; i < NUM_THREADS; i++) {
    if (pthread_join(thds[i], NULL) != 0) {
      fprintf(stderr, "pthread_join failed\n");
    }
  }

  return 0;
}