// Compile with g++ -pthread in LDFLAGS

#include "libscl.h"
#include <pthread.h>   // Header for pthread
#include <unistd.h>    // Header for sysconf

namespace {

  struct arg_type {
    INTEGER threadid;
    const char* message;
  };

  void* write_arg(void* arg_ptr)
  {
    arg_type* arg = (arg_type*)(arg_ptr); 
    std::cout << arg->message << arg->threadid << std::endl;
    pthread_exit(NULL);
  }
}

int main(int argc, char** argp, char** envp)
{

  #if defined _SC_NPROCESSORS_ONLN
    INTEGER num_threads = sysconf(_SC_NPROCESSORS_ONLN);
  #else
    INTEGER num_threads = 2;
    std::cerr << "The variable _SC_NPROCESSORS_ONLN is not defined, using "
              << num_threads << " threads instead\n";
  #endif

  pthread_t threads[num_threads];
  arg_type  args[num_threads];
  int rc, t;
  for(t=0; t<num_threads; t++){
     std::cout << "Creating thread " << t << std::endl;
     args[t].threadid = t;
     args[t].message = "Hello from thread number ";
     rc = pthread_create(&threads[t], NULL, write_arg, (void*)(&args[t]));
     if (rc){
        char msg[256]; 
        sprintf(msg,"Error, return code from pthread_create() is %d",rc);
        scl::error(msg);
     }
  }
  sleep(5);
  pthread_exit(NULL);
}


