libfilezilla
events.cpp

A simple demonstration of using the event system

#include <iostream>
#include <string>
#include <vector>
// A condition that we'll use in this example to signal the main
// thread that the worker has processed the event.
// Define a new event.
// The event is uniquely identified via the incomplete my_event_type struct and
// has two arguments: A string and a vector of ints.
struct my_event_type;
// A simple event handler
class handler final : public fz::event_handler
{
public:
handler(fz::event_loop& l)
: fz::event_handler(l)
{}
virtual ~handler()
{
// This _MUST_ be called to avoid a race so that operator()(fz::event_base const&) is not called on a partially destructed object.
}
private:
// The event loop calls this function for every event sent to this handler.
virtual void operator()(fz::event_base const& ev)
{
// Dispatch the event to the correct function.
fz::dispatch<my_event>(ev, this, &handler::on_my_event);
}
void on_my_event(std::string const& s, std::vector<int> const& v)
{
std::cout << "Received event with text \"" << s << "\" and a vector with " << v.size() << " elements" << std::endl;
// Signal the condition
fz::scoped_lock lock(m);
c.signal(lock);
}
};
int main()
{
// Start an event loop
// Create a handler
handler h(l);
// Send an event to the handler
h.send_event<my_event>("Hello World!", std::vector<int>{23, 42, 666});
// Wait until a signal from the worker thread
fz::scoped_lock lock(m);
c.wait(lock);
// All done.
return 0;
}
Waitable condition variable.
Definition: mutex.hpp:196
void wait(scoped_lock &l)
Wait indefinitely for condition to become signalled.
void signal(scoped_lock &l)
Signal condition variable.
Common base class for all events.
Definition: event.hpp:23
Simple handler for asynchronous event processing.
Definition: event_handler.hpp:55
void remove_handler()
Deactivates handler, removes all pending events and stops all timers for this handler.
virtual void operator()(event_base const &)=0
Called by the event loop in the worker thread with the event to process.
A threaded event loop that supports sending events and timers.
Definition: event_loop.hpp:34
Lean replacement for std::(recursive_)mutex.
Definition: mutex.hpp:52
A simple scoped lock.
Definition: mutex.hpp:93
This is the recommended event class.
Definition: event.hpp:68
Declares the event_handler class.
The namespace used by libfilezilla.
Definition: apply.hpp:17