简体   繁体   English

退出pthread发布malloced内存?

[英]Does exiting from a pthread release malloced memory?

Let's say I have started new thread with pthread_create() and then detached it using pthread_detach() . 假设我已经使用pthread_create()启动了新线程,然后使用pthread_detach()将其分离。 Now, from within the thread context, I allocated some memory using malloc() . 现在, 线程上下文中,我使用malloc()分配了一些内存。

When the thread exits, will the malloc'ed memory be freed automatically? 当线程退出时, malloc'ed内存是否会自动释放?

  • Threads share memory resources (at least POSIX). 线程共享内存资源(至少POSIX)。
  • malloc() / realloc() / free() memory management is not actually aware about threads (at least by now). malloc()/ realloc()/ free()内存管理实际上并不了解线程(至少到现在为止)。
  • So you should treat results of malloc() as simple 'resource'. 因此,您应该将malloc()的结果视为简单的“资源”。 It is not thread-linked. 它不是线程链接的。

So now answer should be obvious, any memory allocated has no linkage to threads so it is not free()'d on thread exit. 所以现在回答应该是显而易见的,任何分配的内存都没有与线程的链接,因此在线程退出时它不是free()。 Of course you can provide some special handling mechanics but it is not done automatically. 当然,您可以提供一些特殊的处理机制,但它不是自动完成的。

Good side of this is you can pass memory allocation between threads in other words allocate such resource in one thread and then free from another (is it good for you or not). 好的一面是你可以在线程之间传递内存分配,换句话说,在一个线程中分配这样的资源,然后从另一个线程中释放(对你有好处)。

Hope this would be useful explanation, think about allocated memory pointer as about any process-level descriptor. 希望这将是有用的解释,考虑分配的内存指针作为任何进程级描述符。

不 - malloc的记忆只能被明确的“免费”释放。

Thats pretty much the difference between threads and processes, processes own their resources like heap memory threads don't. 这几乎就是线程和进程之间的区别,进程拥有自己的资源,就像堆内存线程那样。 If you want that functionality then you want a process not a thread. 如果您需要该功能,那么您需要一个进程而不是一个线程。

我很确定它没有,你必须使用free()。

不会。当进程退出时释放任何malloced内存,但是当线程退出时也是如此。

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

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