Do I need to detach pthread to prevent memory leaks?

In my program, I process new threads with

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

The question is pretty simple - if I just let someFunction finish, do I need to call something in C++ , for example. join or anything else, before prevenet memory leaks or is memory freed up automatically?

+4
source share
1 answer

On the opengroup page for pthread_join

The pthread_join () function provides a simple mechanism that allows an application to wait for a thread to complete. After the thread completes, the application can then choose to clear the resources that were used by the thread. For example, after pthread_join () returns, any stack storage can be restored.

The pthread_join () or pthread_detach () function should ultimately be for each thread created with the detachstate attribute set to PTHREAD_CREATE_JOINABLE so that the storage associated with the thread can be restored.

and on the page page pthread_join

Failure to join a thread that connects (that is, one that is not separate) makes a “zombie thread”. Avoid doing this because each zombie puzzle consumes some system resources, and when enough zombie threads accumulate, it will no longer be possible to create new threads (or processes).

There is no analogue to pthreads waitpid (-1, & status, 0), that is, "join any terminated thread".

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

If you are pthread_detach ,

The pthread_detach () function should indicate the implementation that the storage for the thread thread can be restored when this thread ends

If you do not use detach or join a joinable stream, this can lead to a waste of resources

+7
source

Source: https://habr.com/ru/post/1484600/


All Articles