为什么单线程异常会导致整个程序崩溃(如何防止?)
Why does a single thread exception crash entire program (how to prevent this?)
如果我运行,例如,
int x = *(0x00000);
程序崩溃。但是为什么整个程序崩溃而不是那个单一线程呢?我创建了多个连续休眠的线程来测试这一点。有没有办法只退出当前线程,而不是整个程序(在 windows 使用 winapi)?
谢谢。
But why does the whole program crash instead of that single thread?
这是设计使然。如果没有人(调试器,如果附加和进程本身)不能处理用户模式异常 - 系统终止进程。这是合乎逻辑的——所有资源都是按进程分配的,而不是按线程分配的。发生未处理的异常后 - 进程可能处于 unstable/corrupted 状态。并且新的异常将是或挂起 - 例如线程可以在异常时拥有一些关键部分或其他资源 - 如果在此时简单地终止线程 - 资源将始终被死亡线程忙碌。当另一个线程尝试进入这个 "critical section" (广义上)时 - 它们永远挂起。 (比如堆临界区)。所以最好只是终止进程而不是在进程中得到新的异常和未定义的行为。
出于同样的原因 - 如果未处理的异常处于内核模式 - 系统自行终止并尝试创建 BSOD。因为在内核中出现未处理的异常后 - 所有系统都处于不稳定状态。并简单地终止有问题的线程 - 不是解决方案。
Is there any way to make only the current thread exit, not the whole
program (on windows using winapi)?
正式是的。简单 - 你可以设置 UnhandledExceptionFilter
by SetUnhandledExceptionFilter
function and inside UnhandledExceptionFilter
simply call TerminateThread
for current thread ( GetCurrentThread()
) 因为
The exception handler specified by lpTopLevelExceptionFilter is
executed in the context of the thread that caused the fault.
另请注意,此回调仅在进程未被调试时调用。
但是 - 这不是解决方案 - 终止线程。解决方案 - 不得在您的流程中出现异常,否则您需要处理它。如果不能 - 进程必须终止。
如果我运行,例如,
int x = *(0x00000);
程序崩溃。但是为什么整个程序崩溃而不是那个单一线程呢?我创建了多个连续休眠的线程来测试这一点。有没有办法只退出当前线程,而不是整个程序(在 windows 使用 winapi)?
谢谢。
But why does the whole program crash instead of that single thread?
这是设计使然。如果没有人(调试器,如果附加和进程本身)不能处理用户模式异常 - 系统终止进程。这是合乎逻辑的——所有资源都是按进程分配的,而不是按线程分配的。发生未处理的异常后 - 进程可能处于 unstable/corrupted 状态。并且新的异常将是或挂起 - 例如线程可以在异常时拥有一些关键部分或其他资源 - 如果在此时简单地终止线程 - 资源将始终被死亡线程忙碌。当另一个线程尝试进入这个 "critical section" (广义上)时 - 它们永远挂起。 (比如堆临界区)。所以最好只是终止进程而不是在进程中得到新的异常和未定义的行为。
出于同样的原因 - 如果未处理的异常处于内核模式 - 系统自行终止并尝试创建 BSOD。因为在内核中出现未处理的异常后 - 所有系统都处于不稳定状态。并简单地终止有问题的线程 - 不是解决方案。
Is there any way to make only the current thread exit, not the whole program (on windows using winapi)?
正式是的。简单 - 你可以设置 UnhandledExceptionFilter
by SetUnhandledExceptionFilter
function and inside UnhandledExceptionFilter
simply call TerminateThread
for current thread ( GetCurrentThread()
) 因为
The exception handler specified by lpTopLevelExceptionFilter is executed in the context of the thread that caused the fault.
另请注意,此回调仅在进程未被调试时调用。
但是 - 这不是解决方案 - 终止线程。解决方案 - 不得在您的流程中出现异常,否则您需要处理它。如果不能 - 进程必须终止。