/* 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);
}
这是在一台64位机器上运行,内存为32GB; 安装了Debian 5.0,全部为默认设置。
- ulimit -s 512 以保持堆栈大小
- /proc/sys/kernel/pid_max 设置为1,000,000(默认情况下,它限制为32k个进程ID)。
- 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+连接,各种论文表明线程可能是更好的选择。- 谢谢 :))
pthread_attr_setstack()
手册页的说明,你可以使用的最小堆栈大小为16k。 - Spudd86