Download cpp source code

 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iomanip>
#include <iostream>
#include <mpi.h>
#include <cstdlib>
#include <ctime>

const char* compare(double num, double ref)
{
	if ( num < ref )
		return "less than";
	if ( num > ref )
		return "greater than";
	return "equals to";
}


int main(int argc, char* argv[])
{
	MPI_Init(&argc, &argv);
	
	int my_rank = -1;
	int process_count = -1;
	
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
	MPI_Comm_size(MPI_COMM_WORLD, &process_count);
	
	char hostname[MPI_MAX_PROCESSOR_NAME];
	int hostname_length = -1;
	MPI_Get_processor_name(hostname, &hostname_length);

	srand( my_rank + time(nullptr) + clock() );
	int my_lucky_number = rand() % 100;
	
	int global_min = -1;
	int global_sum = -1;
	int global_max = -1;
	
	MPI_Allreduce(&my_lucky_number, &global_min, /*count*/ 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD);
	MPI_Allreduce(&my_lucky_number, &global_sum, /*count*/ 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
	MPI_Allreduce(&my_lucky_number, &global_max, /*count*/ 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);


	char ready = 'Y';
	if ( my_rank != 0 )
		MPI_Recv(&ready, /*capacity*/ 1, MPI_CHAR, /*source*/ my_rank - 1, /*tag*/ 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

	double average = static_cast<double>(global_sum) / process_count;

	std::cout << std::setfill('0') << std::fixed << std::setprecision(2);

	if ( my_lucky_number == global_min )
		std::cout << "Process " << my_rank << ": my lucky number (" << std::setw(2)
			<< my_lucky_number << ") is the minimum ("<< std::setw(2)  << global_min << ")\n";

	std::cout << "Process " << my_rank << ": my lucky number (" << std::setw(2)
		<< my_lucky_number << ") is " << compare(my_lucky_number, average)
		<< " the average (" << std::setw(2) << average << ")\n";
	
	if ( my_lucky_number == global_max )
		std::cout << "Process " << my_rank << ": my lucky number (" << std::setw(2)
			<< my_lucky_number << ") is the maximum (" << std::setw(2) << global_max << ")\n";


	if ( my_rank < process_count - 1 )
		MPI_Send(&ready, /*count*/ 1, MPI_CHAR, /*dest*/ my_rank + 1, /*tag*/ 0, MPI_COMM_WORLD);

	MPI_Finalize();
}