Parallelizing the Floyd-Warshall algorithm using OpenMP can significantly improve its performance, especially on systems with multiple processors or cores. To use OpenMP in your C code, include the omp.h header and compile the program with an OpenMP-compatible compiler like GCC, using the -fopenmp flag.
Below is a modified version of the Floyd-Warshall algorithm that utilizes OpenMP for parallel processing. The key parts of the algorithm that benefit from parallelization are the loops iterating through the vertices, as each iteration of the inner two loops (over i and j) can be executed independently given a specific value of k.
#include <stdio.h>
#include <omp.h>
#define INF 99999
#define V 4
void printSolution(int dist[][V]);
void floydWarshall(int graph[][V]) {
int dist[V][V], i, j, k;
// Initialize the solution matrix same as input graph matrix.
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
// Adding OpenMP parallel for directive to parallelize the outer loop.
// A single directive is used here for simplicity, but the code can be optimized further.
for (k = 0; k < V; k++) {
#pragma omp parallel for private(i,j) shared(dist,k)
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
// Print the shortest distance matrix
printSolution(dist);
}
void printSolution(int dist[][V]) {
printf("Following matrix shows the shortest distances between every pair of vertices \n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf ("%7d", dist[i][j]);
}
printf("\n");
}
}
int main() {
int graph[V][V] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0} };
floydWarshall(graph);
return 0;
}
To compile this code with GCC and OpenMP support, use the following command:
gcc -fopenmp floyd_warshall_omp.c -o floyd_warshall_omp
Key points:
#pragma omp parallel for: This directive tells OpenMP to parallelize the loop.
private(i,j): Declares i and j as private to each thread to avoid data race conditions.
shared(dist,k): Declares dist and k as shared among threads. Here, k is read-only after initialization, and dist is updated concomitantly by different threads without conflicting due to ensuring each thread works on separate parts of the array.
Remember, the effectiveness of parallelization depends highly on the hardware capabilities (number of cores/threads) and the specific problem size. For small problem sizes or on systems with few cores, the overhead of starting threads may overshadow the benefits of parallel execution.