【发布时间】:2013-06-28 16:29:11
【问题描述】:
使用pthread_exit()退出时出现问题。我的代码是这样的:
{
...
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时,就像这样
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()会导致内存泄漏,希望有人能帮助我,非常感谢。
【问题讨论】:
-
您需要向我们展示更多...也许
deal_thread在到达pthread_exit之前返回 -
日志显示在pthread_exit之前没有返回,一直到pthread_exit,我可以保证。
-
你是否从父线程完成了thread_join()?
-
@rakib 他正在使用
PTHREAD_CREATE_DETACHED创建线程,所以他不需要加入。
标签: c++ memory-leaks pthreads exit