Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

volatile with release/acquire semantics

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#?

like image 746
fredoverflow Avatar asked Jun 29 '11 19:06

fredoverflow


People also ask

What is semantics acquire release?

An operation has acquire semantics if other processors will always see its effect before any subsequent operation's effect. An operation has release semantics if other processors will see every preceding operation's effect before the effect of the operation itself.

What is volatile keyword example?

Example of Volatile Keyword In the following example, we have defined a class which increases the counter value. The run () method in the VolatileThread. java gets the updated value and old value when the thread begins execution. In the main class, we define the array of thread.

What is volatile in threading?

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. The compiler, the runtime system, and even hardware may rearrange reads and writes to memory locations for performance reasons.

What is the volatile keyword used for?

The volatile keyword prevents the compiler from performing optimization on code involving volatile objects, thus ensuring that each volatile variable assignment and read has a corresponding memory access.


1 Answers

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"

like image 176
Eric Lippert Avatar answered Sep 22 '22 05:09

Eric Lippert