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

4

3 に答える 3

3

Sum(ParallelQuery<Int64>)これは、射影と合計を組み合わせるために使用するワンライナーです。

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

Parallel 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 に答える