Subj : Re: atexit handler: pthread_cancel, pthread_testcancel, pthread_join To : comp.programming.threads From : Joe Seigh Date : Thu Aug 18 2005 07:25 am annamalai.gurusami@gmail.com wrote: > Hi All, > > I am having a problem related to pthread_join. The following short > program > demonstrates the problem. > > There are two threads of execution involved. The main program (A) and > another > thread (B). The thread B runs continuously (in forever loop) doing its > work. > Every time in the loop, it once call pthread_testcancel to check if it > has to > continue or not. This is its only cancellation point. > > The thread A, calls pthread_cancel(B) in its atexit handler. This is > followed > by a call to pthread_join(B, 0) (in atexit handler). This seems to > create > problems. Any thoughts on this much appreciated. > > #include > #include > #include > > pthread_t th; > > void* start_thread(void *) > { > for(;;) > { > std::cout << "testcancel()" << std::endl; > pthread_testcancel(); > } > } > > void atexit_handler(void) > { > pthread_cancel(th); > pthread_join(th, 0); > } > > int main() > { > atexit( atexit_handler ); > pthread_attr_t attr; > pthread_attr_init(&attr); > pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); > pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); > pthread_create(&th, &attr, start_thread, 0 ); > exit(0); > } > > Some information about my system. > > $ uname -a > Linux redhatas.mct.com 2.6.9-5.ELsmp #1 SMP Wed Jan 5 19:29:47 EST 2005 > x86_64 x86_64 x86_64 GNU/Linux > [...] I think exit() just terminates all the threads so there are no threads to cancel or join. You should probably get EINVAL though unless something somewhere says you can have undefined behavior. The core dump is probably from the thread id being invalid. Thread id's are opaque handles and on Linux appear to be pointers to thread local storage and you tend to get core dumps when no longer valid thread id's are dereferenced. man exit says this Threads terminated by a call to _Exit() or _exit() shall not invoke their cancellation cleanup handlers or per-thread data destructors. exit isn't a clean way to terminate threads so the obvious answer is don't use it if you want clean thread termination. -- Joe Seigh When you get lemons, you make lemonade. When you get hardware, you make software. .