0
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 中的整数值。我的问题有什么解决办法吗?

4

3 回答 3

3

这是一个Sum(ParallelQuery<Int64>)用于结合投影和求和的单线。

long total = ParallelEnumerable.Range(0, 10000000).Sum(row => count(row));
于 2013-01-17T19:09:52.550 回答
2

并行 LINQ 使这变得简单:

ParallelEnumerable.Range(0, 10000000).Select(i=>count(i)).Sum()
于 2013-01-17T19:08:51.857 回答
0

试试这个:

http://msdn.microsoft.com/en-us/library/system.threading.interlocked.increment(v=vs.100).aspx

你也可以使用标准的 lock() 。

于 2013-01-17T19:05:02.050 回答