gpt4 book ai didi

c++ - 致命 : exception not rethrown in c++

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:17 35 4
gpt4 key购买 nike

我想了解 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 更安全?

最佳答案

很抱歉成为坏消息的传递者,但是很难让 pthread_cancel 在 Linux 中的 C++ 中正常工作。

原因是 Linux 中的 pthread_cancel 方法实现非常糟糕。特别是它会导致抛出异常(abi::__forced_unwind 截至我撰写本文时)。这在 C 程序中可能很好,但在 C++ 中,很难正确处理线程取消。特别是如果你有任何代码吃掉异常(例如 catch (...)),这个内部异常将被处理,而不是按照它需要的方式向上传递堆栈。在这种情况下,您将看到您所看到的错误消息。

就是说,我看不出您的代码中有什么会“吃掉”这个异常,但我怀疑正是这种性质导致了问题。

在您的特定示例中,当您想要退出而不调用 pthread_cancel 时,可以通过使用标志或类似的东西来轻松解决这个问题。不幸的是,这使得 sleep 变得更加复杂(您需要以较小的间隔多次调用它以检查标志)并且几乎不可能调用 accept (您必须做一个从另一个线程或进程连接到端口以强制 accept 退出,以便您可以检查变量)。一般而言,关于线程取消问题的讨论很长(https://lwn.net/Articles/683118/),但鉴于 macOS(可能还有其他非 Linux“unix”)似乎处理得很好,我真的认为 Linux 实现可以做得更好.但在此之前,pthread_cancel 仍然很难使用。

关于c++ - 致命 : exception not rethrown in c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34972909/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com