当使用“挥发性”或“Thread.MemoryBarrier()”中的线程锁定code? (C#)挥发性、线程、MemoryBarrier、Thread

2023-09-02 21:44:23 作者:柔情恋蜜意

当我应该使用挥发性/ Thread.MemoryBarrier()的线程安全?

When should I use volatile/Thread.MemoryBarrier() for thread safety?

推荐答案

您使用挥发性 / Thread.MemoryBarrier()当你想访问线程之间的变量,而不锁定。

You use volatile/Thread.MemoryBarrier() when you want to access a variable across threads without locking.

变量是原子,就像一个 INT 例如,始终读写整个一次。这意味着你将永远不会得到一半的价值的另一个线程改变了它和之后的另一半已经改变了。正因为如此,你可以安全地读取和写入在不同的线程的值而不syncronising。

Variables that are atomic, like an int for example, are always read and written whole at once. That means that you will never get half of the value before another thread changes it and the other half after it has changed. Because of that you can safely read and write the value in different threads without syncronising.

不过,编译器可以优化掉一些读取和写入,您prevent与挥发性关键字。比如你有一个这样的循环:

However, the compiler may optimize away some reads and writes, which you prevent with the volatile keyword. If you for example have a loop like this:

sum = 0;
foreach (int value in list) {
   sum += value;
}

编译器实际上可能计算的寄存器和只写值到变量在循环之后。如果您在变量挥发性,编译器将产生code读取和每一个写变变化,因此,它的值是向上在整个循环日期

The compiler may actually do the calculations in a processor register and only write the value to the sum variable after the loop. If you make the sum variable volatile, the compiler will generate code that reads and writes the variable for every change, so that it's value is up to date throughout the loop.