c# - acquire & release semantics implied during a lock? -
the volatile keyword used protect fields compiler optimizations:
for non-volatile fields, optimization techniques reorder instructions can lead unexpected , unpredictable results in multi-threaded programs access fields without synchronization such provided lock-statement (section 8.12)
however, msdn doesn't seem make clear whether lock applies optimization protections object used in expression, or statements in statement_block.
if have block of code:
lock(obj_something){ boolfoo = true; if(boolisfriday) dosomething(anything); } is boolfoo , boolisfriday implicity volatile (even if not declared volatile)?
this difficult topic , suggest start reading joe duffy's book concurrent programming on windows - it's 1000 pages of pure knowledge.
in answer question: no variables not made "implicitly volatile"
what lock provide - apart mutual exclusion - fence @ both acquire , release.
this means restrictions put on re-ordering optimizations can applied compiler, jitter, cpu or in between.
in particular:
acquiring lock prevents memory accesses moving before fence.
releasing lock prevents memory accesses moving after fence.
in example, write boolfoo cannot observed thread before lock acquired.
similarly reads of boolisfriday , anything cannot use values read before lock acquired.
at release, write boolfoo must visible when lock released, must writes performed dosomething method.
in answer comment: doesn't prevent other threads re-ordering.
if have thread b this:
// work while lock code running ( int = 0 ; < ( int ) 1e7 ; i++ ) ; var copyofboolfoo = boolfoo; then is possible copyofboolfoo false.
that because might ahead, before for loop , lock code runs, , decide read boolfoo , cache value.
there isn't in thread b prevent this, may happen.
if put fence ( e.g. lock! ) before read of boolfoo in thread b, would guarantee read latest value.
Comments
Post a Comment