Mission Impossible / How to create datatypes which cannot contain invalid state
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Possible solution
1
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
// {
class SerialPort {
enum class State { Init, Connected, Sending, Receiving };
public:
void connect();
std::string send_request(const std::string& request);
void print_state(std::ostream& os) const;
private:
mutable std::mutex guard_;
State state_ = State::Init;
};
void SerialPort::connect() {
long_running_task();
std::scoped_lock lock{guard_};
BOOST_ASSERT_MSG(state_ == State::Init, "port already connected");
state_ = State::Connected;
}
std::string SerialPort::send_request(const std::string& request) {
{
std::scoped_lock lock{guard_};
BOOST_ASSERT_MSG(state_ == State::Connected, "port not connected yet");
state_ = State::Sending;
}
long_running_task();
{
std::scoped_lock lock{guard_};
BOOST_ASSERT_MSG(state_ == State::Sending, "detected race");
state_ = State::Receiving;
}
long_running_task();
{
std::scoped_lock lock{guard_};
BOOST_ASSERT_MSG(state_ == State::Receiving, "detected race");
state_ = State::Connected;
}
return "ack";
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content