-
Notifications
You must be signed in to change notification settings - Fork 0
/
centralserver.cpp
87 lines (77 loc) · 2.5 KB
/
centralserver.cpp
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <mpi.h>
#include <stdio.h>
#include <vector>
#include <chrono>
#include <thread>
#include "fakeprocess2.h"
int main(int argc, char** argv) {
int size, rank;
MPI_Status st;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
printf("Process %d started, out of %d processes.\n", rank, size);
unsigned int token = 0;
FakeProcess proc{rank, 0};
// Server/Lider
if (rank == 0) {
// Notify all processes that server is on
printf("Initializing server...\n");
double t1 = MPI_Wtime();
double t2 = MPI_Wtime();
while (t2 < t1+3) {
t2 = MPI_Wtime();
}
for (unsigned i = 1; i < size; ++i) {
MPI_Send(&token, 1, MPI_UNSIGNED, i, TAG_SEND, MPI_COMM_WORLD);
}
bool running = true;
token = 1;
std::vector<int> queue{};
unsigned msg = 0;
while (running) {
// Aguarda pedidos
printf("Server listening...\n");
MPI_Recv(&msg, 1, MPI_UNSIGNED, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &st);
int enquirer = st.MPI_SOURCE;
int tag = st.MPI_TAG;
if (tag == TAG_ASK) {
if (token && queue.size() == 0) {
printf("Server sending token to %d\n", enquirer);
MPI_Send(&token, 1, MPI_UNSIGNED, enquirer, TAG_SEND, MPI_COMM_WORLD);
token = 0;
}
else {
printf("Server put %d in queue.\n", enquirer);
queue.push_back(enquirer);
}
}
if (tag == TAG_GIVEBACK) {
printf("Server received token back from %d\n", enquirer);
token = 1;
}
if (queue.size() > 0 && token) {
printf("Server sending token to %d\n", queue.front());
MPI_Send(&token, 1, MPI_UNSIGNED, queue.front(), TAG_SEND, MPI_COMM_WORLD);
queue.erase(queue.begin());
token = 0;
}
if (tag == TAG_EXIT) {
printf("Server shutting down.\n");
running = false;
}
}
}
// Other processes
else {
while (true) {
proc.update();
}
}
// Last process tells lider to exit
if (rank == size-1) {
MPI_Send(&token, 1, MPI_UNSIGNED, 0, TAG_EXIT, MPI_COMM_WORLD);
}
MPI_Finalize();
return 0;
}