Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it needed to detach pthread to prevent memory leaks?

In my programme, I handle new threads with

 pthread_t thread;
 pthread_create(&thread, NULL,
            c->someFunction, (void *) fd); //where fd is ID of the thread

The question is quite simple - if I just let the someFunction to finish, is it needed then in C++ to call something e.g. join or anything else, to prevenet memory leaks or is the memory freed automatically??

like image 722
Martin Dvoracek Avatar asked Mar 23 '23 17:03

Martin Dvoracek


1 Answers

From the opengroup page for pthread_join,

The pthread_join() function provides a simple mechanism allowing an application to wait for a thread to terminate. After the thread terminates, the application may then choose to clean up resources that were used by the thread. For instance, after pthread_join() returns, any application-provided stack storage could be reclaimed.

The pthread_join() or pthread_detach() function should eventually be called for every thread that is created with the detachstate attribute set to PTHREAD_CREATE_JOINABLE so that storage associated with the thread may be reclaimed.

and from the man page of pthread_join

Failure to join with a thread that is joinable (i.e., one that is not detached), pro‐ duces a "zombie thread". Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).

There is no pthreads analog of waitpid(-1, &status, 0), that is, "join with any ter‐ minated thread".

If you believe you need this functionality, you probably need to rethink your application design.

If you do pthread_detach,

The pthread_detach() function shall indicate to the implementation that storage for the thread thread can be reclaimed when that thread terminates

If you don't detach or join a joinable thread, it can cause waste of resources

like image 96
Suvarna Pattayil Avatar answered Apr 02 '23 05:04

Suvarna Pattayil