using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program
{
class Program
{
static long total = 0;
static long count(int row)
{
/* do_something .. every operation is thread safe here */
return somevalue;
}
static void Main(string[] args)
{
Parallel.For(0, 10000000, i => //some big limit to test threading is working
{
total += count(i);
// however, collecting 'somevalue' from 'count()' operation isn't thread safe.
});
Console.WriteLine(total);
}
}
}
I want to parallelize above code. I have to do one billion operation of count() from 0 to 10^9 – 1. the count() function itself shares no data with other threads. however, adding up results from count() to total ain’t thread safe – the results differ every time I run the program. total has to store some integral value that can’t be stored in int. Is there any solution to my problem?
Here’s a one-liner using
Sum(ParallelQuery<Int64>)to combine the projection and the summation.