[英]Works on debug but not release
I have a thread that sets a value to true when it is done. 我有一个线程在完成后将值设置为true。 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. 这段代码在Debug中运行得很好但在Release中它永远保持在循环中,即使调试器清楚地说它是真的而不是假的。
Why would this not work? 为什么这不起作用?
Thanks 谢谢
This is symptomatic of not marking done
as volatile
. 这是没有症状的标记done
的volatile
。
Without volatile
the optimising compiler can cache the value in a register. 如果没有volatile
,优化编译器可以将值缓存在寄存器中。
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. 由于您使用的是VS,我猜您的目标是Windows,因此我建议您根据您的标准查看WaitForSingleObjects或WaitForMultipleObjects 。
Or if you are just updating stuff on screen maybe take a look at WM_KICKIDLE . 或者,如果您只是在屏幕上更新内容,请查看WM_KICKIDLE 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.