最近,在做一個關於聊天服務器的項目,其中遇到了一個問題,那就是一個進程可以產生多少個線程呢?
開始各種想象,會和不同平臺,不同系統相關,網上很多大佬說是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+參數,臨時修改線程棧大小
線程棧修改之後,線程個數增加了。