c# - Replacing volatile with personal lock or Interlocked? -


curiosity killed cat, cannot resist... asking :-).

there lot of advices floating around avoid volatile. wonder correct/sane replacement -- personal lock, i.e. have variable x wrap in setter/getter lock created it:

private volatile bool x; // // replacement private readonly object x_lock = new object(); private bool __x; private bool x {     { lock (x_lock) return __x; } ... 

or better use interlocked methods (for reading using no-op compareexchange):

private bool x {     { return interlocked.compareexchange(ref __x,false,false); }     ... 

i use bool type avoid discussion problems of compound operations, classic increment of int when have read , write value in 1 atomic step. volatile not such cases in first place, off-topic here.

update: quote eric lippert blog "volatile fields sign doing downright crazy: you’re attempting read , write same value on 2 different threads without putting lock in place". started thinking (up don't see crazy flags). absence of evidence not evidence of absence...


Comments

Popular posts from this blog

php - Autoloader issue not returning Class -

java - How to put two numbers separated by a space into two different arrays -

c++ - Why am i getting wrong values when performing PE base relocation? -