在释放模式无限循环 [英] Infinite loop in release mode

查看:174
本文介绍了在释放模式无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面的code中的调试的模式,它会成功完成并退出。但是,如果我运行下面的code中的发布的模式,它会陷入一个死循环,永不结束。

When I run the following code in debug mode, it'll successfully finish and exit. However, if I run the following code in release mode, it'll get stuck in an infinite loop and never finish.

static void Main(string[] args)
{
    bool stop = false;

    new Thread(() =>
    {
        Thread.Sleep(1000);
        stop = true;
        Console.WriteLine("Set \"stop\" to true.");

    }).Start();

    Console.WriteLine("Entering loop.");

    while (!stop)
    {
    }

    Console.WriteLine("Done.");
}

这优化使其陷入一个死循环?

Which optimization is causing it to get stuck in an infinite loop?

推荐答案

我的猜测是在主线程中的停止变量的处理器缓存。在调试模式下,内存模式是严格的,因为调试器必须能够在所有线程提供变量的状态的一个明智的看法。

My guess would be processor caching of the stop variable on the main thread. In debug mode the memory model is stricter because the debugger needs to be able to provide a sensible view of the variable's state across all threads.

试着做一个字段,并标记为挥发性

Try making a field and marking it as volatile:

volatile bool stop = false;

static void Main(string[] args)
{

    new Thread(() =>
    {
        Thread.Sleep(1000);
        stop = true;
        Console.WriteLine("Set \"stop\" to true.");

    }).Start();

    Console.WriteLine("Entering loop.");

    while (!stop)
    {
    }

    Console.WriteLine("Done.");
}

这篇关于在释放模式无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆