1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50 | /*
* Copyright 2021 Jeisson Hidalgo-Cespedes - Universidad de Costa Rica
* Creates a secondary thread that greets in the standard output
*/
#include <mpi.h>
#include <cstdint>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
const size_t MESSAGE_CAPACITY = 256;
int main(int argc, char* argv[]) {
if (MPI_Init(&argc, &argv) == MPI_SUCCESS) {
int my_rank = -1;
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
int process_count = -1;
MPI_Comm_size(MPI_COMM_WORLD, &process_count);
char hostname[MPI_MAX_PROCESSOR_NAME];
int hostname_len = -1;
MPI_Get_processor_name(hostname, &hostname_len);
std::ostringstream buffer;
buffer << "Hello from main thread of process " << my_rank
<< " of " << process_count << " on " << hostname;
if (my_rank != 0) {
const std::string& message = buffer.str();
MPI_Send(message.data(), /*count*/ message.length() + 1, MPI_SIGNED_CHAR
, /*dest*/ 0, /*tag*/ 0, MPI_COMM_WORLD);
} else {
std::cout << 0 << " says: " << buffer.str() << std::endl;
std::vector<char> message(256, '\0');
for (int sender = 1; sender < process_count; ++sender) {
MPI_Recv(&message[0], /*capacity*/ message.size(), MPI_SIGNED_CHAR
, sender, /*tag*/ 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
std::cout << sender << " says: " << &message[0] << std::endl;
}
}
MPI_Finalize();
} else {
std::cout << "Error: could not init MPI environment" << std::endl;
}
return 0;
}
|