Sunday 15 June 2014

c# - The need for volatile modifier in double checked locking in .NET -



c# - The need for volatile modifier in double checked locking in .NET -

multiple texts when implementing double-checked locking in .net field locking on should have volatile modifier applied. why exactly? considering next example:

public sealed class singleton { private static volatile singleton instance; private static object syncroot = new object(); private singleton() {} public static singleton instance { { if (instance == null) { lock (syncroot) { if (instance == null) instance = new singleton(); } } homecoming instance; } } }

why doesn't "lock (syncroot)" accomplish necessary memory consistency? isn't true after "lock" statement both read , write volatile , necessary consistency accomplished?

volatile unnecessary. well, sort of**

volatile used create memory barrier* between reads , writes on variable. lock, when used, causes memory barriers created around block within lock, in add-on limiting access block 1 thread. memory barriers create each thread reads current value of variable (not local value cached in register) , compiler doesn't reorder statements. using volatile unnecessary** because you've got lock.

joseph albahari explains stuff way improve ever could.

and sure check out jon skeet's guide implementing singleton in c#

update: *volatile causes reads of variable volatilereads , writes volatilewrites, on x86 , x64 on clr, implemented memorybarrier. may finer grained on other systems.

**my reply right if using clr on x86 , x64 processors. might true in other memory models, on mono (and other implementations), itanium64 , future hardware. jon referring in article in "gotchas" double checked locking.

doing 1 of {marking variable volatile, reading thread.volatileread, or inserting phone call thread.memorybarrier} might necessary code work in weak memory model situation.

from understand, on clr (even on ia64), writes never reordered (writes have release semantics). however, on ia64, reads may reordered come before writes, unless marked volatile. unfortuantely, not have access ia64 hardware play with, speculation.

i've found these articles helpful: http://www.codeproject.com/kb/tips/memorybarrier.aspx vance morrison's article (everything links this, talks double checked locking) chris brumme's article (everything links this) joe duffy: broken variants of double checked locking

luis abreu's series on multithreading give nice overview of concepts too http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-load-and-store-reordering.aspx http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-introducing-memory-fences.aspx

c# singleton volatile

No comments:

Post a Comment