假使一个FormView程序有两个button,分别是button "start"和button "end"按下[start]时,创建线程执行:
toterminate = false;
hasterminate = false;
while(toterminate == false){
  ......
}
hasterminate = true;按下[end]时,主线程执行:
toterminate = true;
while(hasterminate == false){}发现如果已经按下[start],再按下[end],程序无法终止。跟踪之下,发现主线程陷入while(hasterminate == false)退不出来
但如果改成while(hasterminate == false){Sleep(50)}
则程序可退出
这种情况对于release版应用程序特别明显,debug版的则不一定会出现这种情况。
我在linxu平台上也曾经碰过类似的问题。
为什么?

解决方案 »

  1.   

    use volatile keyword in the definition of your variable hasterminate
    volatile bool hasterminate;The volatile keyword is a type qualifier used to declare that an object can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.volatile declarator ;
    The following example declares a volatile integer nVint whose value can be modified by external processes:int volatile nVint;
    Objects declared as volatile are not used in optimizations because their value can change at any time. The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment. One use of the volatile qualifier is to provide access to memory locations used by asynchronous processes such as interrupt handlers.
      

  2.   

    http://www.csdn.net/expert/topic/1072/1072136.xml?temp=.8430445
      

  3.   

    to masterz:
    Just let me try later.
      

  4.   

    是否可以这样理解
    当,按下“end”时,在主线程执行到toterminate = true;时,
    按理说辅助线程应该在检测到toterminate == true 时,退出
    循环并执行hasterminate = true;而主线程应检测到
    hasterminate == true 并退出while循环,这是我们所想到的
    也是我们期望程序执行的。
    但我们忽略了windows 的多线程并行执行实际上时虚拟的并行
    执行,因为cpu的速度远远快于其他的部件,才可能实现的
    而这个并行的概念就是 在cpu空闲的时候去执行别的线程,而
    这个调度问题,不是靠时间片轮转就是靠线程的优先级。而,
    就我了解windows好像是靠的优先级 -- 问题的原因就在这了。
    喏!假如,当我们的主线程执行到while()循环时由于它的优先
    级比辅助线程高,在主线程没有放弃对cpu的控制权的情况下,
    不会去执行辅助线程,而辅助线程没有被执行也就不可能使
    hasterminate = true 而如果hasterminate != true 那我们的
    while循环也就是 -- 死循环! 直至被windows视为没有响应而被
    关闭了。主线程已经陷入了死循环当然就没有反应了。
    我想这也就可以解释为什么假如了休眠,就正常了 -- 因为他放
    弃了控制权,辅助线程可以被执行而关闭
    我记得有改变优先级的函数,但是什么我就不知道了。
    如果辅助线成的优先级比主线程高会如何?我没有想出来,试试
    也许就知道了。