2

Just a simple example. No need to explain lock, Interlocked and so on.

The bool signals whether a value for state is available. state and the bool is not further modified afterwards.

int state;
volatile bool stateAvailable;

Thread A:
while(!stateAvailable) { sleep }
read state

Thread B:
state = 5;
stateAvailable = true;

Does this ensure that Thread A will always read the state correctly? I'm confused about the guarantees here (only for this simple example):

  • Will a volatile write ensure that operations before will have happened and the volatile read ensure that the operations after will not have happened, thereby also syncing processor state?
  • Or, will the volatile write/read only make sure that the compiler does not optimize away the bool-check from Thread A and it having no impact on the possibly stale value of state?

If you can point me to a duplicate of this question I'd be grateful as well.

AyCe
  • 727
  • 2
  • 11
  • 30
  • You could look at the [language reference](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#1454-volatile-fields). The first pair of bullet points there seem to match what you've said in your first bullet point quite closely. – Damien_The_Unbeliever Mar 07 '23 at 14:35
  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile the note implies that processor stat eis not synced. – Ralf Mar 07 '23 at 14:41
  • 1
    `volatile` accesses have [acquire / release semantics](https://preshing.com/20120913/acquire-and-release-semantics/) in C#. See [volatile with release/acquire semantics](https://stackoverflow.com/a/6526509) for a quote from the C# standard. It doesn't matter that the fields are "nearby", only that the writer set `stateAvailable = true;` only after setting a value for the "payload", and that the reader doesn't read the payload until after an acquire load sees the value from the writer's release-store. – Peter Cordes Mar 07 '23 at 21:30

0 Answers0