c++ - pthread_exit(NULL);不工作

标签 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);
    }

最佳答案

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

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

关于c++ - pthread_exit(NULL);不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38509274/

相关文章:

c++ - 在 main() 之前可能需要做什么样的操作

c 编程 - 为什么这个使用 switch 的简单计算器不起作用

c++ - 从 C 代码库在 C++ 中对 unsigned char * 上的 strchr 进行微创更改?

c# - 延迟加载和Thread.MemoryBarrier的使用

c++ - 在 C++ 中使用 libsvm

c++ - 如何在QWidget中创建QToolBar?

c# - 如何枚举 C# 中的所有托管线程?

.net - 并行化具有不同边界的多个相关操作

c++ - ->Release() 是在 COM 对象的析构函数上调用的吗?

c++ - 即使启用了 C++11,静态成员初始化也不适用于 GCC