对 Volatile.Read/Write 的理解 [英] understanding of Volatile.Read/Write
问题描述
我正在尝试了解 C# Volatile 类.
I'm trying to understand the C# Volatile class.
正如我所读:
Volatile.Write
方法强制写入 location 中的值到呼叫点.此外,任何较早的程序顺序加载和存储必须在调用 Volatile.Write 之前发生.
The
Volatile.Write
method forces the value in location to be written to at the point of the call. In addition, any earlier program-order loads and stores must occur before the call to Volatile.Write.
Volatile.Read
方法强制读取 location 中的值在通话点.此外,任何后来的程序顺序加载和存储必须在调用 Volatile.Read 之后发生.
The Volatile.Read
method forces the value in location to be read from
at the point of the call. In addition, any later program-order loads
and stores must occur after the call to Volatile.Read.
这是否意味着:
internal sealed class ThreadsSharingData {
private Int32 m_flag = 0;
private Int32 m_value = 0;
// This method is executed by one thread
public void Thread1() {
// Note: 5 must be written to m_value before 1 is written to m_flag
m_value = 5;
Volatile.Write(ref m_flag, 1);
}
// This method is executed by another thread
public void Thread2() {
// Note: m_value must be read after m_flag is read
if (Volatile.Read(ref m_flag) == 1)
Console.WriteLine(m_value);
}
}
cpu 会等待 Volatile.Write(ref m_flag, 1);
之前的命令,然后才开始写入 m_flag
?
the cpu will wait for the commands before Volatile.Write(ref m_flag, 1);
before starting to write to m_flag
?
这对线程同步有何帮助?
And how is that helps the threads synchronization?
推荐答案
cpu 会在 Volatile.Write(ref m_flag, 1); 之前等待命令;在开始写入 m_flag 之前?
the cpu will wait for the commands before Volatile.Write(ref m_flag, 1); before starting to write to m_flag?
呃,有点.更好的表述方式是:保证如果任何其他线程看到 m_flag
设置为 1,它们也会看到 m_value
设置为 5.
Eeeh, kinda. A better way to phrase this is: it's guaranteed that, if any other thread sees m_flag
set to 1, they will also see m_value
set to 5.
这对线程同步有何帮助?
And how is that helps the threads synchronization?
我不会说它有助于同步 - 但它确实有助于实现正确性.
I wouldn't say it helps with synchronization - but it does help with achieving correctness.
如果您没有使用 volatile 读/写,编译器/运行时/cpu 可能会重新排序 Thread1
方法中的两条指令,并且程序将能够打印0、5 或什么都没有.
If you weren't using volatile reads/writes, it would be possible for the compiler/runtime/cpu to reorder the two instructions in the Thread1
method, and the program would be able to print either 0, 5 or nothing at all.
使用易失性读/写,程序将打印 5 或根本不打印,但从不 0.这是预期的行为.
With the volatile reads/writes, the program will print either 5 or nothing at all, but never 0. Which is the intended behaviour.
这篇关于对 Volatile.Read/Write 的理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!