c++cmultithreadingpthreadspthread-exit

pthread_exit(NULL); not working


This is my code for creating some threads. I want create 500 threads in the same time, not more. Easy, but my code failed after 32xxx threads created.

Then I don't understand why I get the error code 11 after 32751 threads, because, each thread ended.

I can understand, if the threads don't exit, then 32751 threads on the same computer ... but here, each thread exited.

Here is my code :

#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);
    }

Solution

  • You're probably getting the error value which corresponds to EAGAIN, which means: Insufficient resources to create another thread.

    The problem is that you're not joining your threads after they exit. This could be done in the if statement where you check if all ids have been used: if (compteur_de_thread>=500).
    Just loop over the array and call pthread_join on the elements of said array.