Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread cancel is successful but failing to create thread after few 100's of thread

Here pthread is not getting created after 1013 threads. I know there is a limit in thread creation for every process, but here I am cancelling the thread and in thread I have also called pthread_testcancel() to make a cancellation point. Actually whats happening here? Can anybody help me correct the thread creation failure? I am new to multithreading and it would be great if you provide me with a detailed explanation. Thank you.

#include<iostream>
#include<pthread.h>


void* t(void*){ 
    while(1){
        pthread_testcancel();  //cancellation point?
    }
}
main(){
    pthread_t id;
    int i = 0;
    while(1){
        ++i;
        if(pthread_create(&id, 0, t, 0)){
            std::cout<<"\n failed to create "<<i;  //approx get hit at i=1013
            break;
        }
        if(pthread_cancel(id))  
            std::cout<<"\n i = "<<i;  //not at al executes, pthread_cancell is always successful?
    }
}
like image 564
Renuka Avatar asked Dec 30 '25 15:12

Renuka


1 Answers

By cancelling the thread, you are just stopping the thread - but the system is still keeping its resources around. Since there's only a limited amount of threading resources available, eventually you'll hit a limit where you can't create any more threads.

To clean up the threads resources, you need to either:

  1. Do a pthread_join() on the thread after cancelling it, which will wait for the thread to actually terminate, and also allow you to get back a return value.
  2. Detach the thread either with pthread_detach() after creation or by creating the thread in a detached state). The resources of detached threads are automatically cleaned up when the thread ends, but it doesn't allow you to get back a return value.
like image 176
sonicwave Avatar answered Jan 01 '26 05:01

sonicwave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!