Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to pthread_join each thread I create?

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.

like image 603
jackhab Avatar asked Jun 30 '09 16:06

jackhab


People also ask

What happens if you don't use pthread_join?

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.

Does pthread_join destroy thread?

pthread_join() does not kill the thread but waits for the thread to complete.

Does pthread_join block other threads?

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.

Can pthread_join be called on the main thread?

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.


1 Answers

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.

like image 192
Joe M Avatar answered Sep 21 '22 16:09

Joe M