【发布时间】:2016-01-24 06:29:51
【问题描述】:
我正在尝试了解 pthread_cancel 在 c++ 中的 linux 环境中的用法。但我遇到了运行时问题。
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);
}
输出:
constructor
while
while
...
while
while
Canceled
FATAL: exception not rethrown
Aborted (core dumped)
核心文件分析:
(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
但是,如果我在线程函数运行中取消注释 sleep(1),我会得到低于输出。
constructor
while
Canceled
destructor
您能否解释一下为什么程序在第一种情况下而不是在第二种情况下给出“致命:异常未重新抛出”?并请举例详细解释为什么pthread_cancel比pthread_kill更安全?
【问题讨论】:
-
几件事:1.)不要在主线程上调用
pthread_exit,如果调用,在创建的线程中进行;这可能是你的问题。 2)什么版本? Pthread 可以是特定于平台的(例如,这在 BSD 上“按预期”工作)。 3.) 您的gdb输出用于线程,因此堆栈将在cout << "while\n"上显示它“崩溃”,执行thread apply all并显示主线程的堆栈。 4.) 问:..explain..in 1st not in 2nd?,答:定时 5.) 问:why pthread_cancel and pthread_kill,答:neither
标签: c++ linux multithreading