gpt4 book ai didi

C++:在没有事件异常的情况下终止调用(GCC)

转载 作者:可可西里 更新时间:2023-11-01 16:42:04 26 4
gpt4 key购买 nike

考虑以下程序:

#include <iostream>
#include <pthread.h>
#include <stdexcept>
#include <unistd.h>

static void* busy(void*)
{
int oldstate ;
auto result = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldstate) ;
if (result != 0)
#ifdef NOEXCEPT
{ std::cerr << "pthread_setcanceltype" << std::endl ; abort() ; }
#else
throw std::runtime_error("pthread_setcanceltype") ;
#endif
while (true)
;
return nullptr ;
}

static pthread_t start()
{
pthread_t t ;
int result = pthread_create(&t,nullptr,busy,nullptr) ;
if (result != 0)
throw std::runtime_error("pthread_create") ;
return t ;
}

static void terminate(pthread_t t)
{
auto result = pthread_cancel(t) ;
if (result != 0)
throw std::runtime_error("pthread_cancel()") ;
result = pthread_join(t,nullptr) ;
if (result != 0)
throw std::runtime_error("pthread_join()") ;
}

int main()
{
auto t = start() ;
sleep(1) ; // may not cause an abort otherwise
terminate(t) ;
return 0 ;
}

只要不使用优化(或 -O1),它就可以正常运行,例如用 g++ -std=c++11 -Wall -o test test.cc -pthread

但是,使用 -O2 或 -O3 程序会中止并显示上述消息。

也很有趣:如果使用 -DNOEXCEPT 编译,它会一直运行。所以看起来,如果一个线程在一个可能 [sic!] 抛出异常的函数中被取消,并且如果打开优化,程序可能会中止。 -- 而且我看不出有什么方法可以防止这种情况发生。

对我来说,它可以在 amd64 gcc 4.8.4 (Ubuntu 14.04.3) 和 armv7l gcc 4.9.2 (Raspbian 4.9.2-10) 上重现。

你能重现吗?你有解释吗?这种行为似乎很奇怪(至少对我而言)。我很乐意收到某种反馈。谢谢!

最佳答案

在 Linux 上(和大多数操作系统一样)异常是一种与语言无关的特性,pthread 取消是使用与语言无关的异常实现的(参见例如 Cancellation and C++ Exceptions)。

当 pthread 取消传递给线程(使用信号,但您不需要知道)时,unwind 机制调用所有已安装的个性,以便它们可以在线程退出之前执行特定于语言的清理。 (这很酷;这意味着如上文所述,您可以为 abi::__forced_unwind 插入一个 catch block ,以检测(但不能阻止)线程取消。)

问题是任何指令都可能发生异步取消,而 g++ 生成的 C++ 异常表仅处理发生在已知能够生成异常的指令(即但不只是调用异常抛出函数)处发生的异常。如果在 C++ 表未涵盖的点生成异常,C++ 个性会 panic 并终止进程(因此“在没有事件异常的情况下终止调用”)。

这受优化影响的原因是 C++ 个性是延迟安装的,但在更高的优化级别下,编译器可能会决定先发制人地安装 C++ 个性。即使在较低的优化级别下,您也可以通过使用 C++ 异常机制来保证崩溃,例如使用 try { throw 0; } 捕捉(整数){}

最简单的修复方法是确保 C++ 个性未安装在要异步取消的线程中。您可以通过将线程函数编译为 C 并且不从中调用任何 C++ 函数来确保这一点。

一个更 hacky 且高度不受支持的解决方案是确保所有异步取消点(即,当收到异步取消时被取消的线程可能所在的所有指令)事实上 C++ 展开表涵盖了这一点。首先你需要编译-fnon-call-exceptions;其次,您必须确保可能是异步取消点的每条指令都在已知为同步取消点的两个点之间,例如pthread_testcancel:

static void* busy(void*)
{
int oldstate ;
auto result = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldstate) ;
if (result != 0)
#ifdef NOEXCEPT
{ std::cerr << "pthread_setcanceltype" << std::endl ; abort() ; }
#else
throw std::runtime_error("pthread_setcanceltype") ;
#endif
pthread_testcancel();
for (unsigned i = 1; ; ++i)
if (i == 0)
pthread_testcancel();
return nullptr ;
}

关于C++:在没有事件异常的情况下终止调用(GCC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37678354/

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