multithreading - C# Garbage Collector, Threading and Compiler/Jitter optimization -
let's assume our program has central point (an instance of document class), kinds of information referenced. have 2 threads. both threads have access our "document" , "document" contains reference let's "params" (an object holds kind of information). if have reference "document" can use "document.params" our params object.
thread 1 following:
params tempparams = document.params; // local reference documents.params int = tempparams.a; // read data params // thread 1 (this thread) gets interrupted thread 2 int b = tempparams.b; // read data params int c = tempparams.c; // read data params
thread 2 following:
params newparams = new params(); ... // fill newparams new parameters lock(obj) { document.params = newparams; // update params in document }
so content of "params" never changed, if change needed new copy generated , reference "document.params" get's updated new params block atomic action.
now big question is:
is possible jitter might optimize code of thread 1 way tempparams not memory address cpu register? , if thread 2 updates document.params reference, there no reference in memory points old "params" block, since reference in thread 1 in cpu register. , if in moment garbage collector starts, how can see old "params" block still in use?
the other question be: might happen jitter optimizes away tempparams variable , uses document.params.a/b/c directly. in case thread 1 see swap of params object not intended. use of tempparams shall ensure thread 1 access a/b/c same params object in document.params when reference copied.
is possible jitter might optimize code of thread 1 way tempparams not memory address cpu register?
i suspect that's possible - won't stop garbage collector treating use of reference. if did, gc bug.
the other question be: might happen jitter optimizes away tempparams variable , uses document.params.a/b/c directly.
that jit bug, imo. there's no guarantee thread 1 see change document.params
(so that's still risk consider in different scenarios), given has copied reference local variable (tempparams
) , variable never changes value, accesses via tempparams
will address same object. (there's no risk tempparams.a
read 1 object tempparams.b
read different one.)
just bring of commentary below answer - there's discussion around whether it's valid jit "optimize" code such appears change value of local variable. this msdn article suggests valid, example. saw something similar , blogged a long time ago. i'm 99% sure talked (possibly joe duffy) around whether effective read introduction valid ecma-335, , impression wasn't. however, can't find definite documentation that, , ecma-335 at least unclear on matter.
the ecma-335 (cli) specification laxer clr 2.0 model ms has implemented time now, don't believe it's quite that lax. if can't rely on local variables being isolated change, it's hard write any valid code, imo.
Comments
Post a Comment