Linux下能够创建的最大线程数

来源:互联网 发布:应力张量不变量 知乎 编辑:程序博客网 时间:2024/06/08 06:25

1. 首先可以运行下面的程序检查,检查你现在的系统总共能创建多少个线程。我的系统上是i=380,也就是最多能创建380个线程。后面分析为什么是它。

// maxthread.cc , compile: gcc maxthread.cc -o thread -lpthread

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

static void *foo( void * ptr);


int main()
{
     int i = 0;
     pthread_t thread;

     while (1) {
         if (pthread_create(&thread, NULL, foo, NULL) != 0)
             return 1;
         i ++;
         printf("i = %d\n", i);
     }
   return 0;
}

void *foo(void * ptr)
{
  printf("Call foo()\n");
}

2. 栈大小的限制,执行下面程序:

int main(int argc, char * argv[])
{
    char buf[1024 * 1024 * 9];
    buf [1024 * 1024 * 9 - 1] = 'a';
    return 0;
}

在我的机器上得到结果:segment ation fault.


3. 检查ulimit -a 的结果,查看stack size:

   stack size              (kbytes, -s) 8192

8192KB 就是栈的大小。不能超过这个栈的数目,因此上面2)分配的buf大小超过了栈限制,得到了setmentation fault。


4. LInux上,最大线程数目是:

number of threads = total virtual memory / (stack size*1024*1024)在32位系统上,进程空间是4G,其中0-3G是用户空间(0x0-0xBFFFFFFF), 3G-4G是内核空间。因此理论上讲,用户空间大小/栈大小=最大线程数。3072M/8M=384,考虑到系统的占用,主线程等,我的系统上是380. 也许在你的系统上是382.5. 根据4),我们可以减小栈限制或者增大虚拟内存使得线程的数目增加。   检查虚拟内存: ulimit -v   检查栈大小: ulimit -s   设置虚拟内存:ulimit -v 新值   设置栈大小: ulimit -s 新值参考:http://stackoverflow.com/questions/344203/maximum-number-of-threads-per-process-in-linux/9211891#9211891
0 0
原创粉丝点击