1

使用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;
}

内存泄漏消失。现在,我的问题是,为什么pthread_exit()在调用的函数中使用run_thread()会导致内存泄漏,希望有人能帮助我,非常感谢。

4

1 回答 1

1

问题是在 C++ 中return导致堆栈被展开并且局部变量被破坏。调用pthread_exit()只保证调用注册的取消处理程序pthread_cancel_push()。您需要从正常返回deal_thread以确保在其堆栈上声明的所有变量都被正确销毁。

一旦你调用pthread_exit线程停止运行 - 它不会从deal_thread(甚至继续执行它)返回。您不需要pthread_exit显式调用,当您从run_thread.

这个:

void* run_thread(void* p)
{
    pthread_exit((void*)1);
}

相当于:

void* run_thread(void* p)
{
    return (void*)1;
}

查看有关implicit call to pthread_exit() 此处的段落。

run_thread另请注意,如果您使用 调用它,可能会发生崩溃NULL。您应该将前 2 行更改为:

int32 iSockId = 0;
if (p != NULL) {
    iSockId = *(int32*)p;
    delete p;
}
于 2013-06-28T16:38:17.870 回答