Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent bad-optimization in Multithreading

The following code:

while (x == 1) { ... }

might be optimized to

while (true) { ... }

if x gets assigned in another thread only. See Illustrating usage of the volatile keyword in C# . The answer there solves this by setting x to be volatile.

However, it looks like that is not the correct way to go about it according to these three contributors (with a combined reputation of over 1 million :) )

Hans Passant A reproducable example of volatile usage : "never assume that it is useful in a multi-threading scenario."

Marc Gravell Value of volatile variable doesn't change in multi-thread : "volatile is not the semantic I usually use to guarantee the behavior"

Eric Lippert Atomicity, volatility and immutability are different, part three : "I discourage you from ever making a volatile field."

Assuming a Backgroundworker is treated like any other multithreading (as opposed to having some built-in mechanism to prevent optimization) - How can bad-optimization be prevented?

like image 552
ispiro Avatar asked Aug 23 '13 13:08

ispiro


1 Answers

You're mischaracterizing my position slightly. Making the field volatile will prevent the optimization. Volatile is not broken in C#. (C++, that's another story.)

My point is not that volatile does not work as expected. My point is that reading and writing the same variable on two different threads is a bad idea in the first place. If you have to use volatile to make your program correct, consider redesigning your program so that it doesn't need volatile at all.

like image 105
Eric Lippert Avatar answered Oct 06 '22 00:10

Eric Lippert