2016-07-21 77 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