// C++ version of cthreads.c
// Sample code that demonstrates the use of pthread_create and pthread_join.
// Multiple threads print out a sequence of numbers using cout stream.
// Although created in order, execution order will vary.
// Because of increased complexity in using streams, output may get fragmented.
//
// 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 = 10;


// print out a sequence of LOOP_NUM numbers with thread identifying number
void* thread_main(void* arg) {
  int* num = reinterpret_cast<int*>(arg);  // read void * argument as intended

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

  delete num;  // child thread cleans up the memory allocated for its argument
  return nullptr;  // return type is a pointer
}


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++) {
    int* num = new int(i);
    if (pthread_create(&thds[i], nullptr, &thread_main, num) != 0) {
      cerr << "pthread_create failed" << endl;
    }
  }

  // wait for all child threads to finish
  // (children may terminate out of order, but cleans up in order)
  for (int i = 0; i < NUM_THREADS; i++) {
    if (pthread_join(thds[i], nullptr) != 0) {
      cerr << "pthread_join failed" << endl;
    }
  }

  return EXIT_SUCCESS;
}