// This code is execerpted from www.cse.nau.edu/~mc8/Thread/Hello_World.html
//HWorld_better.C
//Martin Casado
//12/20/98
//
// Another very simple hello world program which utilizes a few
// methods associated with threads, without dealing with multithreading
// be sure to compile with CC HWorld_better.C -lpthread
#include <iostream.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>//for all our possible error message
//simple struct to house our parameters
struct a_struct{

int id;
int sleep_time;

};

//we must define our thread function
void* MyThreadFunc(void *arg);

int main(void){

//our one and only thread
pthread_t aThread;
pthread_attr_t aTtr;//attributes for our thread
a_struct my_struct;//our argument
my_struct.id = 007;//bond, james bond
my_struct.sleep_time = 5;

//can we use threads on this system?
//he asks knowingly, nudge, nudge, wink, wink
if(sysconf(_SC_THREADS)==-1){

cout<<"Threads not supported\n";
exit(0);

}

//initialize our thread's attributes to systems defeults
//NOTE: this is for demonstrations purposes ONLY! it is much
//easier to simply pass a NULL to the pthread_create(..) method
//if you are going to use the systems defaults.
pthread_attr_init(&aTtr);

int error;
if((error=pthread_create(&aThread,&aTtr,MyThreadFunc,(void* )&my_struct))!=0)
{

switch(error){

case EAGAIN: cout<<"EAGAIN\n";break;
case EINVAL: cout<<"EINVAL\n";break;
case ENOMEM: cout<<"ENOMEM\n";break;

}
exit(1);

}
//wait for aThread to exit
pthread_join(aThread,NULL);

cout<<"Main letting you know program is ending\n";
exit(0);

}

//thread routine
void* MyThreadFunc(void* arg){

a_struct *str = (a_struct *)arg;
int answer =0;
cout<<"Hello I am thread: "<<str->id<<" If you answer the question\n";
cout<<"I will sleep for: "<<str->sleep_time<<" seconds\n";
cout<<"If you answer the question correctly I will tell you\n";
cout<<"My real ID\n";
while(answer!=2){

cout<<"What is 1+1?\n";
cin>>answer;
cout<<"Sleeping"<<endl;
sleep(str->sleep_time);

}
cout<<"My real ID is: "<<pthread_self()<<endl;
cout<<"Good Bye!"<<endl;
return NULL;

}

