Franz Pucher / HIM0Board

You are viewing an older revision! See the latest version

Active Objects

Based on Herb Sutters Klasse "Active Object"

Die Bibliothek mbed-events ist mehr Teil einer Sammlung von Bausteinen als ein Modell für die Entwicklung asynchroner Anwendungen. mbed-events ist ein Teil eines Puzzles, das wir noch nicht ganz herausgefunden haben, und ich bin gespannt, was jeder mit all den Teilen, die wir in mbed OS haben, bauen wird.

Herb Sutters Klasse "Active Object" könnte so aussehen, als wäre sie mit mbed-events implementiert:

Active Object using mbed-events

class Active
{
private:
    EventQueue _queue;
    Thread _thread;

public:
    // Constructor spawns object-specific thread in background
    Active()
    {
        _thread.start(callback(&_queue, &EventQueue::dispatch_forever));
    }

    // Destructor waits for pending events to finish and gracefully cleans up thread
    ~Active()
    {
        _queue.break_dispatch();
        _thread.join();
    }

    // Send passes messages to thread running in the background
    void Send(Callback<void()> m)
    {
        _queue.call(m);
    }
};

Es gibt jedoch einige Bedenken hinsichtlich der Basisimplementierung von Active Objects, insbesondere den Ressourcen, die von jedem Objekt zur Verwaltung seines eigenen Threads verwendet werden. Mit den in mbed-events verfügbaren Tools können Sie auch zusammensetzbare Active Objects erstellen, die die Ausführungsressourcen einer übergeordneten Ereigniswarteschlange gemeinsam nutzen können:

Active Object using mbed-events with shared resources

class ActiveShare
{
private:
    EventQueue _queue;
    Thread *_thread;

public:
    // Constructor chains event queue to parent if provided, otherwise is lazily allocates a thread
    ActiveShare(ActiveShare *parent = NULL)
        : _thread(NULL)
    {
        if (parent) {
            _queue.chain(&parent->_queue);
        } else {
            _thread = new Thread;
            _thread->start(callback(&_queue, &EventQueue::dispatch_forever));
        }
    }

    // Destructor will unchain the event queue from its parent if necessary
    ~ActiveShare()
    {
        if (_thread) {
            _queue.break_dispatch();
            _thread->join();
            delete _thread;
        }
    }

    // Send passes messages to thread running in the background
    void Send(Callback<void()> m)
    {
        _queue.call(m);
    }
};

All wikipages