Renuka
Renuka

Reputation: 217

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?
    }
}

Upvotes: 3

Views: 897

Answers (1)

sonicwave
sonicwave

Reputation: 6092

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.

Upvotes: 5

Related Questions