问题描述
使用pthread_exit()
退出时出现问题.我的代码如下:
I have a problem when use pthread_exit()
to exit .My code is like this:
{
...
pthread_attr_t attr;
iRetValue = pthread_attr_init(&attr);
iRetValue = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
size_t nStackSize = 4 * 1024 * 1024;
iRetValue = pthread_attr_setstacksize(&attr, nStackSize);
while(condition)
{
...
int32 iSockId = cServSocket.accept();
if(iSockId < 0)
{
continue;
}
pthread_t tid;
int32* pSockId = new int(iSockId);
iRetValue = pthread_create(&tid, &attr, run_thread, (void*)pSockId);
...
}
...
pthread_attr_destroy(&attr);
}
void* run_thread(void* p)
{
int32 iSockId = *(int32*)p;
if(p != NULL){delete p}
int32 iRetValue = g_dealMgr.deal_thread(iSockId);
return (void*)iRetValue;
}
int32 CDealMgr::deal_thread(int32 iSocket)
{
... // many temporarydata create,expect will release autoly
pthread_exit((void*)1);
return 0;
}
实际上,这会导致内存泄漏,当我将pthread_exit((void*)1);
移到run_thread
时,就像这样
In fact, it causes memory leaks,and when I move pthread_exit((void*)1);
to run_thread
,like this
void* run_thread(void* p)
{
int32 iSockId = *(int32*)p;
if(p != NULL){delete p}
int32 iRetValue = g_dealMgr.deal_thread(iSockId);
pthread_exit((void*)1);
return (void*)iRetValue;
}
int32 CDealMgr::deal_thread(int32 iSocket)
{
... // many temporary data create,expect will release autoly
return 0;
}
内存泄漏消失了.现在,我的问题是,为什么在函数run_thread()
中使用的pthread_exit()
会导致内存泄漏,希望有人可以帮助我,非常感谢.
memory leaks disappear.Now, my question is, why pthread_exit()
used in the function run_thread()
called will cause memory leaks ,hope someone can help me,thank you very much.
推荐答案
问题是,在C ++中,return
导致堆栈被取消缠绕并且局部变量被破坏.仅保证调用pthread_exit()
会调用在pthread_cancel_push()
中注册的取消处理程序.您需要正常地从deal_thread
返回,以确保在其堆栈上声明的所有变量均已正确销毁.
The problem is that in C++ return
causes the stack to be unwound and local variables to be destroyed. Calling pthread_exit()
is only guaranteed to invoke cancellation handlers registered with pthread_cancel_push()
. You need to return normally from deal_thread
to ensure all variables declared on its stack are properly destroyed.
一旦调用pthread_exit
,线程将停止运行-它不会从deal_thread
返回(甚至不会继续执行).您无需显式调用pthread_exit
,当您从run_thread
返回时也会发生同样的事情.
Once you call pthread_exit
the thread stops running - it does not return from deal_thread
(or even continue executing it). You don't need to call pthread_exit
explicitely, the same thing happens when you return from run_thread
.
此:
void* run_thread(void* p)
{
pthread_exit((void*)1);
}
等效于此:
void* run_thread(void* p)
{
return (void*)1;
}
在implicit call to pthread_exit()
此处中查看有关段落.
还请注意,如果用NULL
调用run_thread
,则可能会导致崩溃.您应该将前两行更改为:
Also note there is the possibility of a crash in run_thread
if you call it with NULL
. You should change the first 2 lines to:
int32 iSockId = 0;
if (p != NULL) {
iSockId = *(int32*)p;
delete p;
}
这篇关于使用pthead_exit()退出线程时内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!