簡體   English   中英

了pthread_exit(NULL); 不工作

[英]pthread_exit(NULL); not working

這是我創建一些線程的代碼。 我想在同一時間創建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);
    }

您可能正在獲取與EAGAIN對應的錯誤值,這意味着: 資源不足以創建另一個線程。

問題是你退出后沒有加入你的線程。 這可以在if語句中完成,您可以在其中檢查是否已使用所有ID: if (compteur_de_thread>=500)
只需遍歷數組並在所述數組的元素上調用pthread_join

除了加入線程之外的另一個選擇是分離每個線程。 分離的線程在其結束時釋放所有資源。

這樣做只需打電話

pthread_detach(pthread_self());

在線程函數內部。

如果這樣做,照顧離開程序的main()調用pthread_exit()而不是僅僅return荷蘭國際集團或exit()荷蘭國際集團),好像缺少這樣做, main()將不只是退出本身,而是整個進程並通過這種方式取消可能仍在運行的所有進程的線程。

謝謝大家。

我替換“pthread_exit(NULL);” 通過“pthread_detach(pthread_self());” 現在很完美

我認為退出意味着:“關閉線程”我認為分離意味着“線程在等待”

但沒有:)謝謝大家。

克里斯托夫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM