我刚刚开始学习c#中的Parallel.For(),我有一个功能,可以做一些事情而且我不知道如何将它调整为并行。 任何人都能告诉我这种类似案例的例子吗?
更新
for (int i = 0; i < (samples32array.Length); i += 35) //Delimiter Samples Length = SampleRate*DelimiterTimeLength,( i.e: 44100*0.2=8820 samples)
{
if ((i + (int)DelimiterSamplesCount - 1) > samples32array.Length)
{
break;
}
double power = MyGoertzel.GoertzelFilter(samples32array, i, i + (int)DelimiterSamplesCount - 1, coeffDelimiter);
if (power > max_power)
{
max_power = power;
max_power_index = i;
}
}
更新:这是我的尝试,但出了点问题......
private int delimiter_search_Parallel(float[] samples32array, int DelimiterSamplesCount, double DelimiterFreq)
{
double normalizedfreqDelimiter = DelimiterFreq / 44100;
double coeffDelimiter = 2 * Math.Cos(2 * Math.PI * normalizedfreqDelimiter);
double max_power = 0;
int max_power_index = 0;
List<double> powerParallelList = new List<double>();
List<int> powerParallelListIndex = new List<int>();
Parallel.For(0, samples32array.Length, (i, loopState) =>
{
if ((i + (int)DelimiterSamplesCount - 1) > samples32array.Length)
{
//TODO -> Genereate a Windows with ERROR Exception
loopState.Stop();
return;
}
else
{
double power = MyGoertzel.GoertzelFilter(samples32array, i, i + (int)DelimiterSamplesCount - 1, coeffDelimiter);
powerParallelList.Add(power);
powerParallelListIndex.Add(i);
}
}
);
max_power = powerParallelList.Max();
max_power_index = powerParallelListIndex[powerParallelList.IndexOf(max_power)];
return max_power_index;
}
答案 0 :(得分:1)
出于您的目的,我建议使用类似于以下示例的ConcurrentDictionary<int,double>dictPower
(参考:https://msdn.microsoft.com/en-us/library/dd287191%28v=vs.110%29.aspx)
// dictionary with the desired concurrencyLevel and initialCapacity
ConcurrentDictionary<int, double> cd = new ConcurrentDictionary<int, double>(concurrencyLevel, initialCapacity);
(并发级别通常等于CPU核心数)并相应地修改代码:而不是
powerParallelList.Add(power);
powerParallelListIndex.Add(i);
使用:
dictPower.Add(i,power)
完成Parallel.For
循环后,只需计算Max()
Items
dictPower
(根据您的要求),或根据需要应用任何其他功能。< / p>
希望这可能会有所帮助。
答案 1 :(得分:1)
你应该使用Parallel.For
重载,它允许你拥有线程本地状态,你可以保持当前的最大值。
private int delimiter_search_Parallel(float[] samples32array,int DelimiterSamplesCount,double DelimiterFreq) {
if(samples32array.Length%35<DelimiterSamplesCount-1) {
//TODO -> Genereate a Windows with ERROR Exception
}
double normalizedfreqDelimiter=DelimiterFreq/44100;
double coeffDelimiter=2*Math.Cos(2*Math.PI*normalizedfreqDelimiter);
object lockObject=new object();
Tuple<double,int> result=null;
Parallel.For(0,(samples32array.Length-(DelimiterSamplesCount-1))/35+1,() => (Tuple<double,int>)null,(i,loopState,max) => {
i*=35;
double power=MyGoertzel.GoertzelFilter(samples32array,i,i+(int)DelimiterSamplesCount-1,coeffDelimiter);
return max==null||power>max.Item1?Tuple.Create(power,i):max;
},max => {
if(max!=null) {
lock(lockObject) {
if(result==null||max.Item1>result.Item1) {
result=max;
}
}
}
});
return result.Item2;
}