Untitled
unknown
c_cpp
7 months ago
2.2 kB
1
Indexable
Never
#include <mpi.h> #include <stdio.h> #include <omp.h> #include <math.h> #include <stdlib.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]); } } } double f(int x) { double res = 0.0; for (int i = 0; i < 10; i++) { res += sin(x * i) * cos(x * i) / (i + 1); } return res; } 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) { N = 4; A = malloc(N * sizeof(int)); B = malloc(N * sizeof(int)); C = malloc(N * sizeof(int)); D = malloc(N * sizeof(int)); for (int i = 0; i < N; i++) { A[i] = i; B[i] = i; C[i] = i; D[i] = i; } for (int i = 0; i < N; i++) { printf("%d %d %d %d \n", A[i], B[i], C[i], D[i]); } } MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD); if (rank == 0) { result_A = calloc(N, sizeof(int)); result_B = malloc(N * sizeof(int)); // Compute result_A #pragma omp parallel for for (int i = 0; i < N; i++) { if (f(A[i]) > C[i]) result_A[i] = 1; } 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); } else { B = malloc(N * sizeof(int)); D = malloc(N * sizeof(int)); result_B = calloc(N, sizeof(int); // 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); } MPI_Finalize(); return 0; }
Leave a Comment