A Naive C++ Eventloop (poll())#

Readability, And OO#

Eventloop, And Associated Types#

@startuml

interface InputHandler {
  + EventAction ready()
}

class Eventloop {
  + register_input(fd, handler)
  + run()
}

Eventloop -right-> InputHandler

InputHandler <|.. UDPToDatabase
InputHandler <|.. StdinToDatabase

@enduml

  • Eventloop: central “loop” object

  • InputHandler: handle input detected on a file descriptor

    • Polymorphic type: abstract base class, an interface

    • Usually reads from its file descriptor, and does something with the data

Re-Designing The Database Application#

  • With the building blocks outlined above, redesign our database application

  • ⟶ Abstraction is cool

  • ⟶ Do not need to know everything

../../../../../../../_images/eventloop-satellites.svg

Re-Writing The Database Application#

  • Externalize building blocks from the diagram into separate files (see Building Blocks In Detail)

  • Functionality is equivalent to the spaghetti implementation

  • See here for the test protocol

#include "database.h"
#include "eventloop.h"
#include "udp-db.h"
#include "stdin-db.h"

int main()
{
    Eventloop loop;                                    // <-- main loop
    Database db;

    UDPToDatabase udp("0.0.0.0", 1234, db);            // <-- satellite
    StdinToDatabase stdin(db);                         // <-- satellite

    udp.hookup(loop);                                  // <-- register with loop
    stdin.hookup(loop);                                // <-- register with loop

    loop.run();                                        // <-- run until quit

    db.commit();
    return 0;
};

Building Blocks In Detail#