一个进程最多创建多少个线程

最近,在做一个关于聊天服务器的项目,其中遇到了一个问题,那就是一个进程可以产生多少个线程呢?

开始各种想象,会和不同平台,不同系统相关,网上很多大佬说是1024个,也有256个。

与其无端猜测,不如动手测试一下。在Linux32位平台,进行测试。

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <iostream>
  4 #include <stdlib.h>
  5 #include <string.h>
  6 #include <pthread.h>
  7 #include <errno.h>
  8 
  9 using namespace std;
 10 //测试一个进程可以启动多少个线程???
 11 
 12 void *thread_function(void *arg);
 13 
 14 char message[] = "Hello world";
 15 
 16 int main()
 17 {
 18     int res;
 19     pthread_t a_thread;
 20     int i = 0;
 21     
 22     while( 1 )
 23     {
 24         //创建线程
 25         res = pthread_create(&a_thread, NULL, thread_function, (void *)messa    ge);
 26         i++;
 27         if( res != 0)
 28         {
 29             cout<<"线程个数:"<<i<<endl;
 30             perror("Thread creation failed;errno:");
 31             return 0;
 32         }
 33     }
 34 }
 35 
 36 void *thread_function(void *arg)
 37 {
 38     printf("thread_function is runing.Argument is %s\n", (char*)arg);
 39 }

可能看着会有些粗糙,但是多次测试下来,可以产生304左右个线程。

32位Linux平台下,虚拟内存空间4G,用户空间占3G,内核空间1G,每个线程的栈大小10240,为10M,3072/10=307。除去主线程,下来接近测试数据。

通过命令  ulimit -s或者ulimit -a 可以查看默认栈大小

当然你可以通过命令ulimit -s+参数,临时修改线程栈大小

线程栈修改之后,线程个数增加了。

--------------------- 作者:渔舟唱晚_hanpan 来源:CSDN 原文:https://blog.csdn.net/hhhanpan/article/details/78192653?utm_source=copy 版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/sinat_39440759/article/details/83004823