gpt4 book ai didi

c++ - 堆栈变量的 pthread 内存泄漏

转载 作者:行者123 更新时间:2023-11-30 03:58:55 24 4
gpt4 key购买 nike

我注意到当我使用表单中的线程调用方法时

////main code/////
pthread_t thread;
pthread_create(thread,function,data);
//////////////////

void* function(void* data){

//work with some data on the heap via a vector on the stack

std::vector<double> variable (100,1.2345);

//do contents of thread

pthread_exit(NULL);
}

尽管没有调用 new( vector 变量中的隐式调用除外),但我遇到了内存泄漏,内存使用量与我调用 function 的次数呈线性关系> 这样。

但是如果我这样做

void* function(void* data){

{
std::vector<double> variable (100,1.2345);

//do contents of thread
}

pthread_exit(NULL);
}

没有发生内存泄漏。

似乎 pthread_exit(NULL) 没有像您在使用 return 的普通函数结束时那样清除堆栈变量(我对此是正确的对吧?!)所以将它们放在自己的范围内可以确保它们得到释放。

然而,这似乎是一场大乱斗。如何确保在退出 pthread 时正确清除堆栈变量(以及它们在容器中的堆内容)?

最佳答案

It seems that pthread_exit(NULL) doesn't clear the stack variables like you would get at the end of a normal function with return (I am correct about that right?!)

这就像调用 exit(0)在非线程代码中,程序会立即退出并且不会展开堆栈。 (由于 pthreads 规范是根据 C 而不是 C++ 定义的,因此它没有定义 C++ 析构函数会发生什么,因此它是特定于平台的)。

so putting them within their own scope ensures they get freed.

因为这样 vector 的析构函数会在您调用 pthread_exit() 之前运行.

How do I ensure the stack variables (and their contents on the heap in terms of containers) are cleared properly when exiting a pthread?

从线程函数返回即可,不需要使用pthread_exit退出线程启动函数(传递给 pthread_create 的函数)。 POSIX说:

An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it.

GNU/Linux man page说同样的话略有不同:

Performing a return from the start function of any thread other than the main thread results in an implicit call to pthread_exit(), using the function's return value as the thread's exit status.

您可以使用 pthread_exit从堆栈下方的其他函数退出线程,就像您可以使用 exit() 一样退出程序而不是从 main() 返回, 但在最外层的功能只是 return NULL; (或您想要的任何返回值)。

唯一一次使用pthread_exit(x)对简单的 return x; 有所不同在main它将导致程序等待直到其他线程完成。

关于c++ - 堆栈变量的 pthread 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27169991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com