Memory leaks when using pthead_exit() to exit thread

孤人 提交于 2019-12-07 09:17:25

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.

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.

This:

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

is equivalent to this:

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

Check out the paragraph about implicit call to pthread_exit() here.

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!