小编典典

NPTL将最大线程数限制为65528吗?

linux

以下代码假定可以创建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);
}

它运行在具有32GB RAM的64位计算机上;已安装Debian 5.0,所有库存。

  • ulimit -s 512来减小堆栈大小
  • / proc / sys / kernel / pid_max设置为1,000,000(默认情况下,上限为32k pid)。
  • 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

我当然不会用完内存。我什至可以启动多个同时运行的程序,它们都启动65k线程。

(请不要建议我不要尝试启动100,000个以上的线程。这是对 应该 正常工作的简单测试。我当前的基于epoll的服务器始终具有大约200k
+的连接,各种论文都认为线程可能是一个更好的选择。
- 谢谢 :) )


阅读 255

收藏
2020-06-07

共1个答案

小编典典

pilcrow的提法/proc/sys/vm/max_map_count是正确的;提高该值允许打开更多线程;不确定确切的公式,但是1mil
+的值允许300k +线程。

(对于尝试使用100k
+线程的其他用户,请查看pthread_create的mmap问题…当消耗较少的内存时,使新线程变得非常慢。)

2020-06-07