嗨,我正在将这个 c++ ( openmp ) 并行 for 转换为 c# 并行 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/