使用 pthread_cancel() 时内存泄漏
大家好,我有一些关于线程的问题,例如,我有一个线程1
,它分配了一些内存,而另一个线程(让我们假设2
)正在杀死线程< code>1 使用 pthread_cancel() 或仅使用 return
它分配的内存和平地发生了什么?如果线程1
没有释放这块内存就会泄漏吗?预先感谢您为
使其更清楚而编辑的
任何答案,因为我知道 pthread_cancel() 会杀死线程,但是当我杀死它时,它的内存发生了什么?在 return
的情况下,如果 1
是主线程,则所有线程都将死亡
hello everyone I have some question about threads if for example I have some thread 1
which allocates some piece of the memory, and anohter thread (let's assume 2
) is killing thread 1
using pthread_cancel() or just using return
what is going on with the peace of memory which it allocated? will be leak if thread 1
didn't free this piece of memory? thanks in advance for any answer
edited
just to make it clearer, as I know pthread_cancel()
kills thread, but what is going on with its memory when I kill it? In case of return
all thread will be dead if 1
is the main thread
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,在这种情况下它会泄漏内存。 C 没有任何垃圾收集——如果你分配内存并且无法释放它,它就会被泄漏,简单明了。
如果您想避免内存泄漏,请不要调用
pthread_cancel
。通过设置一个要求线程退出的标志来使线程正常退出,然后当它们检测到设置了该标志时,它们可以释放内存并通过从线程过程返回或调用 pthread_exit 来杀死自己。或者,您可以通过调用
pthread_cleanup_push
来设置线程清理处理程序,当线程退出或通过调用pthread_cancel
取消时,它将被调用。您可以使用处理程序函数来释放任何未分配的已分配内存。Yes, it will leak memory in that case. C does not have any garbage collection -- if you allocate memory and fail to free it, it will be leaked, plain and simple.
If you want to avoid leaking memory, don't call
pthread_cancel
. Make your threads exit gracefully by setting a flag asking them to exit, and then when they detect that that flag is set, they can free their memory and kill themselves by returning from their thread procedures or by callingpthread_exit
.Alternatively, you can set a thread cleanup handler by calling
pthread_cleanup_push
, which will get called when your thread exits or gets canceled by a call topthread_cancel
. You can use a handler function which will free any allocated memory you have outstanding.首先,是否立即取消取决于取消状态。
请检查“pthread_setcancelstate”和“pthread_setcanceltype”。
另外,取消线程后有一个处理程序也很重要。在处理程序中,必须释放所有资源,例如锁和内存,这与返回类似。所以,是的,如果不实现,则有可能发生泄漏正确的。
我建议在使用方法或函数之前先查看它的实现。
希望这有帮助。
First of all whether it gets cancelled immediately or not depends on cancellation state.
please check "pthread_setcancelstate" and "pthread_setcanceltype".
Also it is important to have a handler after a thread is cancelled.In the handler all the resources must be freed, like locks and memory, it is similar with the return.So, Yes, there is a chance of leak if implementation is not right.
I suggest to look at the implementation of a method or function before using it.
Hope this helps.