【问题标题】:Mergesort using openmp使用openmp进行合并排序
【发布时间】: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 个数组。

标签: c openmp mergesort


【解决方案1】:

首先,将 #pragma omp parallel 移动到 main 中,因为不能嵌套多个并行部分(为了性能,因为它会为每个线程创建一个新的并行部分)。

那么,不要使用sections/section,因为它不是为了这样的用途。请改用任务。任务可以像你想做的那样递归提交。您可以使用taskwait 等待任务执行(通常在合并之前)。

由于任务很昂贵,您应该考虑不要创建太多任务。您可以使用if 子句控制是否要创建任务。

不要忘记在主函数中释放分配的数据。

【讨论】:

  • 一个补充:如果OP希望跟踪递归级别,则需要在mergesort函数中添加一个新参数,可以在if子句中使用该参数来停止创建更多任务。 (我不确定这对 OP 来说是否显而易见)
猜你喜欢
  • 1970-01-01
  • 2011-01-02
  • 2012-11-28
  • 1970-01-01
  • 2021-10-01
  • 2016-04-17
  • 1970-01-01
  • 2011-04-01
  • 2018-10-16
相关资源
最近更新 更多