简体   繁体   中英

Works on debug but not release

I have a thread that sets a value to true when it is done. Until then I wait:

while(1)
{
    if(done[0] == true)
    {

        break;
    }
}

This code works just fine in Debug but in Release it stays in the loop forever even though the debugger clearly says that it is true and not false.

Why would this not work?

Thanks

This is symptomatic of not marking done as volatile .

Without volatile the optimising compiler can cache the value in a register.

eg

private volatile int i;

On a side note, It's NOT (IMHO) a good practice to do something like that. You have probably (smartly) simplify your problem, but create a busy loop like that to wait on some task to finish is a bad, bug prone method. You should probably use some locking/event mechanism (or at the very least add sleep to the loop).

This generally is a bad design idea.

Since you are using VS I guess you are targeting windows so I suggest you take a look at WaitForSingleObjects or WaitForMultipleObjects depending on your criteria.

Or if you are just updating stuff on screen maybe take a look at WM_KICKIDLE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM