简体   繁体   English

c#中的volatile关键字用途是什么?

[英]What is the volatile keyword purpose in c#?

I want to see the real time use of Volatile keyword in c#. 我想看看在c#中实时使用Volatile关键字。 but am unable to project the best example. 但我无法投射最好的例子。 the below sample code works without Volatile keyword how can it possible? 下面的示例代码在没有Volatile关键字的情况下工作怎么可能?

class Program
{
    private static int a = 0, b = 0;

    static void Main(string[] args)
    {
        Thread t1 = new Thread(Method1);
        Thread t2 = new Thread(Method2);

        t1.Start();
        t2.Start();

        Console.ReadLine();
    }

    static void Method1()
    {
        a = 5;
        b = 1;
    }

    static void Method2()
    {
        if (b == 1)
            Console.WriteLine(a);
    }
}

In the above code i am getting a value as 5. how it works without using volatile keyword? 在上面的代码中,我得到一个值为5.如何在不使用volatile关键字的情况下工作?

The volatile keyword tells the compiler that a variable can change at any time, so it shouldn't optimise away reading and writing of the variable. volatile关键字告诉编译器变量可以随时更改,因此它不应该优化读取和写入变量。

Consider code like this: 考虑这样的代码:

int sum;
for (var i = 0; i < 1000; i++) {
  sum += x * i;
}

As the variable x doesn't change inside the loop, the compiler might read the variable once outside the loop and just use the same value throughout the loop. 由于变量x在循环内部没有变化,编译器可能会在循环外部读取变量,并在整个循环中使用相同的值。

If you make the variable x volatile, the compiler will read the value of the variable each time that it is used, so if you change the value in a different thread, the new value will be used immediately. 如果将变量x设为volatile,则编译器将在每次使用变量时读取变量的值,因此如果更改其他线程中的值,则将立即使用新值。

If you use volatile properly, your code is guaranteed to work. 如果正确使用volatile ,则保证代码正常工作。 If you leave out volatile where your code requires it, it will probably work fine most of the time, but it is not guaranteed and will probably fail when it will hurt the most. 如果你在代码需要的地方省略volatile ,它可能在大多数时候都可以正常工作,但是它不能保证,并且当它会受到最大的伤害时可能会失败。

Understanding how code with threading races fails or doesn't fail requires a deep understanding of the implementation and the platform. 了解线程竞争的代码如何失败或不失败需要深入了解实现和平台。 It's not simple and usually not worth worrying about. 这并不简单,通常不值得担心。 Just follow the rules and your code will work all the time. 只需遵守规则,您的代码就会一直有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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