c# - does parallel foreach creates different copies of functions in it -
i have next scenario ,
parallel.foreach(al , sentence => { function abc { double x; } y = add(ref y, x) } public static double add(ref double location1, double value) { double newcurrentvalue = 0; while (true) { double currentvalue = newcurrentvalue; double newvalue = currentvalue + value; newcurrentvalue = interlocked.compareexchange(ref location1, newvalue, currentvalue); if (newcurrentvalue == currentvalue) homecoming newvalue; } }
for each sentence in array of sentence al there value of x calculated. , want sum these values of sentences in variable y. when run code each time different value of y. , guess because x getting overwritten before writing y. each sentence parallel foreach creating different or same re-create of function abc? how can prepare this.
since multiple threads access y
writing @ same time
for ex, below code may not result in 4950
int y=0; parallel.foreach(enumerable.range(0, 100), x => y += x);
but 1 ensures it
int z = 0; parallel.foreach(enumerable.range(0, 100), x => interlocked.add(ref z, x));
c#
No comments:
Post a Comment