Reputation: 217
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
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:
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.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