【发布时间】:2016-11-25 08:15:05
【问题描述】:
这是我创建一些线程的代码。我想同时创建 500 个线程,而不是更多。很简单,但是我的代码在创建 32xxx 个线程后失败了。
那我不明白为什么我在 32751 个线程之后得到错误代码 11,因为,每个线程都结束了。
我可以理解,如果线程不退出,那么同一台计算机上有 32751 个线程......但是在这里,每个线程都退出了。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
void *test_tcp(void *);
int main ()
{
pthread_t threads[500];
int pointeur_thread;
unsigned long compteur_de_thread=0;
long ttt=0;
int i;
for(int i=0;i<=1000000;i++)
{
ttt++;
pointeur_thread=pthread_create(&threads[compteur_de_thread],NULL,test_tcp,NULL);
if (pointeur_thread!=0)
{
printf("Error : %d\n",pointeur_thread);
exit(0);
}
printf("pointeur_thread : %d - Thread : %ld - Compteur_de_thread : %ld\n",pointeur_thread,compteur_de_thread,ttt);
compteur_de_thread++;
if (compteur_de_thread>=500)
compteur_de_thread=0;
}
printf("The END\n");
}
void *test_tcp(void *thread_arg_void)
{
pthread_exit(NULL);
}
【问题讨论】:
-
您正在尝试创建一百万个线程。如果我是你的操作系统,我会拒绝......
-
这会在“同一时间”创建一个超过 500 个线程的 heluvalot,无论您是否意识到这一点。此外,它们都是可加入的,但从未加入。要么加入他们,要么创造他们分离。
标签: c++ c multithreading pthreads pthread-exit