无法在C中使用OpenMP实现Dijkstra算法

omqzjyyz  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(176)

我尝试使用OpenMP并行化Dijkstra,但程序无法正常运行。有时显示正确的结果,而有时得到错误的值。我假设这是因为多个线程正在更新同一个变量。但是我找不到这个问题的根源,因为我正在关键区域内进行共享变量更新。有人能帮我确定我犯了什么错误吗?我的作业很快就要到期了,这段代码在概念上是正确的吗?
第一个
序列号:

int minDistance(int dist[], bool sptSet[])
{
    // Initialize min value
    int min = INT_MAX, min_index;
     
    for (int v = 0; v < V; v++)
        if (sptSet[v] == false && dist[v] <= min)
            min = dist[v], min_index = v;
     
    return min_index;
}
     
// A utility function to print the constructed distance
// array
void printSolution(int dist[])
{
    printf("Vertex \t\t Distance from Source\n");
    for (int i = 0; i < V; i++)
        printf("%d \t\t\t\t %d\n", i, dist[i]);
}
     
// Function that implements Dijkstra's single source
// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
    int dist[V]; // The output array.  dist[i] will hold the
                 // shortest
        // distance from src to i
     
    bool sptSet[V]; // sptSet[i] will be true if vertex i is
                    // included in shortest
    // path tree or shortest distance from src to i is
    // finalized
     
    // Initialize all distances as INFINITE and stpSet[] as
    // false
    for (int i = 0; i < V; i++)
        dist[i] = INT_MAX, sptSet[i] = false;
     
    // Distance of source vertex from itself is always 0
    dist[src] = 0;
     
    // Find shortest path for all vertices
    for (int count = 0; count < V - 1; count++) {
        // Pick the minimum distance vertex from the set of
        // vertices not yet processed. u is always equal to
        // src in the first iteration.
        int u = minDistance(dist, sptSet);
     
        // Mark the picked vertex as processed
        sptSet[u] = true;
     
        // Update dist value of the adjacent vertices of the
        // picked vertex.
        for (int v = 0; v < V; v++)
        {
            // Update dist[v] only if is not in sptSet,
            // there is an edge from u to v, and total
            // weight of path from src to  v through u is
            // smaller than current value of dist[v]
            if (!sptSet[v] && graph[u][v]
                && dist[u] != INT_MAX
                && dist[u] + graph[u][v] < dist[v])
                dist[v] = dist[u] + graph[u][v];
        }
    }
     
    // print the constructed distance array
    printSolution(dist);
}
yquaqz18

yquaqz181#

Dijkstra算法是一个很好的算法示例,其中标准公式很难并行化。1.找到最小值2.更新其邻居的每一步都依赖于前一步。因此,您最多只能做到1.将该最小值转化为OpenMP约简2.将更新转化为并行循环。在度数较小的图上,这不会给您带来太多加速。这也意味着您的代码不正确:您正试图并行化外部步骤,这些步骤是顺序的。
但是,您不必仅更新该最小点的相邻点:你可以更新每一步中的所有点。2这简化了代码,减少了开销。3它也做了更多的工作,但是在挂钟时间里它可能完成得稍微快一点。

相关问题