GitHub - lightful/syscpp: C++ Active Objects (original) (raw)

C++ essential additions

ActorThread: Active Object pattern in C++

Implementation of theActive Object patternwrapping a standard C++11 thread.

Simple

Main features

Performance

Robustness

Minimum compiler required

Example

// Linux: g++ -std=c++11 -lpthread demo.cpp -o demo // Windows: cl.exe demo.cpp

#include #include #include #include "ActorThread.hpp"

struct Message { std::string description; }; struct OtherMessage { double beautifulness; };

class Consumer : public ActorThread { friend ActorThread; void onMessage(Message& p) { std::cout << "thread " << std::this_thread::get_id() << " receiving " << p.description << std::endl; } void onMessage(OtherMessage& p) { std::cout << "thread " << std::this_thread::get_id() << " receiving " << p.beautifulness << std::endl; } };

class Producer : public ActorThread { friend ActorThread; std::shared_ptr consumer; void onMessage(std::shared_ptr& c) { consumer = c; timerStart(true, std::chrono::milliseconds(250), TimerCycle::Periodic); timerStart(3.14, std::chrono::milliseconds(333), TimerCycle::Periodic); } void onTimer(const bool&) { std::ostringstream report; report << "test from thread " << std::this_thread::get_id(); consumer->send(Message { report.str() }); } void onTimer(const double& value) { consumer->send(OtherMessage { value }); } };

class Application : public ActorThread { friend ActorThread; void onStart() { auto consumer = Consumer::create(); // spawn new threads auto producer = Producer::create(); producer->send(consumer); std::this_thread::sleep_for(std::chrono::seconds(3)); stop(); } };

int main() { return Application::run(); // re-use existing thread }

Despite received by reference, a copy of the original object is delivered to the destination thread. Alternatively, the carried object can be moved, which is the way to transfer non-copiable objects like a unique_ptr. Copying is highly efficient with pointers, but note that several threads must not concurrently access a unsafe pointed object.

See the examples folder for more elaborated examples, including a library and its client using the callbacks mechanism.