简体   繁体   中英

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

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.

Another option besides joining the threads, would be to detach each thread. A detached thread releases all its resources the moment it ends.

To do so just call

pthread_detach(pthread_self());

inside the thread function.

If doing so, take care to also leave the program's main() by calling pthread_exit() (instead of just return ing or exit() ing), as if missing to do so, main() will not just exit itself but the whole process and with this taking down all of the process' threads, which might still be running.

Thanks all.

I replace "pthread_exit(NULL);" by "pthread_detach(pthread_self());" and now is perfect.

I thought that exit means :"Close the Thread" And I thought that detach means "Thread in wait"

But no :) Thanks all.

Christophe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM