繁体   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