2016-07-21 129 views
1

这是我创建一些线程的代码。我想在同一时间创建500个线程,而不是更多。很简单,但是我的代码在创建32xxx线程后失败。pthread_exit(NULL);不工作

然后我不明白为什么我得到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); 
    } 
+0

您正在尝试创建一百万个线程。我会拒绝,如果我是你的操作系统... –

+0

可能重复[Pthread \ _create失败后创建几个线程](http://stackoverflow.com/questions/5844428/pthread-create-fails-after-creating-several-线程) –

+1

这会在“同一时间”创建超过500个线程的helluvalot,无论您是否意识到这一点。此外,他们都可以联接,但从未加入。加入他们或创建他们分离。 – WhozCraig

回答

1

你可能会得到对应于EAGAIN误差值,这意味着:资源不足,无法创建另一个线程。

问题是,您退出后没有加入您的线程。这可以在if语句中检查是否已使用所有id:if (compteur_de_thread>=500)
只是在数组上循环并且在所述数组的元素上调用pthread_join

1

除了加入线程之外,另一个选择是分离每个线程。分离线程在其结束的时刻释放所有资源。

这样做只是叫

pthread_detach(pthread_self()); 

线程函数里面。

如果这样做,照顾到让程序通过调用pthread_exit()(而不是仅仅return ING或exit()荷兰国际集团),好像缺少这样做,main()不会随便退出本身,而是整个的main()过程,并取消所有进程的线程,这些线程可能仍在运行。

+1

这个答案应该*可能*包含''main()''exit()'或'return'的警告不是线程安全的。 – EOF

+0

@EOF:是的,你是对的...... ;-) sry,在接下来的7个小时内没有评论向上投票。 – alk

+0

如果这些线程在创建新线程之前无法退出,则可能会导致相同的问题。 – 2501

0

谢谢大家。

我将“pthread_exit(NULL);”替换为“通过“pthread_detach(pthread_self());”现在是完美的。

我认为退出的意思是:“关闭线程” 而且我认为分离意思是“等待线程”

但没有:) 感谢所有。

Christophe