understanding of Volatile.Read/Write

前端 未结 2 1572
温柔的废话
温柔的废话 2021-02-19 01:31

I\'m trying to understand the C# Volatile class.

As i read:

  • The Volatile.Write method forces the value in location to be written to at the

2条回答
  •  旧时难觅i
    2021-02-19 02:12

    How does that help thread synchronization?

    It does not help thread synchronization in the sense of setting the order in which their commands execute. It lets you ensure that a concurrent thread observes changes to values in memory in a specific order, in cases when a particular order is important for the logic of your program.

    [Does] the CPU wait for the commands before Volatile.Write(ref m_flag, 1); before starting to write to m_flag?

    No, the command to write to m_value has already executed. However, its results may not be visible outside the CPU's core - in particular, a thread running on a different core might read an old value from m_value after the command that wrote 5 to it has finished executing. This is because the new value may be in the cache of the CPU, not in the memory.

    If you write

    m_value = 5;
    m_flag = 1;
    

    instead of Volatile.Write(ref m_flag, 1) the other core may see the writes in a different order: first it would see that m_flag became 1, and after that it would see that m_value became 5. If your other thread uses the value of m_flag to judge the validity of m_value, the logic may be broken: for example, Thread2 may occasionally print zero.

提交回复
热议问题