How does this help thread synchronization?
This does not help synchronizing threads in the sense of setting the order of execution of their commands. This ensures that a parallel thread observes changes in memory values ββin a specific order, in cases where a specific order is important to your program logic.
[Does] The CPU expects a command before Volatile.Write(ref m_flag, 1); before you start writing to m_flag ?
No, the command to write to m_value has already been completed. However, its results may not be displayed outside the CPU core, in particular, a thread running on another core may read the old value from m_value after the team that wrote 5 completed execution. This is because the new value may be in the CPU cache, and not in memory.
If you write
m_value = 5; m_flag = 1;
instead of Volatile.Write(ref m_flag, 1) other core can see the entries in a different order: first, it will see that m_flag become 1 , and after that it will see that m_value become 5 . If your other thread uses the m_flag value to evaluate the validity of the m_value , the logic may be broken: for example, Thread2 can sometimes print zero.
dasblinkenlight
source share