Reputation: 1017
There have been questions asked before on this topic , but still I'm not very clear with the usage of pthread_join().
I read somewhere that resources are not cleaned up when a thread exists without getting joined with the main thread . What are the resources we are talking about? If these resources are present in the stack of the calling thread , wont they be cleared up when the calling thread exists? So I think pthread_join() helps clean up the resources which are present in the heap ? Also what is the advantage of using pthread_exit()?
Upvotes: 0
Views: 133
Reputation: 16726
A thread terminates when it thread function returns. If your thread function calls other helper functions you might have a call stack like thread function -> helper1 -> helper2 -> helper3. When helper3 now comes to the conclusion that the thread shall terminate, you can return on each function and let each caller detect the necessity to terminate. Or helper3 can just call pthread_exit
.
Threads are not only the code they execute but also some OS management information like a handle, the priority, the return value and so on. This information has to be kept in memory until the last reference to the thread is deleted. pthread_join
will free this reference so the OS can free up threads.
On Linux terminated threads/processes are put into a "zombie state" where they are just waiting to be closed.
Upvotes: 1