Reputation: 22006
I have written this code:
void* th (void* arg)
{
sleep(1);
for(int i=0; i<1000;i++)
{
fprintf(stderr,"%d\t",i);
}
pthread_exit(NULL);
}
int main(int argc, char** argv)
{
pthread_t thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
pthread_create(&thread,&attr,th,NULL);
pthread_attr_destroy(&attr);
return 0;
}
The detach state should make the thread not joinable, so it should run even after the main process is terminated.But it doesn't print the numbers, all I see is that the thread terminated without printing anything to stderr.
Why isn't the detached thread executed?
Upvotes: 0
Views: 195
Reputation: 78973
A return
from the main
thread is equivalent to an exit
of the whole process, so your process will exit before your thread may even print anything. Use pthread_exit
instead to terminate that thread.
Upvotes: 6