简体   繁体   中英

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 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.

I noticed though in Procexp that the new (restarted) thread actually ran for a little bit until the program crashed.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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