Prevent bad-optimization in Multithreading
The following code:
while (x == 0) { ... }
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 as
volatile.
However, it looks like that is not reliable 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 code that uses a Backgroundworker and doesn't have two threads
writing to the same object - How can bad-optimization be prevented?
No comments:
Post a Comment