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 的十亿次操作。count()
函数本身不与其他线程共享数据。但是,将结果相加count()
并不是total
线程安全的 - 每次运行程序时结果都会有所不同。total
必须存储一些不能存储在 int 中的整数值。我的问题有什么解决办法吗?