views:

273

answers:

1

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.

+6  A: 

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.

Joe M
you can also create the thread with the PTHREAD_CREATE_DETACHED attribute by using pthread_attr_setdetachstate
Hasturkun
I thought there was such a parameter, but I couldn't remember what it was called. Thanks for refreshing my memory!
Joe M