% ======================================================================
% ======================================================================
\chapter{Putting it all together}
% ======================================================================
% ======================================================================


\section{Threads as monitors}
As it was subtely alluded in section \ref{threads}, \code{threads} in \CFA are in fact monitors. This means that all the monitors features are available when using threads. For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine :
\begin{cfacode}
// Visualization declaration
thread Renderer {} renderer;
Frame * simulate( Simulator & this );

// Simulation declaration
thread Simulator{} simulator;
void render( Renderer & this );

// Blocking call used as communication
void draw( Renderer & mutex this, Frame * frame );

// Simualation loop
void main( Simulator & this ) {
	while( true ) {
		Frame * frame = simulate( this );
		draw( renderer, frame );
	}
}

// Rendering loop
void main( Renderer & this ) {
	while( true ) {
		waitfor( draw, this );
		render( this );
	}
}
\end{cfacode}
One of the obvious complaints of the previous code snippet (other than its toy-like simplicity) is that it does not handle exit conditions and just goes on for ever. Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner :
\begin{cfacode}
// Visualization declaration
thread Renderer {} renderer;
Frame * simulate( Simulator & this );

// Simulation declaration
thread Simulator{} simulator;
void render( Renderer & this );

// Blocking call used as communication
void draw( Renderer & mutex this, Frame * frame );

// Simualation loop
void main( Simulator & this ) {
	while( true ) {
		Frame * frame = simulate( this );
		draw( renderer, frame );

		// Exit main loop after the last frame
		if( frame->is_last ) break;
	}
}

// Rendering loop
void main( Renderer & this ) {
	while( true ) {
		   waitfor( draw, this );
		or waitfor( ^?{}, this ) {
			// Add an exit condition
			break;
		}

		render( this );
	}
}
\end{cfacode}

\section{Fibers \& Threads}