From pthread_join()
man page :
When a joinable
thread terminates, its memory resources (thread descriptor and stack
) are not deallocated until thread performs pthread_join
on it. Therefore, pthread_join
must be called once for each joinable
thread created to avoid memory leaks.
Does it mean i need to join each thread i create to prevent leaks? But joining blocks the caller.
Please, explain more.
If you want to be sure that your thread have actually finished, you want to call pthread_join . If you don't, then terminating your program will terminate all the unfinished thread abruptly. That said, your main can wait a sufficiently long time until it exits.
pthread_join() does not kill the thread but waits for the thread to complete.
The pthread_join subroutine blocks the calling thread until the thread thread terminates. The target thread's termination status is returned in the status parameter.
Assuming the main thread is joinable, there's no problem if main calls pthread_exit before start calls pthread_join . The semantics of a joinable thread are like those of a pid for a child process.
You don't need to join a thread, but it is a good idea. Without calling pthread_join(), there is a possibility that the main() function will return before the thread terminates. In this case, pthread_join() makes the application wait until the other thread finishes processing. Plus, when you join the thread, it gives you the opportunity to check for return values and make sure that everything went smoothly, and it gives you the opportunity to clean up any resources you may have shared with the thread.
EDIT: A function that may be of interest to you is pthread_detach(). pthread_detach() allows the thread's storage to be cleaned up after the thread terminates, so there is no need to join the thread afterwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With