gpt4 book ai didi

c# - 将 OpenMp Parallel for 简单转换为 c# Parallel for

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:41:57 25 4
gpt4 key购买 nike

您好,我正在将此 c++ ( openmp ) parallel for 转换为 c# parallel for 但它说:

Error 1 Not all code paths return a value in lambda expression of type 'System.Func<int,System.Threading.Tasks.ParallelLoopState,int,int>'

这是我的代码:

C++

void floyd_warshall(int NumOfThreads) {
int i, j, k;

omp_set_num_threads(NumOfThreads);
for (k = 0; k < n; ++k)
#pragma omp parallel for private(i,j)
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
/* If i and j are different nodes and if
the paths between i and k and between
k and j exist, do */
if ((dist[i][k] * dist[k][j] != 0) && (i != j))
/* See if you can't get a shorter path
between i and j by interspacing
k somewhere along the current
path */
if ((dist[i][k] + dist[k][j] < dist[i][j]) || (dist[i][j] == 0))
dist[i][j] = dist[i][k] + dist[k][j];
}

c#

 void floyd_warshall(int NumOfThreads)
{
int k;
ParallelOptions pOp;
pOp.MaxDegreeOfParallelism = NumOfThreads;

for (k = 0; k < n; ++k)
Parallel.For<int>(0, n, pOp , () => 0, (i, loop, j) =>
{ // for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
/* If i and j are different nodes and if
the paths between i and k and between
k and j exist, do */
if ((dist[i, k] * dist[k, j] != 0) && (i != j))
/* See if you can't get a shorter path
between i and j by interspacing
k somewhere along the current
path */
if ((dist[i, k] + dist[k, j] < dist[i, j]) || (dist[i, j] == 0))
dist[i, j] = dist[i, k] + dist[k, j];
}, (j) => 0);
}

最佳答案

您可以使用 Parallel.For 方法的更简单的重载,它不需要您的委托(delegate)有一个返回值。

    var pOp = new ParallelOptions { MaxDegreeOfParallelism = NumOfThreads };

for (int k = 0; k < n; ++k)
Parallel.For(0, n, pOp, i =>
{ // for (i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
/* If i and j are different nodes and if
the paths between i and k and between
k and j exist, do */
if ((dist[i, k] * dist[k, j] != 0) && (i != j))
/* See if you can't get a shorter path
between i and j by interspacing
k somewhere along the current
path */
if ((dist[i, k] + dist[k, j] < dist[i, j]) || (dist[i, j] == 0))
dist[i, j] = dist[i, k] + dist[k, j];
});

关于c# - 将 OpenMp Parallel for 简单转换为 c# Parallel for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27077472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com