了pthread_exit(NULL);不工作

时间:2016-07-21 16:12:42

标签: c++ c multithreading pthreads pthread-exit

这是我创建一些线程的代码。我想在同一时间创建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);
    }

3 个答案:

答案 0 :(得分:2)

您可能获得了与EAGAIN相对应的错误值,这意味着:创建另一个线程的资源不足。

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

答案 1 :(得分:1)

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

为此,请致电

pthread_detach(pthread_self());

在线程函数内部。

如果这样做,请注意 通过调用main()(而不仅仅是{{}来离开该计划pthread_exit() {}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}线程,可能仍在运行。

答案 2 :(得分:0)

谢谢大家。

我替换&#34; pthread_exit(NULL);&#34; by&#34; pthread_detach(pthread_self());&#34;现在很完美。

我认为退出意味着:&#34;关闭线程&#34; 而且我认为分离意味着&#34;线程在等待&#34;

但没有:) 谢谢大家。

克里斯托弗