Right way to do a Parallel.For to compute data from Array

前端 未结 2 461
渐次进展
渐次进展 2021-01-22 05:47

want to: sum x and sum x*x. Where x = line[i]. Because more than one thread wants to read/write to the \"sumAll\" and \"sumAllQ\" I need to lock its access. The problem is that

2条回答
  •  礼貌的吻别
    2021-01-22 06:05

    As suggested in the comments, you can use Aggregate to accomplish this with AsParallel in LINQ. For example:

    using System.Linq;
    
    //A class to hold the results.
    //This can be improved by making it immutable and using a constructor.
    public class Result
    {
        public double SumAll { get; set; }
        public double SumAllQ { get; set; }
    }
    

    And you can use LINQ like so:

    var result = line.AsParallel().Aggregate(new Result(), (input, value) => new Result {SumAll = input.SumAll+value, SumAllQ = input.SumAllQ+value*value});
    

    Or even better:

    var pline = line.AsParallel().WithDegreeOfParallelism(Environment.ProcessorCount);
    var result = new Result { SumAll = pline.Sum(), SumAllQ = pline.Sum(x => x * x) };
    

    AsParallel doesn't give you the ability to directly specify options, but you can use .WithDegreeOfParallelism(), .WithExecutionMode(), or .WithMergeOptions() to give you more control. You may have to use WithDegreeOfParallelism to even get it to run with multiple threads.

提交回复
热议问题