简体   繁体   English

在iOS上执行pthread_cancel时会释放堆中的内存吗?

[英]Will the memory in the heap be released when I do pthread_cancel on iOS?

Lets say I have allocated some memory in my background thread, that is, a thread stack is holding a pointer to that memory. 可以说我在后台线程中分配了一些内存,也就是说,线程堆栈持有指向该内存的指针。 Now I want do terminate background thread execution by calling pthread_cancel on it. 现在,我想通过调用pthread_cancel终止后台线程执行。 Will that memory be released or not? 记忆会被释放吗? (My platform is iOS, compiler is gcc 4.2) (我的平台是iOS,编译器是gcc 4.2)

Each thread by necessity requires its own stack; 每个线程必然需要自己的堆栈; however there is typically only one heap per process. 但是,通常每个进程只有一个堆。 When a thread is destroyed, there is no automatic mechanism to free the memory allocated on the heap. 销毁线程时,没有自动机制释放堆上分配的内存。 All you end up with is a memory leak. 您最终遇到的就是内存泄漏。

As a general rule, avoid using pthread_cancel since it is hard to ensure that pthread_cancel will run safely. 通常,请避免使用pthread_cancel因为很难确保pthread_cancel可以安全运行。 Rather build in some mechanism where you can pass a message to the thread to destroy itself (after freeing any resources that it owns). 而是建立某种机制,您可以在其中释放一条消息给线程以破坏自身(在释放其拥有的任何资源之后)。

The thread stack will be removed once the thread exits. 线程退出后,线程堆栈将被删除。 But there will be no process or code that will look into your thread stack and release any references for the objects that you've allocated on the heap. 但是,不会有任何进程或代码会查看您的线程堆栈并释放您在堆上分配的对象的任何引用。 Also, typically, thread stacks don't hold any references to the memory, the thread stack is an independent space that is given to the thread to use for generic program stack, any reference will only be on the stack for as long as you are inside the function that pushed such a reference onto the stack, typically because you are referencing it with a local variable. 同样,通常,线程堆栈不保存对内存的任何引用,线程堆栈是为线程分配的一个独立空间,供通用程序堆栈使用,只要您在内存中,任何引用都将在堆栈上在将此类引用推入堆栈的函数内部,通常是因为您使用局部变量对其进行了引用。

by default, no -- see other answers, which are more specific to the answer you seek. 默认情况下,否-请参阅其他答案,这些答案更特定于您要寻找的答案。 there is however, such a thing as a thread-specific allocator; 但是,有一个特定于线程的分配器; if you were using one, you'd know. 如果您使用的是一个,就会知道。

No, it won't be deleted or freed automatically. 不,它不会被自动删除或释放。 If you're very lucky, it might be garbage collected sometime if you're running a collector. 如果您很幸运,那么在运行收集器时可能会在某个时间收集垃圾。 File handles, shared memory ids, mutexes etc. won't be released/deallocated either. 文件句柄,共享内存ID,互斥对象等也不会被释放/释放。 Async cancellation is safe for eg pure maths calculations on data still owned by another thread, but very risky in general - that's why some threading APIs have experimented with and removed the function completely. 异步取消对于例如仍由另一个线程拥有的数据进行纯数学计算是安全的,但是总体上来说非常冒险-这就是为什么某些线程API已经尝试并完全删除了该函数的原因。

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

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