Tuesday, November 16, 2021

[SOLVED] Not able to create thread after reaching count 32751

Issue

#include <stdio.h>
#include <pthread.h>
#include <errno.h>

void *my_thread(void *ddd)
{
    printf("Thread created\n");
    pthread_exit(NULL);
}

int main()
{
    int ret = 0, counter = 0;
    pthread_t et;
    while(1)
    {
        ret = pthread_create(&et, NULL, my_thread, (void *)&counter);
        if(ret)
        {
            printf("Ret = %d, errr = %d, couter = %d\n", ret, errno, counter);
            break;
        }
        counter++;
    }
    return 0;
}

Above is my C code. checked ulimit -s it gives 8192.I am not using pthred_join because i want to process my data parallel and any how thread will be exited after finishing its job. output of the program after creating 32750 thred is

Thread created 32750
Thread created 32751
Ret = 11, errr = 12, couter = 32751

Solution

From the pthread_create man page:

A thread may either be joinable or detached. ...

Only when a terminated joinable thread has been joined are the last of its resources released back to the system. ...

When a detached thread terminates, its resources are automatically released back to the system: ....

By default, a new thread is created in a joinable state, unless attr was set to create the thread in a detached state (using thread_attr_setdetachstate(3)).

This means that for any thread you create but do not join, some resources are still kept after it terminates. After a certain number of threads you will run out of resources.

To avoid this, cou can call pthread_detach after creating the thread or use pthread_attr_setdetachstate Before you create it.



Answered By - Gerhardh