Philip C
Philip C

Reputation: 1847

Multithreaded Win32 C++ program crashes using try/catch in multiple threads

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:

and running without the debugger:

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.

Upvotes: 3

Views: 1805

Answers (1)

David Heffernan
David Heffernan

Reputation: 612914

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:

  1. This is a bug in the compiler/runtime.
  2. You are linking against a single threaded runtime, or perhaps need to initialize the runtime for multi-threading. You are calling CreateThread but some C++ runtimes require you to use a runtime supplied thread creation function.

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.

Upvotes: 3

Related Questions