\section{Event Library}\label{sec:events}

Another common activity for protocols is to schedule an event to
happen some time in the future. To understand how a protocol might use
such events, consider the situation where a network sometimes fails to
deliver a message to the destination. A protocol that wants to offer a
reliable channel across such a network might, after sending a message,
schedule an event that is to occur after a certain period of time. If
the protocol has not received confirmation that the message was
delivered by the time this event happens, then the protocol
retransmits the message. In this case, the event implements a {\it
timeout}; we will see an example of a protocol that uses timeouts
in a later section. Note that another use for events is to perform
periodic maintenance functions, such as garbage collection.

This section introduces the interface to the $x$-kernel's event
manager, which allows protocols to schedule a procedure that is to be
called after a period of time. (See \cite{Event} for a description of
the algorithm and data structures that underly the event manageer.)

The event manager defines a single object---the {\var Event}---and the
following operation:

\begin{quote}
{\var Event evSchedule(EvFunc function, void *argument, int time)}
\end{quote}

\noindent This operation schedules an event that executes the specified
{\var function} with the given {\var argument} after a delay of {\var
time} microseconds.  ({\var EvFunc} is a pointer to function that
returns a {\var void}.) A handle to the event is returned, and this
can be used to cancel the event at some later time.  When an event
fires, a new process is created to run the specified {\var function};
that is, the event runs asynchronously with respect to the rest of the
system.  Since each event occurs at most one time, if the protocol
wants a repeating event, then the next incarnation of the event should
be re-scheduled using {\var evSchedule} as the last action taken in
the event handling {\var function}.

A second operation:

\begin{quote}
{\var EvCancelReturn evCancel(Event event)}
\end{quote}

\noindent is used to cancel the given {\var Event}. {\var evCancel}
is called, for example, because a source has received confirmation
that a message it sent was successfully delivered, and so there is no
reason for it to retransmit the message. The operation's return value,
as defined by the enumeration type {\var EvCancelReturn}, is set to
{\var EVENT\_FINISHED} if the event has already happened, {\var
EVENT\_RUNNING} if the event is currently running, and {\var
EVENT\_CANCELLED} if the event has not run and can be guaranteed to
not run.

Finally, the following operation releases a handle to an event. As
soon as {\var function} completes, the internal resources associated
with the event are freed:

\begin{quote}
{\var void evDetach(Event event)}
\end{quote}
