简体   繁体   English

使用 pthread_cancel() 时 memory 泄漏

[英]leak of the memory while using pthread_cancel()

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?大家好,我对线程有一些疑问,例如,我有一些线程1分配了 memory 的一部分,而另一个线程(假设2 )正在使用 pthread_cancel() 杀死线程1 ,或者只是使用return发生了什么平安memory它配哪个? will be leak if thread 1 didn't free this piece of memory?如果线程1没有释放这块 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?只是为了更清楚,因为我知道pthread_cancel()会杀死线程,但是当我杀死它时它的 memory 发生了什么? In case of return all thread will be dead if 1 is the main threadreturn的情况下,如果1是主线程,则所有线程都将死亡

Yes, it will leak memory in that case.是的,在这种情况下它会泄漏 memory。 C does not have any garbage collection -- if you allocate memory and fail to free it, it will be leaked, plain and simple. C 没有任何垃圾收集 - 如果您分配 memory 并且未能释放它,它将被泄漏,简单明了。

If you want to avoid leaking memory, don't call pthread_cancel .如果您想避免泄漏 memory,请不要调用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 .通过设置一个要求它们退出的标志来使您的线程正常退出,然后当它们检测到该标志已设置时,它们可以释放它们的 memory 并通过从它们的线程过程返回或调用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 .或者,您可以通过调用pthread_cancel pthread_cleanup_push时,将调用该处理程序。 You can use a handler function which will free any allocated memory you have outstanding.您可以使用处理程序 function 来释放您未分配的任何已分配的 memory。

First of all whether it gets cancelled immediately or not depends on cancellation state.首先是否立即取消取决于取消 state。 please check "pthread_setcancelstate" and "pthread_setcanceltype".请检查“pthread_setcancelstate”和“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.同样重要的是在线程被取消后有一个处理程序。在处理程序中必须释放所有资源,如锁和memory,它与返回类似。所以,是的,如果实现不存在泄漏的机会正确的。 I suggest to look at the implementation of a method or function before using it.我建议在使用之前先看一下方法的实现或 function。 Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM