Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.8 kB
1
Indexable
Never
#include <mpi.h>
#include <stdio.h>

#define CHUNK_SIZE 1024

void print_elements(int rank, int *A, int *B, int *result_A, int *result_B, int N) {
    int i;
    for (i = 0; i < N; i += CHUNK_SIZE) {
        int j;
        for (j = i; j < i + CHUNK_SIZE && j < N; j++) {
            if (result_A[j])
                printf("%d ", A[j]);
            if (result_B[j])
                printf("%d ", B[j]);
        }
    }
}

int main(int argc, char **argv) {
    int rank, size, N;
    int *A, *B, *C, *D, *result_A, *result_B;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    if (rank == 0) {
        printf("Enter the size of the arrays: ");
        scanf("%d", &N);
    }

    MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);

    if (rank == 0) {
        A = malloc(N * sizeof(int));
        C = malloc(N * sizeof(int));
        result_A = calloc(N, sizeof(int));
        result_B = malloc(N * sizeof(int));
    } else {
        B = malloc(N * sizeof(int));
        D = malloc(N * sizeof(int));
        result_B = calloc(N, sizeof(int));
    }

    if (rank == 0) {
        // Compute result_A
        #pragma omp parallel for
        for (int i = 0; i < N; i++) {
            if (f(A[i]) > C[i])
                result_A[i] = 1;
        }
    } else {
        // Compute result_B
        #pragma omp parallel for
        for (int i = 0; i < N; i++) {
            if (f(B[i]) < D[i])
                result_B[i] = 1;
        }

        MPI_Send(result_B, N, MPI_INT, 0, 0, MPI_COMM_WORLD);
    }

    if (rank == 0) {
        MPI_Recv(result_B, N, MPI_INT, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        print_elements(rank, A, B, result_A, result_B, N);
    }

    MPI_Finalize();
    return 0;
}
Leave a Comment