| 1 | #include <pthread.h>
|
|---|
| 2 | #include <mpi.h>
|
|---|
| 3 | #include <stdio.h>
|
|---|
| 4 |
|
|---|
| 5 | #define TAG 99
|
|---|
| 6 |
|
|---|
| 7 | $input int _mpi_nprocs = 2;
|
|---|
| 8 |
|
|---|
| 9 | void * Thread(void * tid) {
|
|---|
| 10 | int rank, x, y;
|
|---|
| 11 |
|
|---|
| 12 | MPI_Comm_rank(MPI_COMM_WORLD, &rank);
|
|---|
| 13 | x = 2*rank + (int)tid;
|
|---|
| 14 | for (int j=0; j<2; j++) {
|
|---|
| 15 | if (rank == 0) {
|
|---|
| 16 | for (int i=0; i<2; i++){
|
|---|
| 17 | printf("thread %d of rank %d sends at iteration %d.\n", tid, rank, j);
|
|---|
| 18 | MPI_Send(&x, 1, MPI_INT, 1, TAG, MPI_COMM_WORLD);
|
|---|
| 19 | }
|
|---|
| 20 | for (int i=0; i<2; i++){
|
|---|
| 21 | printf("thread %d of rank %d receives at iteration %d.\n", tid, rank, j);
|
|---|
| 22 | MPI_Recv(&y, 1, MPI_INT, 1, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
|
|---|
| 23 | }
|
|---|
| 24 | } else if (rank == 1) {
|
|---|
| 25 | for (int i=0; i<2; i++){
|
|---|
| 26 | printf("thread %d of rank %d receives at iteration %d.\n", tid, rank, j);
|
|---|
| 27 | MPI_Recv(&y, 1, MPI_INT, 0, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
|
|---|
| 28 | }
|
|---|
| 29 | for (int i=0; i<2; i++){
|
|---|
| 30 | printf("thread %d of rank %d sends at iteration %d.\n", tid, rank, j);
|
|---|
| 31 | MPI_Send(&x, 1, MPI_INT, 0, TAG, MPI_COMM_WORLD);
|
|---|
| 32 | }
|
|---|
| 33 | }
|
|---|
| 34 | }
|
|---|
| 35 | pthread_exit(NULL);
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | int main(int argc, char * argv[]) {
|
|---|
| 39 | pthread_t threads[2];
|
|---|
| 40 |
|
|---|
| 41 | MPI_Init(&argc, &argv);
|
|---|
| 42 | for (int i=0; i<2; i++) {
|
|---|
| 43 | pthread_create(&threads[i], NULL, Thread, (void *)(long)i);
|
|---|
| 44 | }
|
|---|
| 45 | for (int i=0; i<2; i++) {
|
|---|
| 46 | pthread_join(threads[i], NULL);
|
|---|
| 47 | }
|
|---|
| 48 | MPI_Finalize();
|
|---|
| 49 | }
|
|---|