.net - C# modifying DataRow array reference in parallel.foreach , Why code runs correctly? -
this not did code should represent scenario of swapping array reference. not sure if type of array matters @ still specified in title.
- declare datarow arrays outside of loop. name them array1, array2 ... arrayx etc
- array1 = array2 or array1 = array3 ... or array1 = arrayx depending on iteration variable
- do array1
code this:
void somefunction() { int indices[]; (int = 0; < threadamount; ++i) { indices[i] = i; } datarow[] array1, array2, array3; //assign these arrays //... //end of assigning stuff parallel.foreach<int>(indices, index => { if(index == 2) array1 = array2; else if(index == 3) array1 = array3; //do stuff array1 }); } so question. seems code run on arrays (correctly assigning array2 / array3 array1 in other threads) without race condition.
why that? thought have create new variable inside loop no. because creates copy of reference of array1 each thread? , reference array1 in each thread different objects?
ps: first question on here hope did not make mistake :p did read other questions before trying post here don't answer question...
i think mistaken, , there are problems.
i modified code test if array1 changed after thread has set it, , turns out is changed.
the following code print "error!" if array1 changed. on system, prints "error" several times on either release or debug builds (quad core processor).
the results differ each run (what you'd expect race condition):
using system; using system.threading.tasks; namespace demo { static class program { static void main() { somefunction(); } static void somefunction() { int threadamount = 100; int[] indices = new int[threadamount]; (int = 0; < threadamount; ++i) { indices[i] = i; } int[] array1 = new int[1], array2 = new int[2], array3 = new int[3]; parallel.foreach<int>(indices, index => { if (index == 2) array1 = array2; else if (index == 3) array1 = array3; int[] test = array1; console.writeline(array1.length); if (!referenceequals(test, array1)) { console.writeline("error!"); } }); } } }
Comments
Post a Comment