Since Java 5, the volatile
keyword has release/acquire semantics to make side-effects visible to other threads (including assignments to non-volatile variables!). Take these two variables, for example:
int i; volatile int v;
Note that i
is a regular, non-volatile variable. Imagine thread 1 executing the following statements:
i = 42; v = 0;
At some later point in time, thread 2 executes the following statements:
int some_local_variable = v; print(i);
According to the Java memory model, the write of v
in thread 1 followed by the read of v
in thread 2 ensures that thread 2 sees the write to i
executed in thread 1, so the value 42 is printed.
My question is: does volatile
have the same release/acquire semantics in C#?
Advertisement
Answer
The semantics of “volatile” in C# are defined in sections 7.10 and 14.5.4 of the C# 6.0 specification. Rather than reproduce them here, I encourage you to look it up in the spec, and then decide that it is too complicated and dangerous to use “volatile”, and go back to using locks. That’s what I always do.
See “7.10 Execution order” and “14.5.4 Volatile fields” in the C# 6.0 specification.
In the C# 5.0 specification, see “3.10 Execution Order” and “10.5.3 Volatile Fields”