【发布时间】:2022-01-10 20:09:29
【问题描述】:
我正在学习并行编程,我正在尝试并行化合并排序,以使线程数等于递归级别数。将数组分成 8 个子数组,每个子数组使用每个线程。我不想使用 pthreads。我正在发布顺序代码。请告诉我如何使用#pragma 命令和并行化算法的步骤。
#include <stdlib.h>
#include "omp.h"
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int *a, num, i;
scanf("%d",&num);
a = (int *)malloc(sizeof(int) * num);
for(i=0;i<num;i++)
scanf("%d",&a[i]);
mergesort(a, 0, num-1);
printf("\nSorted array :\n");
for(i=0;i<num;i++)
printf("%d ",a[i]);
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
int tid;
if(i<j)
{
mid=(i+j)/2;
//tid=omp_get_thread_num;
#pragma omp parallel sections
ct=omp_get_num_threads(3);
{
//printf("%d",tid);
#pragma omp section
{
mergesort(a,i,mid); //left recursion
}
#pragma omp section
{
mergesort(a,mid+1,j); //right recursion
}
}
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[1000]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second list
temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
【问题讨论】:
-
我会尝试您在问题中发布的内容。将数组分成 8 个数组(逻辑上,使用 8 对索引)。使用 8 个“线程”对 8 个数组进行归并排序,然后使用 4 个“线程”将 4 对数组合并为 4 个数组,然后使用 2 个“线程”将 2 对数组合并为 2 个数组,再使用 1 个“线程”将1 对成 1 个数组。