我有一个应用程序在主线程中使用pthread_create()
和,稍后在子线程中使用。pthread_detach()
pthread_exit()
经过大约 54 个pthread_create()
呼叫,每个呼叫都与后续呼叫配对,然后pthread_detach()
失败。这是失败的“内存不足”。pthread_exit()
pthread_create()
ENOMEM
什么可能导致pthread_exit()
无法释放旧线程的内存并导致我的应用程序泄漏内存并最终耗尽?
这是在 Linux Centos 5 64 位但 32 位构建的应用程序上运行的。
这是创建同时调用pthread_create()
和的线程的代码pthread_detach()
。
int
_createThread()
{
pthread_attr_t attr;
int return_val;
return_val = setupMutex(_Mtx());
if (return_val != 0) {
return return_val;
}
return_val = setupCond(_StartCond());
if (return_val != 0) {
return return_val;
}
return_val = setupCond(_EndCond());
if (return_val != 0) {
return return_val;
}
return_val = pthread_attr_init(&attr);
if (return_val != 0) {
return -1;
}
size_t stackSize = 1024 * 1024 * 64; // Our default stack size 64MB.
return_val = pthread_attr_setstacksize(&attr, stackSize);
if (return_val != 0) {
return -1;
}
int tries = 0;
retry:
// _initialize() gets called by the thread once it is created.
return_val = pthread_create(&_threadId, &attr,
(void *(*)(void *))_initialize,
(void *)this);
if (return_val != 0) {
if (return_val == EAGAIN) {
if (++tries < 10) {
Exit::deferredWarning(Exit::eagainThread);
goto retry;
}
}
return -1;
}
return_val = pthread_attr_destroy(&attr);
if (return_val != 0) {
return -1;
}
return_val = pthread_detach(_threadId);
if (return_val != 0) {
return -1;
}
// Wait for the new thread to finish starting up.
return_val = waitOnCond(_Mtx(), _EndCond(), &_endCount, 10 /* timeout */, 0,
"_createThread-end");
if (return_val != 0) {
return -1;
}
return 0;
}
void
_exitThread()
{
(void) releaseCond(_Mtx(), _EndCond(), &_endCount, "_exitThread-end");
pthread_exit(NULL);
}