File size: 3,272 Bytes
8f4d2d0 | 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | // ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Ping-Pong Example β Learning the Simplx Actor Model
//
// Two actors exchange events back and forth, demonstrating:
// - Actor creation
// - Event definition and registration
// - Event::Pipe for sending events
// - getSourceActorId() for replies
//
// This is the first exercise for understanding the actor framework.
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#include "engine/SimplxShim.hpp"
#include <iostream>
#include <string>
using namespace tredzone;
// ββ Events βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
struct PingEvent : Actor::Event {
int counter;
explicit PingEvent(int c) : counter(c) {}
};
struct PongEvent : Actor::Event {
int counter;
explicit PongEvent(int c) : counter(c) {}
};
// ββ PongActor: receives Ping, sends Pong back βββββββββββββββββββββ
class PongActor : public Actor {
public:
PongActor() {
registerEventHandler<PingEvent>(*this);
std::cout << "[Pong] Created on core " << (int)getCore() << "\n";
}
void onEvent(const PingEvent& event) {
std::cout << "[Pong] Received ping #" << event.counter << "\n";
Event::Pipe pipe(*this, event.getSourceActorId());
pipe.push<PongEvent>(event.counter);
}
};
// ββ PingActor: sends Ping, receives Pong βββββββββββββββββββββββββββ
class PingActor : public Actor {
public:
PingActor(const ActorId& pongId, int maxRounds)
: pongPipe_(*this, pongId), maxRounds_(maxRounds)
{
registerEventHandler<PongEvent>(*this);
std::cout << "[Ping] Created on core " << (int)getCore() << "\n";
// Send first ping
std::cout << "[Ping] Sending ping #1\n";
pongPipe_.push<PingEvent>(1);
}
void onEvent(const PongEvent& event) {
std::cout << "[Ping] Received pong #" << event.counter << "\n";
if (event.counter < maxRounds_) {
int next = event.counter + 1;
std::cout << "[Ping] Sending ping #" << next << "\n";
pongPipe_.push<PingEvent>(next);
} else {
std::cout << "[Ping] Done after " << maxRounds_ << " rounds.\n";
}
}
private:
Event::Pipe pongPipe_;
int maxRounds_;
};
// ββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
int main() {
std::cout << "=== Ping-Pong Actor Example ===\n\n";
// Create actors (in shim mode, single-threaded)
auto pong = std::make_unique<PongActor>();
auto ping = std::make_unique<PingActor>(pong->getActorId(), 5);
std::cout << "\n=== Complete ===\n";
return 0;
}
|