问题描述
我有以下情形,在C实现与pthreads的:
I have following scenario, in C implementation with pthreads :
在主线程(T1)创建另一个线程(T2),它等待的事件。
The main thread(T1) creates another thread(T2) which waits for an event.
在事件T2调用树遍历 recusive 的函数,它接受一个函数指针的动作被树节点上执行。在树的遍历,如果节点找到了FN指针被解雇,创建一个线程(T3),服务节点,应该是正常消亡。
On an event T2 calls a Tree Traversal recusive function that takes in a function pointer for an action to be executed on a Tree node. During Tree traversal, if the node is found the fn pointer is fired that creates a thread (T3), services the node and is supposed to normally die out.
我观察到来自T3的堆栈一个巨大的内存泄漏。在Valgrind的告诉我,
I am observing a huge memory leak that comes from the T3's stack. The Valgrind tells me that
==9251== 2,720 bytes in 20 blocks are possibly lost in loss record 142 of 157
==9251== at 0x402425F: calloc (vg_replace_malloc.c:467)
==9251== by 0x4010CDB: _dl_allocate_tls (dl-tls.c:300)
==9251== by 0x403A2E2: pthread_create@@GLIBC_2.1 (allocatestack.c:561)
==9251== by 0x80571CC: serviceNode (NodeHndlr.c:432)
==9251== by 0x804AD88: preOrderTpTraversal (treefunct.c:503)
==9251== by 0x804AE01: preOrderTpTraversal (treefunct.c:513)
==9251== by 0x804AE01: preOrderTpTraversal (treefunct.c:513)
==9251== by 0x804AE01: preOrderTpTraversal (treefunct.c:513)
==9251== by 0x8057450: serviceproc (NodeHndlr.c:519)
==9251== by 0x403996D: start_thread (pthread_create.c:300)
==9251== by 0x411AA4D: clone (clone.S:130)
下面的 serviceproc
是T2 serviceNode
为节点的函数指针。
Here the serviceproc
is the T2serviceNode
is the function pointer for the Node.
因此最终的系统运行的VM,并创建线程失败,错误code = 11(没有足够的资源)
Thus eventually the system runs out of vm and the thread creation fails with errorcode=11 (not enough resources)
我的问题是,一旦在T3的正常退出,不应该在线程的堆栈被垃圾自动收集或(由 serviceNode
创建)我失去了一些东西在这里。 ?
My question is that once the the T3 (created by serviceNode
) exits normally , shouldn't the thread stack be garbage collected automatically or am i missing something here. ?
编辑:或问题,由于与创建函数指针的射击?
or is the issue created with due to firing of the function pointer ?
推荐答案
对于大多数pthreads的实现,你会泄露一些内存,当一个线程退出除非您:
With most pthreads implementations, you will leak some memory when a thread exits unless you either:
-
呼叫在pthread_join()该线程
Call pthread_join() that thread
或
创建线程作为分离线程,通过调用pthread_detach()或作为属性pthread_create的
Create the thread as a detached thread, by calling pthread_detach() or as an attribute to pthread_create
请确保你做上述之一。
这篇关于线程堆栈泄漏通过递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!