An event-based "Dining Philosophers" implementation.
#include <map>
#include <thread>
#include <utility>
#include <vector>
#include <chrono>
#include <sstream>
#include <iostream>
#include "caf/all.hpp"
using std::cout;
using std::cerr;
using std::endl;
using std::chrono::seconds;
namespace {
reacts_to<put_atom>>;
chopstick::behavior_type taken_chopstick(chopstick::pointer,
chopstick::behavior_type available_chopstick(chopstick::pointer self) {
return {
[=](take_atom) -> std::tuple<taken_atom, bool> {
self->become(taken_chopstick(self, self->current_sender()));
return std::make_tuple(taken_atom::value, true);
},
cerr << "chopstick received unexpected 'put'" << endl;
}
};
}
chopstick::behavior_type taken_chopstick(chopstick::pointer self,
return {
[](take_atom) -> std::tuple<taken_atom, bool> {
return std::make_tuple(taken_atom::value, false);
},
if (self->current_sender() == user)
self->become(available_chopstick(self));
}
};
}
public:
std::string n,
chopstick l,
chopstick r)
name_(std::move(n)),
left_(std::move(l)),
right_(std::move(r)) {
set_default_handler(
skip);
thinking_.assign(
[=](eat_atom) {
become(hungry_);
send(left_, take_atom::value);
send(right_, take_atom::value);
}
);
hungry_.assign(
[=](taken_atom, bool result) {
if (result)
become(granted_);
else
become(denied_);
}
);
granted_.assign(
[=](taken_atom, bool result) {
if (result) {
<< " has picked up chopsticks with IDs "
<< left_->id() << " and " << right_->id()
<< " and starts to eat\n";
delayed_send(this, seconds(5), think_atom::value);
become(eating_);
} else {
send(this, eat_atom::value);
become(thinking_);
}
}
);
denied_.assign(
[=](taken_atom, bool result) {
if (result)
send(this, eat_atom::value);
become(thinking_);
}
);
eating_.assign(
[=](think_atom) {
delayed_send(this, seconds(5), eat_atom::value);
<< " puts down his chopsticks and starts to think\n";
become(thinking_);
}
);
}
const char* name() const override {
return name_.c_str();
}
protected:
send(this, think_atom::value);
return (
[=](think_atom) {
aout(
this) << name_ <<
" starts to think\n";
delayed_send(this, seconds(5), eat_atom::value);
become(thinking_);
}
);
}
private:
std::string name_;
chopstick left_;
chopstick right_;
};
}
aout(
self) <<
"chopstick ids are:";
std::vector<chopstick> chopsticks;
for (size_t i = 0; i < 5; ++i) {
chopsticks.push_back(self->spawn(available_chopstick));
aout(
self) <<
" " << chopsticks.back()->id();
}
std::vector<std::string> names {"Plato", "Hume", "Kant",
"Nietzsche", "Descartes"};
for (size_t i = 0; i < 5; ++i)
self->spawn<philosopher>(names[i], chopsticks[i], chopsticks[(i + 1) % 5]);
}
CAF_MAIN()