2014-11-18 4 views
2

4 개 노드로 계산하는 프로그램을 작성하려고합니다. 첫 번째 N 개 숫자의 합이 MPI_Scatter입니다.MPI_Scatter가 올바르게 작동하지 않습니다.

각 노드가 계산해야하는 번호를 묻습니다 (예를 들어 5를 입력하면 마스터는 20 개의 크기로 배열을 만들고 각 노드는 5 개의 숫자 합계를 계산합니다) 다시 주인에게. 마침내 마스터는 반환 된 모든 값의 합계를 계산합니다 (MPI_Gather 사용).

node0 -> 1 + 2 + 3 + 4 + 5 = 15

노드 1 -> 6 + 7 + 8 + 9 + 10 = 40

...

node0 -> 15 + 40 + ...

당신은 요점을 얻습니다.

: - 나는 MPI_Scatter 기능에 붙어

은 그냥

내가 오류가 좀 .. 제대로 작동하지 않습니다 "malloc에 ​​3 오류 : 할당 할 수있는 메모리"

내 코드 : 당신이 라인 int *procRow = malloc(sizeof(int) * input);를 호출 할 때

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <mpi.h> 

int *createArray (int st_proc, int input) { 
    int *array; 
    array = malloc(input*st_proc*sizeof(int)); 
    int i; 
    for (i=0; i<input*st_proc; i++) { 
     array[i] = i+1; 
    } 

    return array; 
} 

void printArray (int *row, int nElements) { 
    int i; 
    for (i=0; i<nElements; i++) { 
     printf("%d ", row[i]); 
    } 
    printf("\n"); 
} 

int main (int argc, char **argv) { 

    MPI_Init(&argc, &argv); 
    int nproc, id; 
    MPI_Comm_size(MPI_COMM_WORLD, &nproc); // Get number of processes 
    MPI_Comm_rank(MPI_COMM_WORLD, &id); // Get own ID 

    int *array; 
    int input; 
    if (id == 0) { 
     printf("Vnesi stevilo: \n"); 
     scanf("%d",&input); 
     array = createArray(nproc, input); // Master process creates matrix 
     printf("Initial matrix:\n"); 
     printArray(array, input*nproc); 
    } 
    MPI_Barrier(MPI_COMM_WORLD); 
    int *procRow = malloc(sizeof(int) * input); // received row will contain input integers 
    if (procRow == NULL) { 
     perror("Error in malloc 3"); 
     exit(1); 
    } 

    if (MPI_Scatter(array, input, MPI_INT, // send one row, which contains input integers 
       procRow, input, MPI_INT, // receive one row, which contains input integers 
       0, MPI_COMM_WORLD) != MPI_SUCCESS) { 

     perror("Scatter error"); 
     exit(1); 
    } 

    printf("Process %d received elements: ", id); 
    printArray(procRow, input); 

    MPI_Finalize(); 

    return 0; 
} 
+0

당신은 메모리 누수가있어, 더 이상 필요하지 않게 된 후에'array','procRow'를 자유롭게 사용하거나'return 0' 전에 바로 사용하십시오; –

+0

그래, 나도 알아, 나는 그것을 어떤 이유로 든 제거했다 .. 너무 좌절 ... –

답변

4

이 오류가 발생하는 이유는 만 0 input에 대한 유효한 값을 가지고 평가한다. 다른 모든 순위는 사용자가 입력 한 내용을 알지 못하며 input은 초기화되지 않으므로 malloc 정의되지 않은 동작이 발생합니다. MPI_Barrier 명령을 MPI_Bcast(&input, 1, MPI_INT, 0, MPI_COMM_WORLD); 줄로 바꾸면 코드가 제대로 작동합니다.

+0

나는 그 방향으로 어떻게 든 목표를 세웠다. 다른 계급은 입력에 접근 할 수 없다. . 고마워요! –

관련 문제