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);
}
}
}
上記のコードを並列化したい。count()
0 から 10^9 - 1 までの 10億回の操作を行う必要があります。count()
関数自体は他のスレッドとデータを共有しません。ただし、からの結果を合計するcount()
とtotal
、スレッドセーフではありません。結果は、プログラムを実行するたびに異なります。total
int に格納できない整数値を格納する必要があります。私の問題の解決策はありますか?