说明volatile关键字的使用在C# [英] Illustrating usage of the volatile keyword in C#

查看:240
本文介绍了说明volatile关键字的使用在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想codeA的小程序,它直观地说明了挥发性关键字的行为。理想的情况下,它应该是一个程序,它执行并发访问非易失性静态字段和它获取由于不正确的行为。

I would like to code a little program which visually illustrates the behavior of the volatile keyword. Ideally, it should be a program which performs concurrent access to a non volatile static field and which gets incorrect behavior because of that.

添加在同一个程序应该可以解决这个问题volatile关键字。

Adding the volatile keyword in the same program should fix the problem.

这件事我没能实现。即使尝试了几次,可实现优化等等,我总是得到一个正确的行为没有'动荡'关键字。

That something I didn't manage to achieve. Even trying several times, enabling optimization, etc., I always get a correct behavior without the 'volatile' keyword.

你有关于这个主题的任何想法?你知道如何在一个简单的演示应用程序模拟这样的问题?是否依赖于硬件?

Do you have any idea about this topic? Do you know how to simulate such a problem in a simple demo app? Does it depend on hardware?

推荐答案

我来达到的工作的例子!

I've acheived a working example!

这是维基收到的主要思想,但也有一些变化为C#。维基文章演示了本作的C ++静态字段,它看起来像C#八方通精心编制的请求静态字段...我做例子非静态的:

The main idea received from wiki, but with some changes for C#. The wiki article demonstrates this for static field of C++, it is looks like C# allways carefully compile requests to static fields... and i make example with non static one:

如果您运行这个例子中的发布模式和无需调试器(Ctrl + F5键),然后行',而(test.foo!= 255)'将得到优化到,而(真),并将该软件永远不会返回。 但是,增加动荡关键字后,你总能得到'OK'。

If you run this example in Release mode and without debugger (Ctrl+F5) then a line 'while (test.foo != 255)' will be optimized to 'while(true)' and this program never returns. But after adding 'volatile' keyword, you always get 'OK'.

class Test
{
    int foo;

    static void Main()
    {
        var test = new Test();

        new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start();

        while (test.foo != 255) ;
        Console.WriteLine("OK");
    }
}

这篇关于说明volatile关键字的使用在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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