【问题标题】:pthread_exit(NULL); not workingpthread_exit(NULL);不工作
【发布时间】:2016-11-25 08:15:05
【问题描述】:

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

【问题讨论】:

  • 您正在尝试创建一百万个线程。如果我是你的操作系统,我会拒绝......
  • 这会在“同一时间”创建一个超过 500 个线程的 heluvalot,无论您是否意识到这一点。此外,它们都是可加入的,但从未加入。要么加入他们,要么创造他们分离。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    要这样做,只需调用

    pthread_detach(pthread_self());
    

    在线程函数内部。

    如果这样做,请注意通过调用pthread_exit()(而不仅仅是returning 或exit()ing)离开程序的main() , 好像没有这样做,main() 不仅会退出自己,还会退出整个进程,并因此取消所有进程的线程,这些线程可能仍在运行。

    【讨论】:

    • 这个答案应该可能包含关于来自main()exit()returning 不是线程安全的警告。
    • @EOF:是的,你是对的...... ;-) 抱歉,接下来的 7 小时内没有评论支持。
    • 如果这些线程在创建新线程之前没有设法退出,这可能会导致同样的问题。
    【解决方案3】:

    谢谢大家。

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

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

    但是没有:) 谢谢大家。

    克里斯托夫

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 2012-01-20
      • 2014-12-22
      • 2015-01-29
      • 2012-04-19
      相关资源
      最近更新 更多