Home > Enterprise >  How can I find out which thread crashed inside my program?
How can I find out which thread crashed inside my program?

Time:02-27

Consider the following program:

#include <atomic>
#include <thread>
#include <iostream>
#include <string>
#include <windows.h>

std::atomic<int> crashId;

void threadFunction(int id) {
    while (id != crashId) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    int* p = nullptr;
    *p = id;
}

int main() {
    std::thread t1(&threadFunction, 1);
    std::thread t2(&threadFunction, 1);
    int id;
    std::cin >> id;
    crashId = id;
    while (true) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

I start the program (built in Release mode) and go to lunch. When I come back a colleague has typed in either 1 or 2.

How can I find out which thread crashed? Alternatively how could I rewrite the program so that I could find out this the next day?

I tried the Event Viewer. That only seemed to report the process id and filepath to my .exe.

If I had each thread running in a separate .dll would I see this in the Event Viewer log?

CodePudding user response:

On Windows, you can set a registry key associated with your program's name to generate a dump file when a crash happens

Sample instructions here and here (I always recommend generating "full" crash dumps)

With the crash dump in hand, you can load it into a tool such as Windbg or even Visual Studio to observe the call stack and see variable values.

You'll likely need to have the PDB files associated with the EXE in your tool's symbol path to see the function and variable names. Optimized builds are often harder to debug, but there are some compiler switches that generate better (and larger) PDB files that make retail debugging almost as good as non-optimzed builds.

  • Related