You are not logged in.
Pages: 1
"A thread's underlying storage can be reclaimed immediately on termination if that thread has been detached",can you tell me what is the meaning of this sentence ,and what is the thread detached?
and how we can detach a thread?
thanks ,best wishes
Offline
Offline
If you DO NOT care about WHY you thread is exiting, then perform a detach operation...
If you DO care about WHY you thread is exiting, the either do NOT detach and perform a join operation... OR detach BUT make certain that there is a global repository for thread results and that every thread calls it ( and deposits their result ) prior to exiting...
Of course - tis just my opinion...
Michael
"The only difference between me and a madman is that I'm not mad."
Salvador Dali (1904-1989)
Offline
Hello
I am going to open an old discussion, but i think this is an important information.
1) Is there any differences about the structures allocated by the kernel between a detached thread or a non-detached thread
2) Are the data structures of a non-detached thread deallocated automatically after the thread termination, or you have to call pthread_join()?
Offline
1. No, it only influences thread exit behaviour.
2. An exited, but not joined thread is comparable to a zombie process. So
although most resources are gone, you still need to call pthread_join.
If you can't always join a thread then make it detached, except if the
whole program exits, in which case it doesn't matter. Not doing a join
is just messy.
Of course there are exceptions, e.g. if it only happens a limited amount
of times in rare circumstances, when it's not worth worrying about it and
when doing it the "proper" just complicates the code.
Offline
Let's take a look at the different scenarios:
Normal threads' resources are freed
- after the thread has exited and the main thread called pthread_join
- in case the main thread exits
Detached thread's resources are freed
- right after it exits/is finished
- in case the main thread exits
So, no matter what you do, if the main thread exits, it takes all its child threads with it.
What is a normal thread good for....
Your main thread on a 4 core computer has to do N independent calculations and needs all of the results before it can continue. So it starts N threads and then waits in a join loop until all N results are ready. This way it can use all available cores and the program logic needing all of the results will not be broken.
What is a detached thread good for...
You have a simple http server and use a thread for every incoming connection. The thread that's created is detached as the main thread doesn't need to know anything after the child thread is created successfully.
Those examples are simplified of course, but you should get the drift...
Offline
Thank you Loco for your clear explanation
Pages: 1