Hi All,
I will be glad if you could help me resolve this problem.
I have created two detachable threads and wanted to them execute independent of the parent thread ( the main task which creates the detachable threads). But I see no output coming from the execution of two detachable threads. When I debugged the application, I found that the parent thread terminates before the newly created threads complete the execution and this causes the child threads to terminate without completing their job. I have no idea what is causing the detachable threads to stop their execution. As far as I know we should be able to execute the detachable threads irrespective of the parent thread status(of course there is nothing like parent child hierarchy in posix lib by default) , please correct me if I am wrong.
Following is the sample code to reproduce the problem.
class Sample
{
public:
Sample()
{ cout <<"Sample:: constructor \n"; }
~Sample()
{ cout <<"Sample :: destructor\n"; }
};
void* ThreadFun(void * data)
{
Sample s1;
cout<<" ThreadFun "<<*((int*)(data))<<"\n";
}
int main()
{
pthread_t tid1,tid2;
pthread_attr_t attr,attr1;
int i=11;
int a =10, b=20;
cout<<" from main \n";
pthread_attr_init(&attr);
pthread_attr_init(&attr1);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
pthread_attr_setdetachstate(&attr1,PTHREAD_CREATE_DETACHED);
int j=pthread_create(&tid1,&attr,&ThreadFun,(void*)&a);
j=pthread_create(&tid2,&attr1,&ThreadFun,(void*)&b);
pthread_attr_destroy(&attr);
pthread_attr_destroy(&attr1);
//sleep(2);
return 0;
}
OUTPUT:
from main
And If I remove the comments at "sleep(2)" , then it works fine. Following is the output with sleep statement.
from main
Sample:: constructor
ThreadFun 10
Sample :: destructor
Sample:: constructor
ThreadFun 20
Sample :: destructor