我注意到当我使用表单中的线程调用方法时
////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时,如何确保正确清除堆栈变量(及其在容器中的内容,以容器为单位)?
最佳答案
这就像在非线程代码中调用exit(0)
一样,该程序立即退出并且不会展开堆栈。 (由于pthreads规范是用C而不是C++定义的,因此它没有定义C++析构函数会发生什么,因此它是特定于平台的)。
因为这样, vector 的析构函数会在调用pthread_exit()
之前运行。
只需从线程函数返回,就无需使用pthread_exit
退出线程启动函数(传递给pthread_create
的函数)。 POSIX说:
而GNU/Linux man page表示相同的内容略有不同:
您可以使用pthread_exit
将线程从堆栈中的其他函数退出,就像您可以使用exit()
退出程序而不是从main()
返回一样,但是在最外层的函数中,只有return NULL;
(或所需的任何返回值)。
唯一使用ojit_code与pthread_exit(x)
有所不同的地方是return x;
,它会导致程序等待直到其他线程完成。
关于c++ - 带堆栈变量的pthread内存泄漏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27169991/