A detached pthread causes memory leaks

后端 未结 1 1366
无人共我
无人共我 2021-01-18 14:50

There is a known memory leak, when terminating a process with running undetached pthreads. However, detaching the thread doesn\'t seem to be a solution. Consider the followi

相关标签:
1条回答
  • 2021-01-18 15:02

    Returning from main is equivalent to an exit of the whole process, so this is in effect quite a rude way to terminate your detached thread. Your thread simply hasn't terminated when the main function ends, it only does so later when the exit mechanism forces it. So valgrind is missing the release of the resources of the thread.

    The fact that valgrind tells you that there is leaking memory shouldn't worry you by itself, but the fact that your thread is terminated without being able to cleanup and/or finish its task should worry you.

    If you want to have your thread continue execution after your main thread ends, you should terminate main by pthread_exit instead of return. Then it is up to your detached thread to decide when to terminate itself. It could decide so, on receiving the necessary information through a state variable that is set atomically or through a mutex/condition mechanism.

    0 讨论(0)
提交回复
热议问题