-
Notifications
You must be signed in to change notification settings - Fork 0
/
proposer.cpp
65 lines (55 loc) · 1.98 KB
/
proposer.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
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <chrono>
#include <thread>
#include <random>
#include "proposer.h"
Proposer::Proposer(
unsigned int minProposalNumber,
unsigned int proposalNumbersIncrement,
std::vector<std::shared_ptr<Acceptor>> acceptors)
: currentProposalNumber(minProposalNumber),
proposalNumbersIncrement(proposalNumbersIncrement),
acceptors(acceptors)
{
std::random_shuffle(this->acceptors.begin(), this->acceptors.end());
}
void Proposer::propose(int val)
{
unsigned int n;
bool exchanged;
do {
n = this->currentProposalNumber.load();
exchanged = this->currentProposalNumber.compare_exchange_weak(n, n + this->proposalNumbersIncrement);
} while (!exchanged);
std::default_random_engine randomEngine(val);
std::uniform_int_distribution<int> uniform_dist(1, 1000);
// TODO: persist n.
// Phase 1.
int majority = this->acceptors.size() / 2 + 1;
PrepareResponse highestNumberedResponse;
highestNumberedResponse.alreadyAccepted = false;
// TODO: parallelize.
for (int i = 0; i < majority; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(uniform_dist(randomEngine)));
PrepareResponse response = this->acceptors[i]->prepare(n);
if (!response.prepareAck) {
std::cout << "Prepare failed!\n";
return;
}
if (response.alreadyAccepted
&& (!highestNumberedResponse.alreadyAccepted
|| response.prevProposalNumber > highestNumberedResponse.prevProposalNumber))
{
highestNumberedResponse = response;
}
}
// Phase 2.
int actualVal = highestNumberedResponse.alreadyAccepted ? highestNumberedResponse.prevValue : val;
// TODO: parallelize;
for (int i = 0; i < majority; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(uniform_dist(randomEngine)));
this->acceptors[i]->accept(n, actualVal);
}
}