understanding of Volatile.Read/Write

前端 未结 2 1566
温柔的废话
温柔的废话 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:19

    the cpu will wait for the commands before Volatile.Write(ref m_flag, 1); before starting to write to m_flag?

    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.

    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.

    With the volatile reads/writes, the program will print either 5 or nothing at all, but never 0. Which is the intended behaviour.

提交回复
热议问题