我试图理解 C# Volatile 类。
正如我读到的:
这是否意味着在以下情况下:
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
?
这如何帮助线程同步?
cpu 会在 Volatile.Write(ref m_flag, 1); 之前等待命令。在开始写入 m_flag 之前?
呃,有点。更好的表达方式是:保证如果任何其他线程看到m_flag
设置为 1,他们也会看到m_value
设置为 5。
这如何帮助线程同步?
我不会说它有助于同步 - 但它确实有助于实现正确性。
如果您没有使用易失性读/写,编译器/运行时/CPU 可能会重新排序Thread1
方法,程序将能够打印 0、5 或根本不打印任何内容。
对于易失性读/写,程序将打印 5 或根本不打印任何内容,但是never0. 这是预期的行为。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)