1
I’m trying to paralyze the bubblesort algorithm using Open-MP and C++, and the parallelization strategy is pipe. The following code, to me, makes sense, but it doesn’t work, and only sorts the subvectors (Input size)/(N) with N being the number of threads.
Wouldn’t the "Critical" clause cause threads to be organized and return the ordered vector?
I tried using the "Atomic" clause instead of "Critical", but the compiler returns the error error: invalid form of ‘#pragma omp atomic’ before ‘;’ token
Example: vector 9 4 19 9 5 4 5 6 20 18, with 3 threads, generates vector 4 9 9 4 5 5 19 6 18 20.
#include <iostream>
#include <fstream>
#include <omp.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int *leArq(int numeros,ifstream &ifs)
{
int *vetor;
char caractere[255];
if(ifs.good())
{
vetor = new int [numeros];
for(int i =0;i<numeros;i++)
{
ifs>>vetor[i];
//cout<<vetor[i]<<endl;
}
}
return vetor;
}
void bubbleparalelo(int *a,int tam,int nT)
{
int fatia = tam/nT;
#pragma omp parallel num_threads(nT)
{
int indice = omp_get_thread_num();
int temp;
for(int i=0; i<=tam; i++)
{
for(int j=indice*fatia; j<(indice+1)*fatia; j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
#pragma omp atomic
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Thread numero: %d\n\n", indice);
}
if (tam <= 30)
{
for(int i=0;i<tam;i++)
printf("Vetor: %d\n", a[i]);
}
return;
}
int main(int argc, char **argv)
{
int *a;
int tam;
ifstream ifs;
ifs.open(argv[1]);
int nThreads = atoi(argv[2]);
ifs>>tam;
printf("Lendo o arquivo: %s\n", argv[1]);
a = leArq(tam,ifs);
bubbleparalelo(a,tam,nThreads);
return 0;
}