以下代码应该生成10万个线程:
/* 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位的机器上运行的,内存为32 on;Debian5.0已全部安装。
运行此操作将显示以下内容:
65500 threads so far ...
Failed with return code 12 creating thread 65529 (Cannot allocate memory).
Malloc worked, hmmm我当然不会耗尽内存;我甚至可以启动更多这样的程序--所有这些程序都同时运行,它们都启动它们的65k线程。
(请不要建议我不要尝试启动100,000+线程。这是对应该起作用的东西的简单测试。我当前基于epoll的服务器在任何时候都有大致的200k+连接,而各种文件建议线程可能是一个更好的选择。-谢谢:)
发布于 2010-08-19 16:37:58
pilcrow提到的/proc/sys/vm/max_map_count是正确的;提高这个值可以打开更多的线程;不确定所涉及的确切公式,但是1mil+值允许一些300k+线程。
(对于其他尝试100k+线程的人,请注意创建的mmap问题.当内存不足时,使新线程变得非常慢。)
发布于 2010-08-19 14:00:30
一个可能的问题是主程序中的局部变量thread。我认为64位计算机上的pthread_t应该是8个字节(假设64位构建)。这将是堆栈上的80万字节。我认为你512 K的堆叠限制是个问题。512 K/8= 65536,这与您正在创建的线程数非常接近。您可以尝试动态分配该数组,而不是将其放在堆栈上。
发布于 2010-11-22 19:46:53
这可能有助于将程序中的堆栈大小设置为它可以执行的最小大小(如果您选择的还不够):
/* 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];
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setstacksize(&thread_attr, PTHREAD_STACK_MIN);
printf("Creating threads ...\n");
for (i = 0; i < MAX_THREADS && rc == 0; i++) {
rc = pthread_create(&(thread[i]), &thread_attr, (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);
}此外,您还可以添加这样的调用:在调用pthread_attr_setstacksize()之后添加一个pthread_attr_setstacksize(),但是您将完全释放堆栈溢出检测,这只会为您节省4k的地址空间和零实际内存。
https://stackoverflow.com/questions/3521485
复制相似问题