MPI_Gather素数阵列成一个数组

时间:2018-04-15 15:31:34

标签: c parallel-processing mpi

我正在尝试拆分一个计算数字是否为素数的程序。所以,我在每个过程中分散了一系列数字,并找到该范围内的素数。这是有效的,每个过程都取得范围并找到正确的素数。然后,当我想将每个进程中的所有数组聚集到一个时,我遇到了问题。

它打印出正确数量的数组值,但是有额外的0,所以它会打印出类似2,3,5,7,0,11,13,0,0,0,17,19...的东西,或者我得到断言失败错误,其中memcpy参数内存范围重叠。

以下是我主要的相关代码 -

  thesePrimes = (int*)malloc(sizeof(int) * maxNumberOfTotalPrimes);

  //findPrimes returns k which is the number of primes found and
  //puts all of the prime numbers from this process into thesePrimes.
  //n is the highest number to check if prime (ie n = 100 check for primes
  //less than 100)
  k = findPrimes(thesePrimes, start, end, n);

  //Reduce k to get the total number of primes within the input
  MPI_Reduce(&k, &numberOfPrimes, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);

  //Allocate just enough space to hold all of the primes based on the reduced
  //number of primes
  allPrimes = (int*)malloc(sizeof(int) * numberOfPrimes);

  //Gather each process's thesePrimes into allPrimes using k as the buffer
  //size since k is the number of primes for the process, just send k numbers
  MPI_Gather(thesePrimes, k, MPI_INT, allPrimes, k, MPI_INT, 0, MPI_COMM_WORLD);

  if(myRank == 0) {
    printf("Attempting to print...\n");
    for(i = 0; i < numberOfPrimes; i++)
        printf("allPrimes[%d]=%d\n", i, allPrimes[i]);

    printf("There are %d prime numbers in the range 0 to %d\n", numberOfPrimes, n);
  }

这是我找到素数的函数 -

int findPrimes(int primes[], int start, int end, int n){
    //k is used to count the number of primes
    int i, j, maxJ, k = 0;
    int isPrime = 1;

    printf("Finding primes from %d to %d\n", start, end);

    if(end > n) end = n;
    if(start == 0) start = 2;

    for(i = start; i <= end; i++) {
        maxJ = sqrt(i);

        for(j = 2; j <= maxJ; j++) {
            if(i%j == 0) {
                isPrime = 0;
                break;
            }
        }
        printf("Checking if %d is prime...\n", i);
        if(isPrime) {
         primes[k++] = i;
         printf("%d is a prime number.\n", primes[k-1]);
        }
        else isPrime = 1;
//      printf("Prime check complete.\n");
    }
    printf("k = %d\n", k);
    return k;
}

1 个答案:

答案 0 :(得分:1)

您需要MPI_Gather()每个等级的素数数量,然后您才能MPI_Gatherv()素数。