使用 pthread_cancel() 时内存泄漏

发布于 2024-11-09 09:23:14 字数 341 浏览 0 评论 0原文

大家好,我有一些关于线程的问题,例如,我有一个线程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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷你仙 2024-11-16 09:23:14

是的,在这种情况下它会泄漏内存。 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 calling pthread_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 to pthread_cancel. You can use a handler function which will free any allocated memory you have outstanding.

留一抹残留的笑 2024-11-16 09:23:14

首先,是否立即取消取决于取消状态。
请检查“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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文