The program below keeps hanging/freezing in GDB 7.4 (MinGW32, Eclipse, Windows) absolutely randomly, estimating about every 5 or 6 runs. It is most easily found by mashing the debug button in eclipse and then checking the debug instances that haven't terminated. You can of course do the same thing by running it like a normal person and likely will get the same result quite soon.
The sample never freezes when not attached to GDB. Ever. I also could not expose the same issue under VC++ Express (it was a different sample but really just the same idea).
It hangs mostly around thread creation, thread deletion, and program termination. Also worth of note is that even though main returns -1 as exit code, when attached to GDB whenever the program doesn't freeze it exits with code 0.
Another interesting fact - when I uncomment the "Sleep(1)" call it stops hanging 80% of the time. When it does freeze however, it freezes after it prints "Return -1\n". All other terminations continue to return 0 (except when ran w/o gdb).
Without further ado, the code:
#include <stdio.h>
#include <windows.h>
#include <process.h>
void __cdecl callback(void *arg)
{
int count = 0;
while(count < 10)
{
printf("Thread 2(%i): looping %i\n", (int)arg, count);
count++;
}
printf("Ending thread...\n");
_endthread();
}
int main(int argc, char *argv[])
{
// Mingw32 on windows w/ eclipse - fix console output not showing up until the app terminates
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
bool runMain = true;
int runCount = 0;
while(runMain == true)
{
if(runCount == 5)
{
printf("Thread starting... ");
int result = _beginthread(callback, 0, (void*)5);
// Sleep(1);
if(result == 0)
printf("[FAILURE]\n");
else
printf("[SUCCESS]\n");
}
printf("Thread 1: %i\n", runCount);
runCount++;
if(runCount == 20)
runMain = false;
}
printf("Return -1\n");
return -1;
}
What do you think is causing this, and more importantly - how do I fix it?