如何在c#中写入并行前缀和?
我想用c#写一个并行前缀和。我使用了这个算法:如何在c#中写入并行前缀和?,c#,parallel-processing,prefix-sum,C#,Parallel Processing,Prefix Sum,我想用c#写一个并行前缀和。我使用了这个算法: initial condition: list of n >= 1 elements stored in A[0...(n-1)] final condition: each element A[i] contains A[0]+A[1]+...+A[i] begin spawn (p1,p2,...,p(n-1)) foe all pi where 1 <= i <= n-1 do for j←0 to ⌈log
initial condition: list of n >= 1 elements stored in A[0...(n-1)]
final condition: each element A[i] contains A[0]+A[1]+...+A[i]
begin
spawn (p1,p2,...,p(n-1))
foe all pi where 1 <= i <= n-1 do
for j←0 to ⌈logn⌉-1 do
if i - 2^j >= 0 then
A[i] ← A[i] + A[i - 2^j]
end if
end for
end for
end
初始条件:n>=1个元素的列表存储在[0…(n-1)]
最终条件:每个元素A[i]包含一个[0]+A[1]+…+A[i]
开始
产卵(p1,p2,…,p(n-1))
对于所有pi,其中1至于正确性,原始算法中的对数是以2为底的,这是您的错误(或其中之一)
关于效率,您没有正确理解双缓冲区算法:您应该在B[i]中写入、同步,然后在下一次迭代之前交换A和B数组。你不需要两个障碍或者A[i]=B[i]。然而,当t大于或等于i时,必须执行B[i]=A[i]
最后,Math.Pow是低效的,最好从t=1开始,然后在每次迭代时将其乘以2(据我所知,C#代码使用的算法与原始代码不同。第一段代码使用2个循环(例如,可能是打字错误?)虽然C#snippet只实现了一个循环,但第一个循环告诉所有处理器应该运行以下代码
part将并行运行所有处理器。错误是否可能是因为您正在使用新数组而不是更改旧数组中的值?因此,在if语句中,您应该编写“a[i]+=a[i-t]”或不简写“a[i]=a[i]+a[i-t]”?我不认为这是一个问题。我使用了两个数组,因为处理器的运行速度不一样,而且可能在一个阶段中,一个处理器在其他处理器读取数组之前读取并更改数组。我不认为这是一个问题。我发现了一个问题:每个节点都在本地看到一个数组。如何使所有处理器都看到一个数组的全局数组拉雷?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MPI;
namespace prefixsum3
{
class Program
{
static void Main(string[] args)
{
int[] A = new int[] { 4, 3, 8, 2, 9, 1, 3, 5, 6, 3 };
using (new MPI.Environment(ref args))
{
Intracommunicator comm = Communicator.world;
int size, rank, n, i;
size = comm.Size;
i = comm.Rank + 1;
n = A.Length;
int[] B = new int[10];
for (int j = 0; j <= (Math.Ceiling(Math.Log(n))) - 1; j++)
{
int t = Convert.ToInt32(Math.Pow(2, j));
if ( i - t >= 0)
{
B[i] = A[i] + A[i - t];
}
comm.Barrier();
A[i] = B[i];
comm.Barrier();
}
if (comm.Rank == 0)
{
for (int z = 0; z < n; z++)
{
Console.Write(A[z].ToString() + ",");
}
}
}
}
}
}
for (int t = 1; t < n; t <<= 1)