// Remember to compile with -pthread

#include <pthread.h>
#include <iostream>

using std::cout;
using std::cerr;
using std::endl;

const int NUM_THREADS = 4;
const int LOOP_NUM = 500;

void *thread_main(void *arg) {
  int *num = reinterpret_cast<int*>(arg);

  for (int i = 0; i < LOOP_NUM; i++) {
    cout << "[cthread: " << *num << "] " << i << endl;
  }

  delete num;
  return NULL;
}

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

  for (int i = 0; i < NUM_THREADS; i++) {
    int *num = new int(i);
    if (pthread_create(&thds[i], NULL, &thread_main, num) != 0) {
      cerr << "pthread_create failed" << endl;
    }
  }

  for (int i = 0; i < NUM_THREADS; i++) {
    if (pthread_join(thds[i], NULL) != 0) {
      cerr << "pthread_join failed" << endl;
    }
  }

  return 0;
}