我正在尝试理解C#中的Volatile类。
据我的阅读:
Volatile.Write
方法在调用点强制将位置上的值写入。此外,任何早期程序顺序的加载和存储都必须发生在对Volatile.Write的调用之前。Volatile.Read
方法在调用点强制从位置中读取值。此外,任何较晚的程序顺序加载和存储都必须发生在对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);
}
}
在执行写入m_flag
之前,CPU会等待Volatile.Write(ref m_flag, 1);
命令的执行吗?
这如何帮助线程同步?