A simple way to understand the event driven programming model is to compare and contrast it with the the traditional model. In the traditional model the programmer:
- Writes a main program.
- Explicitly controls a main loop which looks for stuff to do and then does it.
In the event driven model, the programmer:
- Writes application initialization code which, among other things, requests the receipt of events of interest from the outside world.
- Writes handlers for the events and reigsters a correspondence betwen events and their handlers.
- Turns control over to a library event loop which waits for the desired events and dispatches control to their handlers as required.
Event driven software is a win whenever:
- The event loop is sufficiently complex that you'd like to re-use it from application to application.
- You want to decouple the user interface from the functionality of the software.
Both of these criteria are true for the spectrodaq framework.
In the spectrodaq event framework, event handlers are member functions of classes descended from the CEvent class. Thus events are handled as follows:
- The appropriate CEvent subclass is subclassed and its event handlers are overridden with application specific code.
- One or more instance's of this event handler are created (e.g. via new).
- An Event handler's CEvent::Enable member function is called to start the handlers private thread and event loop. See General concepts. for more information about the event classes.
- As the event thread detects events, the overridden handler function is called triggering the application specific behavior.
The example below shows this process:
#include <iostream.h>
#include <stdio.h>
#include <spectrodaq.h>
#include <SpectroFramework.h>
class Echo : public CFileEvent
{
public:
Echo(int fd, const char* pName);
virtual void OnReadable(istream& rin);
};
Echo::Echo(int fd, const char* pName):
CFileEvent(fd, pName)
{
AppendClassInfo();
}
void
Echo::OnReadable(istream& rin)
{
CFileEvent::OnReadable(rin);
string word;
rin >> word;
cout << word << endl;
}
class MyApp : public DAQROCNode
{
protected:
virtual int operator()(int argc, char** argv);
};
int
MyApp::operator()(int argc, char** argv)
{
Echo echo(fileno(stdin), "EchoProcessor");
echo.Enable();
DAQThreadId id = echo.getThreadId();
Join(id);
}
MyApp theapp;
The Echo class subclasses CFileEvent which is an event handler that watches for events on a file descriptor. Overriding OnReadable supplies application specific behavior for a file descriptor when the file becomes readable. The line in MyApp::operator() which reads:
Echo echo(fileno(stdin), "EchoProcessor");
creates an instance of this event to listen for and react to input on stdin. and the call to echo.Enable() starts the thread.
When the event thread detecs input on stdin, it calls Echo::OnReadable which proceses the input in an application specific manner.
Generated on Thu Jan 6 16:58:45 2005 for Spectrodaq External Event Framework by
1.3.9.1