1st question: Linux / windows?
if you are working in Windows, I am sure there will be similar method call like pthreads.
Following examples are given using pthread.
Answer of Q 1) You can create a thread from the constructor but why do you want to create a thread from constructor, its not a good practice.
Its funny that i just replied someone with his thread question, here is the sample code which i written for him, it may be helpful for you too.
/*
* thread.h
*
* Created on: Nov 8, 2010
*/
#ifndef THREAD_H_
#define THREAD_H_
#include <pthread.h>
class PThread{
pthread_t thread_id;
public:
PThread(){
pthread_create( &thread_id, NULL, EntryPoint, (void *)this);
}
void Start(){
//pthread_create( &thread_id, NULL, EntryPoint, (void *)this);
}
static void *EntryPoint(void *thread){
PThread *self = static_cast<PThread *>(thread);
self->Run();
}
virtual void Run() = 0; //It is a virtual method, have fun!!
};
class JobSchedular: public PThread{
virtual void Run(){
for(int i = 1; i <= 10; i++){
cout << "scheduling job" << endl;
sleep(1);
}
}
};
#endif /* THREAD_H_ */ JobSchedular th1;
// th1.Start(); YOUR case constructor starts it, but not a good practice!!
Answer of Q 2) Yes ofcourse
//look i have called Run method
self->Run();
Answer of Q 3) As long as your Run method is running :) your thread will run, but if your process terminate, your thread will terminate too.
there is a method in Pthread, pthread_join which you can use/call from main, if you call this method, then calling point will wait unless this thread has finished and joined.
pthread_join( thread_id, NULL);