简体   繁体   English

如何重新启动崩溃的线程

[英]How to Restart a Crashed Thread

I'm trying to wait on a thread and restart it if it crashes. 我正在尝试等待线程,如果崩溃则重新启动它。

It crashes on the part inside of the if statement. 它在if语句的内部崩溃。 (If I take that out and replace it with a Sleep and then kill the thread inside Process Explorer I do not get any error (but also the thread does not restart). The error I get is an exception due to a stack overflow in ws2_32.dll . I tried calling the current function inside of the function to see if maybe it would work after having the VirtualAlloc() , memcpy() and what not done over again but I got the same error upon attempting to restart the thread. (如果我将其取出并替换为Sleep ,然后在Process Explorer中杀死线程,我不会得到任何错误(但线程也不会重新启动)。由于ws2_32.dll的堆栈溢出,我得到的错误是一个异常ws2_32.dll 。我尝试在函数内部调用当前函数,以查看是否在具有VirtualAlloc()memcpy()和未完成的操作后VirtualAlloc()正常工作,但尝试重新启动线程时遇到相同的错误。

I noticed though in Procexp that the new (restarted) thread actually ran for a little bit until the program crashed. 我在Procexp中注意到,新的(重新启动的)线程实际上运行了一段时间,直到程序崩溃。

HANDLE theadHandle = CreateThread(NULL, 0, LPTHREAD_START_ROUTINE(code), NULL, 0, NULL);

while (true) {
    ...

    BOOL state = WaitForSingleObject(threadHandle, 0); // Checks if the the thread has died and if so restarts it
    if (state == WAIT_OBJECT_0) {
    threadHandle = CreateThread(NULL, 0, LPTHREAD_START_ROUTINE(code), NULL, 0, NULL);
    }
}

I'm expecting the thread restarts as if nothing ever happened. 我期望线程重新启动,好像什么也没发生。

Thank you for your time. 感谢您的时间。

This approach won't work -- once the memory space of your process is corrupted (as it must be if a thread is crashing), trying to get useful behavior out of your program is a fool's errand. 这种方法行不通-一旦进程的内存空间被破坏(线程崩溃时必须如此),试图从程序中获取有用的行为是愚蠢的。 Even if you think you've got it working, sooner or later you'll find out that it doesn't work reliably (eg it only crashes on certain hardware, or under certain conditions). 即使您认为它可以正常工作,迟早也会发现它不能可靠地工作(例如,它仅在某些硬件或特定条件下崩溃)。

A better approach is to debug your code so that it never crashes in the first place -- that's the only way to make your program reliable and efficient. 更好的方法是调试您的代码,以使其永远不会崩溃—这是使程序可靠和高效的唯一方法。

If for some reason you can't do that, a (not very good) work-around would be to launch the buggy code inside a child process instead of in a thread -- that way, at least when the child process corrupts itself, your main process will be protected (and you can then safely start a new child process if you want to). 如果由于某种原因您不能执行此操作,那么(不是很好)的解决方法是在子进程内而不是线程内启动错误代码-至少在子进程损坏时,您的主进程将受到保护(如果需要,您可以安全地启动新的子进程)。 However, this is only a hack work-around; 但是,这只是一个解决方法。 the proper fix is to make sure the crash doesn't happen in the first place, by making sure the code isn't buggy. 正确的解决方法是通过确保代码没有错误来确保崩溃不会首先发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM