Zackary Zackary - 1 year ago 92
C++ Question

Visual Studio C++ Runtime Issue with Multithreading on the Release Configuration

When I compile with the configuration set to release (for both x86 and x64), my program fails to complete. To clarify, there are no build errors or execution errors.

After looking for a cause and solution for the issue, I found Program only crashes as release build -- how to debug? which proposes that it is an array issue. Though this solve my problem, it gave me some insight on the matter (which I leave here for the next person).

To further muddle matters, it's only when a subroutine on the main thread has an execution time greater than about 0ms.

Here are the relevant sections of code:

// Startup Progress Bar Thread
nPC_Current = 0; // global int
nPC_Max = nPC; // global int (max value nPC_Current will reach)

DWORD myThreadID;
HANDLE progressBarHandle = CreateThread(0, 0, printProgress, &nPC_Current, 0, &myThreadID);

/* Do stuff and time how long it takes (this is what increments nPC_Current) */

// Wait for Progress Bar Thread to Terminate
WaitForSingleObject(progressBarHandle, INFINITE);

Where the offending line that my program gets stuck on is that last statement, where the program waits for the created thread to terminate:

WaitForSingleObject(progressBarHandle, INFINITE);

And here is the code for the progress bar function:

DWORD WINAPI printProgress(LPVOID lpParameter)
int lastProgressPercent = -1; // Only reprint bar when there is a change to display.

// Core Progress Bar Loop
while (nPC_Current <= nPC_Max)
// Do stuff to print a text progress bar
return 0;

Where the 'Core' while loop generally won't get a single iteration if the execution time of the measured subroutine is about 0ms. To clarify this, if the execution time of the timed subroutine is about 0ms, the nPC_Current will be greater than nPC_Max before the printProgressBar executes once. This means that thread will terminate before the main thread begins to wait for it.

If anyone would help with this, or provide some further insight on the matter, that would be fantastic as I'm having quite some trouble figuring this out.



  • wording

  • deleted distracting contents and added clarifications

Answer Source

My guess would be that you forgot to declare your shared global variables volatile (nPC_Current specifically). In the release version of the code the compiler optimized you progress bar loop into an infinite loop with permanently zero value of nPC_Current.

This is why your progress bar never updates from 0% value in release version of the code and this is why your progress bar thread never terminates.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download