I’m writing a multithreaded program, which would crash when a particular exception was thrown. Having stripped out more and more of the code to find the problem, I’m now left with an extremely simple case which causes one of many different crashes, seemingly at random. I’m at a loss as to why it’s doing this.
Here’s the entire contents of the program as it stands:
#include <windows.h>
WINAPI DWORD threadFunc(LPVOID x) {
while (true) {
try {
throw 1;
} catch (...) {
}
}
return 0;
}
int main(int argc, char *argv[]) {
CreateThread(NULL, 0, threadFunc, NULL, 0, NULL);
CreateThread(NULL, 0, threadFunc, NULL, 0, NULL);
Sleep(1000);
return 0;
}
As far as I can tell, the program crashes while trying to throw, but not necessarily the first time.
The errors I’m getting in debug mode are:
- seg fault, with stack trace including:
- 00403F70 _Unwind_SjLj_RaiseException(exc=0x474380) (../../../gcc-4.4.1/libgcc/../gcc/unwind.inc:113)
- 00000000 0x004025f6 in __cxa_throw() (??:??)
- 00401380 threadFunc(x=0x0) (D:\Software Projects\testcpp\main.cpp:6)
- 7C80B729 KERNEL32!GetModuleFileNameA() (C:\WINDOWS\system32\kernel32.dll:??)
- 00000000 0x00000000 in ??() (??:??)
- Program exited with code 03
and running without the debugger:
- “The instruction 0x something referenced memory at 0x something else“, sometimes once, sometimes twice (presumably for the second thread)
- “Process returned -1073741819 (0xC0000005)”, which is an access violation
- “This application has requested the Runtime to terminate it in an unusual way … Process returned 3 (0x3)”
I’m completely stumped as to what could be causing all these different errors in such a short program. Commenting out one of the CreateThreads stops any errors occurring, so it seems to be something to do with the interaction of multithreading and exception throwing.
I’m using 32-bit Windows XP SP3, and MinGW 4.4.1
Update
The problem seems to have been a bug in the compiler (which is TDM-2 mingw32 4.4.1 – I wasn’t aware of the TDM element when asking the question, but I don’t think it makes a difference). Having upgraded to version 4.6.1 instead, it all seems to work fine.
Thanks to all who contributed to this question.
Update Having clarified in the comments that the errors occur immediately, and not at process shutdown, the only remaining conclusions that I can see are that:
Your problem is probably that the exception handling runtime support is being unloaded whilst the threads are still active. The runtime will shut itself down when you exit the main function. I would have expected the runtime to be more robust than this, but there you go.
I would expect that your problems would vanish if you made sure that all your threads had terminated before you exited your main function. This is good practise no matter what, you don’t want threads to be forcibly terminated under any circumstances.