Volatility with release / acquisition semantics

Since Java 5, the volatile keyword has release / get semantics to make side effects visible to other threads (including assignments to immutable variables!). Take these two variables, for example:

 int i; volatile int v; 

Note that i is a regular, nonvolatile variable. Imagine thread 1 doing the following statements:

 i = 42; v = 0; 

At some later point, thread 2 performs the following statements:

 int some_local_variable = v; print(i); 

According to the Java memory model, the record v in thread 1, followed by the reading of v in thread 2, ensures that thread 2 sees the record in i made in thread 1, so the value 42 is printed.

My question is: does volatile the same release / receive semantics in C #?

+6
source share
2 answers

The semantics of "volatile" in C # are defined in sections 3.10 and 10.4.3 of the specification. Instead of reproducing them here, I recommend that you look at it in the specification, and then decide that it is too difficult and dangerous to use "volatility" and return to using locks. This is what I always do.

See 3.10 Order of execution and 10.4.3 Flying fields specification.

+14
source

Ok, I believe that if some_local_variable reads as 0 (due to writing to v ), i will be considered as 42.

The hard part is "at some later point in time." While volatility is usually discussed in terms of flushing, it says that it’s not the way it is actually defined in the specification (either Java or C #).

From the C # 4 language specification, section 10.5.3:

For non-volatile fields, optimization methods that change the order of instructions can lead to unpredictable and unpredictable results in multithreaded programs that access fields without synchronization, for example, provided by the lock operator (Β§8.12). These optimizations can be performed by a compiler, a runtime system, or hardware. For volatile fields, such reordering optimizations are limited:

  • Reading a volatile field is called volatile reading. Intermittent reading has "acquire semantics"; that is, it is guaranteed to occur before any memory references that occur after it in a sequence of commands.
  • A variable field record is called volatile write. A volatile entry has "release semantics"; that is, it is guaranteed to happen after any memory references before a write command in a sequence of commands.

Here is an example that is very similar to yours, but depends on the value read from the mutable variable.

And, like Eric, I would not rely heavily on volatility. It's hard to reason, and it's best to leave Joe Duffy / Stephen Tus in the world.

+6
source

Source: https://habr.com/ru/post/891672/


All Articles