I am trying to understand the usage of pthread_cancel on linux environment in c++. But i am getting below runtime problem.
class A {
public:
A(){cout<<"constructor\n";}
~A(){cout<<"destructor\n";}
};
void* run(void* data) {
A a;
while(1) {
//sleep(1);
cout<<"while\n";
}
}
int main() {
pthread_t pid;
pthread_create(&pid,NULL,run,NULL);
sleep(2);;
pthread_cancel(pid);
cout<<"Canceled\n";
pthread_exit(0);
}
Output:
constructor
while
while
...
while
while
Canceled
FATAL: exception not rethrown
Aborted (core dumped)
Core file analysis:
(gdb) where
#0 0x00000036e8c30265 in raise () from /lib64/libc.so.6
#1 0x00000036e8c31d10 in abort () from /lib64/libc.so.6
#2 0x00000036e9c0d221 in unwind_cleanup () from /lib64/libpthread.so.0
#3 0x00000036fa69042b in std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) () from /usr/lib64/libstdc++.so.6
#4 0x00000000004009c5 in run(void*) ()
#5 0x00000036e9c0677d in start_thread () from /lib64/libpthread.so.0
#6 0x00000036e8cd49ad in clone () from /lib64/libc.so.6
But, If i uncomment the sleep(1) in thread function run, I am getting below output.
constructor
while
Canceled
destructor
Could you please explain me why the program is giving "FATAL: exception not rethrown" in 1st case and not in 2nd? And please explain in detail why pthread_cancel is safer than pthread_kill with an example?