NPTL最大线程为65528?

rek*_*mso 5 c linux multithreading pthreads nptl

以下代码应该生成100,000个线程:

/* compile with:   gcc -lpthread -o thread-limit thread-limit.c */
/* originally from: http://www.volano.com/linuxnotes.html */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>

#define MAX_THREADS 100000
int i;

void run(void) {
  sleep(60 * 60);
}

int main(int argc, char *argv[]) {
  int rc = 0;
  pthread_t thread[MAX_THREADS];
  printf("Creating threads ...\n");
  for (i = 0; i < MAX_THREADS && rc == 0; i++) {
    rc = pthread_create(&(thread[i]), NULL, (void *) &run, NULL);
    if (rc == 0) {
      pthread_detach(thread[i]);
      if ((i + 1) % 100 == 0)
    printf("%i threads so far ...\n", i + 1);
    }
    else
    {
      printf("Failed with return code %i creating thread %i (%s).\n",
         rc, i + 1, strerror(rc));

      // can we allocate memory?
      char *block = NULL;
      block = malloc(65545);
      if(block == NULL)
        printf("Malloc failed too :( \n");
      else
        printf("Malloc worked, hmmm\n");
    }
  }
sleep(60*60); // ctrl+c to exit; makes it easier to see mem use
  exit(0);
}
Run Code Online (Sandbox Code Playgroud)

这是在64位机器上运行,具有32GB RAM; 安装Debian 5.0,全部库存.

  • ulimit -s 512保持堆栈大小
  • / proc/sys/kernel/pid_max设置为1,000,000(默认情况下,它的上限为32k pids).
  • ulimit -u 1000000增加最大进程(不要认为这很重要)
  • / proc/sys/kernel/threads-max设置为1,000,000(默认情况下,它根本没有设置)

运行这个吐出以下内容:

65500 threads so far ...
Failed with return code 12 creating thread 65529 (Cannot allocate memory).
Malloc worked, hmmm
Run Code Online (Sandbox Code Playgroud)

我当然没有用完公羊; 我甚至可以在同一时间启动这些程序中的几个并且它们都启动它们的65k线程.

(请不要建议我不要尝试启动100,000多个线程.这是对应该工作的东西的简单测试.我目前的基于epoll的服务器总是有大约200k +连接,各种论文都表明线程可能是更好的选择. - 谢谢 :) )

rek*_*mso 6

pilcrow提到的/proc/sys/vm/max_map_count是正确的; 提高此值可以打开更多线程; 不确定所涉及的确切公式,但1mil +值允许大约300k +线程.

(对于试验100k +线程的其他人来说,请查看pthread_create的mmap问题......当较低的内存用完时,新线程会非常快地运行.)