c++ - 使用 pthead_exit() 退出线程时内存泄漏

标签 c++ memory-leaks pthreads exit

我在使用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()会导致内存泄漏,希望有人能帮助我,非常感谢。

最佳答案

问题在于,在 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;
}

查看有关隐式调用 pthread_exit() 的段落 here .

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

int32 iSockId = 0;
if (p != NULL) {
    iSockId = *(int32*)p;
    delete p;
}

关于c++ - 使用 pthead_exit() 退出线程时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17369442/

相关文章:

c++ - "CoInitialize failed"当一个函数(来自库)包含在 VC++ MFC 项目中时

android.widget.PopupWindow$PopupDecorView 在打开菜单的情况下旋转设备时泄漏

c# - 旋转图像显示“内存不足”异常

c++ - 并发访问大量项目

c++ - 当一个线程 forks() 时其他线程会发生什么?

c++ - 编译 Qt Installer Framework static

c++ - 从 C++ 中不同类的成员函数访问数据

c - 异步信号导致套接字 I/O 问题

c++ - 实现 C++ Win32 启动画面的最快方法

c++ - 将数组修剪为 i 和 j 之间的元素