An event-based "Dining Philosophers" implementation.
#include <map>
#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 {
::with_either<taken_atom>
::or_else<busy_atom>,
reacts_to<put_atom>>;
chopstick::behavior_type taken_chopstick(chopstick::pointer
self,
actor_addr);
chopstick::behavior_type available_chopstick(chopstick::pointer self) {
return {
[=](take_atom) {
self->become(taken_chopstick(self, self->current_sender()));
return taken_atom::value;
},
cerr << "chopstick received unexpected 'put'" << endl;
}
};
}
chopstick::behavior_type taken_chopstick(chopstick::pointer self,
return {
[](take_atom) {
return busy_atom::value;
},
if (self->current_sender() == user) {
self->become(available_chopstick(self));
}
}
};
}
public:
philosopher(const std::string& n, const chopstick& l, const chopstick& r)
: name(n),
left(l),
right(r) {
thinking.assign(
[=](eat_atom) {
become(hungry);
send(left, take_atom::value);
send(right, take_atom::value);
}
);
hungry.assign(
[=](taken_atom) {
become(granted);
},
[=](busy_atom) {
become(denied);
}
);
granted.assign(
[=](taken_atom) {
aout(this) << name
<< " 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);
},
[=](busy_atom) {
send(this, eat_atom::value);
become(thinking);
}
);
denied.assign(
[=](taken_atom) {
send(this, eat_atom::value);
become(thinking);
},
[=](busy_atom) {
send(this, eat_atom::value);
become(thinking);
}
);
eating.assign(
[=](think_atom) {
delayed_send(this, seconds(5), eat_atom::value);
aout(this) << name << " puts down his chopsticks and starts to think\n";
become(thinking);
}
);
}
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;
};
void dining_philosophers() {
aout(self) << "chopstick ids are:";
std::vector<chopstick> chopsticks;
for (size_t i = 0; i < 5; ++i) {
chopsticks.push_back(
spawn_typed(available_chopstick));
aout(self) << " " << chopsticks.back()->id();
}
aout(self) << endl;
std::vector<std::string> names {"Plato", "Hume", "Kant",
"Nietzsche", "Descartes"};
for (size_t i = 0; i < 5; ++i) {
spawn<philosopher>(names[i], chopsticks[i], chopsticks[(i + 1) % 5]);
}
}
}
int main(int, char**) {
dining_philosophers();
}