-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacceptor.cpp
More file actions
60 lines (52 loc) · 1.98 KB
/
acceptor.cpp
File metadata and controls
60 lines (52 loc) · 1.98 KB
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
#include <iostream>
#include <cassert>
#include <atomic>
#include "acceptor.h"
PrepareResponse Acceptor::prepare(unsigned int proposalNumber)
{
std::cout << "Acceptor " << id << ": prepare " << proposalNumber << std::endl;
bool exchanged = false;
AcceptorState currentState;
do {
currentState = this->state.load();
if (proposalNumber > currentState.minNumberToAccept) {
AcceptorState newState = currentState;
newState.minNumberToAccept = proposalNumber;
exchanged = this->state.compare_exchange_weak(currentState, newState);
}
else {
// We can ignore this request or respond with a message NACK.
PrepareResponse nack;
nack.prepareAck = false;
return nack;
}
} while (!exchanged);
return currentState.response;
}
bool Acceptor::accept(unsigned int proposalNumber, int value)
{
std::cout << "Acceptor " << id << ": accept " << proposalNumber << ", value: " << value << std::endl;
bool exchanged = false;
AcceptorState currentState = this->state.load();
assert(currentState.minNumberToAccept >= proposalNumber);
bool accepted = false;
if (currentState.minNumberToAccept == proposalNumber) {
AcceptorState newState = currentState;
newState.response.alreadyAccepted = true;
newState.response.prevValue = value;
newState.response.prevProposalNumber = proposalNumber;
accepted = this->state.compare_exchange_strong(currentState, newState);
}
if (accepted) {
std::cout << "Acceptor " << this->id << " has accepted (" << proposalNumber << ", " << value << ")\n";
}
else {
std::cout << "Acceptor " << this->id << " has NOT accepted (" << proposalNumber << ", " << value << ")\n";
}
// Instead of returning false, we could also just ignore the message and don't respond.
return accepted;
}
PrepareResponse Acceptor::getAccepted()
{
return this->state.load().response;
}