ENOMEM无法创建线程的原因? [英] Reason for ENOMEM failure to create threads?

查看:112
本文介绍了ENOMEM无法创建线程的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在主线程中使用 pthread_create() pthread_detach()的应用程序,以后 pthread_exit()在子线程中。

I have an application that is using pthread_create() and pthread_detach() in the main thread and later pthread_exit() in the child thread.

大约54 pthread_create()调用均已与随后的 pthread_detach()配对,然后与 pthread_exit() pthread_create()失败。这是 ENOMEM 故障内存不足。

After around 54 pthread_create() calls that have each been paired with a subsequent pthread_detach() and then pthread_exit() the pthread_create() fails. It is ENOMEM failure "Out of memory".

可能导致 pthread_exit()的原因不会释放旧线程的内存并导致我的应用程序泄漏内存并最终耗尽?

What might cause pthread_exit() to not be freeing up the memory of the old threads and causing my application to leak memory and eventually run out?

这是在Linux上运行的Centos 5 64位但构建为32位的应用程序。

This is running on Linux Centos 5 64 bit but a 32 bit built application.

以下是用于创建调用两个 pthread_create() pthread_detach()

Here is the code to create the thread which calls both pthread_create() and 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);
}


推荐答案

调用 pthread_join pthread_exit 之前,以便线程可以在退出前进行清理。

Call pthread_join before pthread_exit so the thread can cleanup before exiting.

这篇关于ENOMEM无法创建线程的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆