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

查看:54
本文介绍了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_exit 之前调用 pthread_join 以便线程可以在退出前进行清理.

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

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

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