\documentclass[AMA,STIX1COL]{WileyNJD-v2}

\articletype{RESEARCH ARTICLE}%

\received{26 April 2016}
\revised{6 June 2016}
\accepted{6 June 2016}

\raggedbottom

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Latex packages used in the document.

\usepackage{epic,eepic}
\usepackage{xspace}
\usepackage{comment}
\usepackage{upquote}						% switch curled `'" to straight
\usepackage{listings}						% format program code
\usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig}
\renewcommand{\thesubfigure}{(\Alph{subfigure})}
\captionsetup{justification=raggedright,singlelinecheck=false}
\usepackage{siunitx}
\sisetup{binary-units=true}

\hypersetup{breaklinks=true}
\definecolor{OliveGreen}{cmyk}{0.64 0 0.95 0.40}
\definecolor{Mahogany}{cmyk}{0 0.85 0.87 0.35}
\definecolor{Plum}{cmyk}{0.50 1 0 0}

\usepackage[pagewise]{lineno}
\renewcommand{\linenumberfont}{\scriptsize\sffamily}

\renewcommand{\textfraction}{0.0}			% the entire page maybe devoted to floats with no text on the page at all

\lefthyphenmin=3							% hyphen only after 4 characters
\righthyphenmin=3

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Names used in the document.

\newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
\newcommand{\CFA}{\protect\CFAIcon} 		% safe for section/caption
\newcommand{\CFL}{\textrm{Cforall}\xspace} 	% Cforall symbolic name
\newcommand{\Celeven}{\textrm{C11}\xspace} 	% C11 symbolic name
\newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
\newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
\newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
\newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
\newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name
\newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
\newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}}
\newcommand{\uC}{$\mu$\CC}
\newcommand{\TODO}[1]{{\Textbf{#1}}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
% removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
% AFTER HYPERREF.
%\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}
\renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}

\renewcommand*{\thefootnote}{\Alph{footnote}} % hack because fnsymbol does not work
%\renewcommand*{\thefootnote}{\fnsymbol{footnote}}

\makeatletter
% parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
% use rather than use \parident directly.
\newlength{\parindentlnth}
\setlength{\parindentlnth}{\parindent}

\newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{\lst@basicstyle{#1}}}}
\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}

\newlength{\gcolumnposn}					% temporary hack because lstlisting does not handle tabs correctly
\newlength{\columnposn}
\setlength{\gcolumnposn}{3.5in}
\setlength{\columnposn}{\gcolumnposn}

\newcommand{\C}[2][\@empty]{\ifx#1\@empty\else\global\setlength{\columnposn}{#1}\global\columnposn=\columnposn\fi\hfill\makebox[\textwidth-\columnposn][l]{\lst@basicstyle{\LstCommentStyle{#2}}}}
\newcommand{\CRT}{\global\columnposn=\gcolumnposn}

% Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
% The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
\newcommand{\newtermFontInline}{\emph}
\newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}

% Latin abbreviation
\newcommand{\abbrevFont}{\textit}			% set empty for no italics
\@ifundefined{eg}{
\newcommand{\EG}{\abbrevFont{e}\abbrevFont{g}}
\newcommand*{\eg}{%
	\@ifnextchar{,}{\EG}%
		{\@ifnextchar{:}{\EG}%
			{\EG,\xspace}}%
}}{}%
\@ifundefined{ie}{
\newcommand{\IE}{\abbrevFont{i}\abbrevFont{e}}
\newcommand*{\ie}{%
	\@ifnextchar{,}{\IE}%
		{\@ifnextchar{:}{\IE}%
			{\IE,\xspace}}%
}}{}%
\@ifundefined{etc}{
\newcommand{\ETC}{\abbrevFont{etc}}
\newcommand*{\etc}{%
	\@ifnextchar{.}{\ETC}%
        {\ETC.\xspace}%
}}{}%
\@ifundefined{etal}{
\newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}}
\newcommand*{\etal}{%
	\@ifnextchar{.}{\protect\ETAL}%
		{\protect\ETAL.\xspace}%
}}{}%
\@ifundefined{viz}{
\newcommand{\VIZ}{\abbrevFont{viz}}
\newcommand*{\viz}{%
	\@ifnextchar{.}{\VIZ}%
		{\VIZ.\xspace}%
}}{}%
\makeatother

\newenvironment{cquote}{%
	\list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
	\item\relax
}{%
	\endlist
}% cquote

% CFA programming language, based on ANSI C (with some gcc additions)
\lstdefinelanguage{CFA}[ANSI]{C}{
	morekeywords={
		_Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, __attribute, __attribute__,
		auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__, __const, __const__,
		coroutine, disable, dtype, enable, exception, __extension__, fallthrough, fallthru, finally,
		__float80, float80, __float128, float128, forall, ftype, _Generic, _Imaginary, __imag, __imag__,
		inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
		otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread,
		_Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
		virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
	moredirectives={defined,include_next}%
}

\lstset{
language=CFA,
columns=fullflexible,
basicstyle=\linespread{0.9}\sf,							% reduce line spacing and use sanserif font
stringstyle=\tt,										% use typewriter font
tabsize=5,												% N space tabbing
xleftmargin=\parindentlnth,								% indent code to paragraph indentation
%mathescape=true,										% LaTeX math escape in CFA code $...$
escapechar=\$,											% LaTeX escape in CFA code
keepspaces=true,										%
showstringspaces=false,									% do not show spaces with cup
showlines=true,											% show blank lines at end of code
aboveskip=4pt,											% spacing above/below code block
belowskip=3pt,
% replace/adjust listing characters that look bad in sanserif
literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
	{~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
	{<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
	{<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex{\textrm{\textgreater}}}2,
moredelim=**[is][\color{red}]{`}{`},
}% lstset

% uC++ programming language, based on ANSI C++
\lstdefinelanguage{uC++}[ANSI]{C++}{
	morekeywords={
		_Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _CatchResume, _Cormonitor, _Coroutine, _Disable,
		_Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
		_Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
}
\lstdefinelanguage{Golang}{
	morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
	morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
		bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
	morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
	morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
	morekeywords=[5]{Println,Printf,Error,},
	sensitive=true,
	morecomment=[l]{//},
	morecomment=[s]{/*}{*/},
	morestring=[b]',
	morestring=[b]",
	morestring=[s]{`}{`},
}

\lstnewenvironment{cfa}[1][]
{\lstset{#1}}
{}
\lstnewenvironment{C++}[1][]                            % use C++ style
{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
{}
\lstnewenvironment{uC++}[1][]
{\lstset{#1}}
{}
\lstnewenvironment{Go}[1][]
{\lstset{#1}}
{}

% inline code @...@
\lstMakeShortInline@%

\let\OLDthebibliography\thebibliography
\renewcommand\thebibliography[1]{
  \OLDthebibliography{#1}
  \setlength{\parskip}{0pt}
  \setlength{\itemsep}{4pt plus 0.3ex}
}

\title{\texorpdfstring{Concurrency in \protect\CFA}{Concurrency in Cforall}}

\author[1]{Thierry Delisle}
\author[1]{Peter A. Buhr*}
\authormark{DELISLE \textsc{et al.}}

\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}

\corres{*Peter A. Buhr, Cheriton School of Computer Science, University of Waterloo, 200 University Avenue West, Waterloo, ON, N2L 3G1, Canada. \email{pabuhr{\char`\@}uwaterloo.ca}}

\fundingInfo{Natural Sciences and Engineering Research Council of Canada}

\abstract[Summary]{
\CFA is a modern, polymorphic, \emph{non-object-oriented} extension of the C programming language.
This paper discusses the design of the concurrency and parallelism features in \CFA, and the concurrent runtime-system.
These features are created from scratch as ISO C lacks concurrency, relying largely on the pthreads library.
Coroutines and lightweight (user) threads are introduced into the language.
In addition, monitors are added as a high-level mechanism for mutual exclusion and synchronization.
A unique contribution is allowing multiple monitors to be safely acquired simultaneously.
All features respect the expectations of C programmers, while being fully integrate with the \CFA polymorphic type-system and other language features.
Finally, experimental results are presented to compare the performance of the new features with similar mechanisms in other concurrent programming-languages.
}%

\keywords{concurrency, parallelism, coroutines, threads, monitors, runtime, C, Cforall}


\begin{document}
\linenumbers                                            % comment out to turn off line numbering

\maketitle


\section{Introduction}

This paper provides a minimal concurrency \newterm{Application Program Interface} (API) that is simple, efficient and can be used to build other concurrency features.
While the simplest concurrency system is a thread and a lock, this low-level approach is hard to master.
An easier approach for programmers is to support higher-level constructs as the basis of concurrency.
Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{Hochstein05}.
Examples of high-level approaches are task (work) based~\cite{TBB}, implicit threading~\cite{OpenMP}, monitors~\cite{Java}, channels~\cite{CSP,Go}, and message passing~\cite{Erlang,MPI}.

The following terminology is used.
A \newterm{thread} is a fundamental unit of execution that runs a sequence of code and requires a stack to maintain state.
Multiple simultaneous threads give rise to \newterm{concurrency}, which requires locking to ensure safe communication and access to shared data.
% Correspondingly, concurrency is defined as the concepts and challenges that occur when multiple independent (sharing memory, timing dependencies, \etc) concurrent threads are introduced.
\newterm{Locking}, and by extension \newterm{locks}, are defined as a mechanism to prevent progress of threads to provide safety.
\newterm{Parallelism} is running multiple threads simultaneously.
Parallelism implies \emph{actual} simultaneous execution, where concurrency only requires \emph{apparent} simultaneous execution.
As such, parallelism only affects performance, which is observed through differences in space and/or time at runtime.

Hence, there are two problems to be solved: concurrency and parallelism.
While these two concepts are often combined, they are distinct, requiring different tools~\cite[\S~2]{Buhr05a}.
Concurrency tools handle synchronization and mutual exclusion, while parallelism tools handle performance, cost and resource utilization.

The proposed concurrency API is implemented in a dialect of C, called \CFA.
The paper discusses how the language features are added to the \CFA translator with respect to parsing, semantic, and type checking, and the corresponding high-performance runtime-library to implement the concurrency features.


\section{\CFA Overview}

The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency.
Extended versions and explanation of the following code examples are available at the \CFA website~\cite{Cforall} or in Moss~\etal~\cite{Moss18}.

\CFA is an extension of ISO-C, and hence, supports all C paradigms.
%It is a non-object-oriented system-language, meaning most of the major abstractions have either no runtime overhead or can be opted out easily.
Like C, the basics of \CFA revolve around structures and routines.
Virtually all of the code generated by the \CFA translator respects C memory layouts and calling conventions.
While \CFA is not an object-oriented language, lacking the concept of a receiver (\eg @this@) and nominal inheritance-relationships, C does have a notion of objects: ``region of data storage in the execution environment, the contents of which can represent values''~\cite[3.15]{C11}.
While some \CFA features are common in object-oriented programming-languages, they are an independent capability allowing \CFA to adopt them while retaining a procedural paradigm.


\subsection{References}

\CFA provides multi-level rebindable references, as an alternative to pointers, which significantly reduces syntactic noise.
\begin{cfa}
int x = 1, y = 2, z = 3;
int * p1 = &x, ** p2 = &p1,  *** p3 = &p2,	$\C{// pointers to x}$
	`&` r1 = x,  `&&` r2 = r1,  `&&&` r3 = r2;	$\C{// references to x}$
int * p4 = &z, `&` r4 = z;

*p1 = 3; **p2 = 3; ***p3 = 3;       // change x
r1 =  3;     r2 = 3;      r3 = 3;        // change x: implicit dereferences *r1, **r2, ***r3
**p3 = &y; *p3 = &p4;                // change p1, p2
`&`r3 = &y; `&&`r3 = &`&`r4;             // change r1, r2: cancel implicit dereferences (&*)**r3, (&(&*)*)*r3, &(&*)r4
\end{cfa}
A reference is a handle to an object, like a pointer, but is automatically dereferenced the specified number of levels.
Referencing (address-of @&@) a reference variable cancels one of the implicit dereferences, until there are no more implicit references, after which normal expression behaviour applies.


\subsection{\texorpdfstring{\protect\lstinline{with} Statement}{with Statement}}
\label{s:WithStatement}

Heterogeneous data is aggregated into a structure/union.
To reduce syntactic noise, \CFA provides a @with@ statement (see Pascal~\cite[\S~4.F]{Pascal}) to elide aggregate field-qualification by opening a scope containing the field identifiers.
\begin{cquote}
\vspace*{-\baselineskip}%???
\lstDeleteShortInline@%
\begin{cfa}
struct S { char c; int i; double d; };
struct T { double m, n; };
// multiple aggregate parameters
\end{cfa}
\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
void f( S & s, T & t ) {
	`s.`c; `s.`i; `s.`d;
	`t.`m; `t.`n;
}
\end{cfa}
&
\begin{cfa}
void f( S & s, T & t ) `with ( s, t )` {
	c; i; d;		// no qualification
	m; n;
}
\end{cfa}
\end{tabular}
\lstMakeShortInline@%
\end{cquote}
Object-oriented programming languages only provide implicit qualification for the receiver.

In detail, the @with@ statement has the form:
\begin{cfa}
$\emph{with-statement}$:
	'with' '(' $\emph{expression-list}$ ')' $\emph{compound-statement}$
\end{cfa}
and may appear as the body of a routine or nested within a routine body.
Each expression in the expression-list provides a type and object.
The type must be an aggregate type.
(Enumerations are already opened.)
The object is the implicit qualifier for the open structure-fields.
All expressions in the expression list are open in parallel within the compound statement, which is different from Pascal, which nests the openings from left to right.


\subsection{Overloading}

\CFA maximizes the ability to reuse names via overloading to aggressively address the naming problem.
Both variables and routines may be overloaded, where selection is based on types, and number of returns (as in Ada~\cite{Ada}) and arguments.
\begin{cquote}
\vspace*{-\baselineskip}%???
\lstDeleteShortInline@%
\begin{cfa}
// selection based on type
\end{cfa}
\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
const short int `MIN` = -32768;
const int `MIN` = -2147483648;
const long int `MIN` = -9223372036854775808L;
\end{cfa}
&
\begin{cfa}
short int si = `MIN`;
int i = `MIN`;
long int li = `MIN`;
\end{cfa}
\end{tabular}
\begin{cfa}
// selection based on type and number of parameters
\end{cfa}
\begin{tabular}{@{}l@{\hspace{2.7\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
void `f`( void );
void `f`( char );
void `f`( int, double );
\end{cfa}
&
\begin{cfa}
`f`();
`f`( 'a' );
`f`( 3, 5.2 );
\end{cfa}
\end{tabular}
\begin{cfa}
// selection based on type and number of returns
\end{cfa}
\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
char `f`( int );
double `f`( int );
[char, double] `f`( int );
\end{cfa}
&
\begin{cfa}
char c = `f`( 3 );
double d = `f`( 3 );
[d, c] = `f`( 3 );
\end{cfa}
\end{tabular}
\lstMakeShortInline@%
\end{cquote}
Overloading is important for \CFA concurrency since the runtime system relies on creating different types to represent concurrency objects.
Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions to prevent name clashes.
As seen in Section~\ref{basics}, routine @main@ is heavily overloaded.

Variable overloading is useful in the parallel semantics of the @with@ statement for fields with the same name:
\begin{cfa}
struct S { int `i`; int j; double m; } s;
struct T { int `i`; int k; int m; } t;
with ( s, t ) {
	j + k;									$\C{// unambiguous, s.j + t.k}$
	m = 5.0;								$\C{// unambiguous, s.m = 5.0}$
	m = 1;									$\C{// unambiguous, t.m = 1}$
	int a = m;								$\C{// unambiguous, a = t.m }$
	double b = m;							$\C{// unambiguous, b = s.m}$
	int c = `s.i` + `t.i`;					$\C{// unambiguous, qualification}$
	(double)m;								$\C{// unambiguous, cast s.m}$
}
\end{cfa}
For parallel semantics, both @s.i@ and @t.i@ are visible the same type, so only @i@ is ambiguous without qualification.


\subsection{Operators}

Overloading also extends to operators.
Operator-overloading syntax creates a routine name with an operator symbol and question marks for the operands:
\begin{cquote}
\lstDeleteShortInline@%
\begin{tabular}{@{}ll@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
\begin{cfa}
int ++? (int op);
int ?++ (int op);
int `?+?` (int op1, int op2);
int ?<=?(int op1, int op2);
int ?=? (int & op1, int op2);
int ?+=?(int & op1, int op2);
\end{cfa}
&
\begin{cfa}
// unary prefix increment
// unary postfix increment
// binary plus
// binary less than
// binary assignment
// binary plus-assignment
\end{cfa}
&
\begin{cfa}
struct S { int i, j; };
S `?+?`( S op1, S op2) { // add two structures
	return (S){op1.i + op2.i, op1.j + op2.j};
}
S s1 = {1, 2}, s2 = {2, 3}, s3;
s3 = s1 `+` s2;		// compute sum: s3 == {2, 5}
\end{cfa}
\end{tabular}
\lstMakeShortInline@%
\end{cquote}
While concurrency does not use operator overloading directly, it provides an introduction for the syntax of constructors.


\subsection{Parametric Polymorphism}
\label{s:ParametricPolymorphism}

The signature feature of \CFA is parametric-polymorphic routines~\cite{} with routines generalized using a @forall@ clause (giving the language its name), which allow separately compiled routines to support generic usage over multiple types.
For example, the following sum routine works for any type that supports construction from 0 and addition:
\begin{cfa}
forall( otype T | { void `?{}`( T *, zero_t ); T `?+?`( T, T ); } ) // constraint type, 0 and +
T sum( T a[$\,$], size_t size ) {
	`T` total = { `0` };					$\C{// initialize by 0 constructor}$
	for ( size_t i = 0; i < size; i += 1 )
		total = total `+` a[i];				$\C{// select appropriate +}$
	return total;
}
S sa[5];
int i = sum( sa, 5 );						$\C{// use S's 0 construction and +}$
\end{cfa}

\CFA provides \newterm{traits} to name a group of type assertions, where the trait name allows specifying the same set of assertions in multiple locations, preventing repetition mistakes at each routine declaration:
\begin{cfa}
trait `sumable`( otype T ) {
	void `?{}`( T &, zero_t );				$\C{// 0 literal constructor}$
	T `?+?`( T, T );						$\C{// assortment of additions}$
	T ?+=?( T &, T );
	T ++?( T & );
	T ?++( T & );
};
forall( otype T `| sumable( T )` )			$\C{// use trait}$
T sum( T a[$\,$], size_t size );
\end{cfa}

Assertions can be @otype@ or @dtype@.
@otype@ refers to a ``complete'' object, \ie an object has a size, default constructor, copy constructor, destructor and an assignment operator.
@dtype@ only guarantees an object has a size and alignment.

Using the return type for discrimination, it is possible to write a type-safe @alloc@ based on the C @malloc@:
\begin{cfa}
forall( dtype T | sized(T) ) T * alloc( void ) { return (T *)malloc( sizeof(T) ); }
int * ip = alloc();							$\C{// select type and size from left-hand side}$
double * dp = alloc();
struct S {...} * sp = alloc();
\end{cfa}
where the return type supplies the type/size of the allocation, which is impossible in most type systems.


\subsection{Constructors / Destructors}

Object lifetime is a challenge in non-managed programming languages.
\CFA responds with \CC-like constructors and destructors:
\begin{cfa}
struct VLA { int len, * data; };			$\C{// variable length array of integers}$
void ?{}( VLA & vla ) with ( vla ) { len = 10;  data = alloc( len ); }  $\C{// default constructor}$
void ?{}( VLA & vla, int size, char fill ) with ( vla ) { len = size;  data = alloc( len, fill ); } // initialization
void ?{}( VLA & vla, VLA other ) { vla.len = other.len;  vla.data = other.data; } $\C{// copy, shallow}$
void ^?{}( VLA & vla ) with ( vla ) { free( data ); } $\C{// destructor}$
{
	VLA  x,            y = { 20, 0x01 },     z = y;	$\C{// z points to y}$
	//    x{};         y{ 20, 0x01 };          z{ z, y }; 
	^x{};									$\C{// deallocate x}$
	x{};									$\C{// reallocate x}$
	z{ 5, 0xff };							$\C{// reallocate z, not pointing to y}$
	^y{};									$\C{// deallocate y}$
	y{ x };									$\C{// reallocate y, points to x}$
	x{};									$\C{// reallocate x, not pointing to y}$
	//  ^z{};  ^y{};  ^x{};
}
\end{cfa}
Like \CC, construction is implicit on allocation (stack/heap) and destruction is implicit on deallocation.
The object and all their fields are constructed/destructed.
\CFA also provides @new@ and @delete@, which behave like @malloc@ and @free@, in addition to constructing and destructing objects:
\begin{cfa}
{	struct S s = {10};						$\C{// allocation, call constructor}$
	...
}											$\C{// deallocation, call destructor}$
struct S * s = new();						$\C{// allocation, call constructor}$
...
delete( s );								$\C{// deallocation, call destructor}$
\end{cfa}
\CFA concurrency uses object lifetime as a means of synchronization and/or mutual exclusion.


\section{Concurrency Basics}\label{basics}

At its core, concurrency is based on multiple call-stacks and scheduling threads executing on these stacks.
Multiple call stacks (or contexts) and a single thread of execution, called \newterm{coroutining}~\cite{Conway63,Marlin80}, does \emph{not} imply concurrency~\cite[\S~2]{Buhr05a}.
In coroutining, the single thread is self-scheduling across the stacks, so execution is deterministic, \ie given fixed inputs, the execution path to the outputs is fixed and predictable.
A \newterm{stackless} coroutine executes on the caller's stack~\cite{Python} but this approach is restrictive, \eg preventing modularization and supporting only iterator/generator-style programming;
a \newterm{stackfull} coroutine executes on its own stack, allowing full generality.
Only stackfull coroutines are a stepping-stone to concurrency.

The transition to concurrency, even for execution with a single thread and multiple stacks, occurs when coroutines also context switch to a scheduling oracle, introducing non-determinism from the coroutine perspective~\cite[\S~3]{Buhr05a}.
Therefore, a minimal concurrency system is possible using coroutines (see Section \ref{coroutine}) in conjunction with a scheduler to decide where to context switch next.
The resulting execution system now follows a cooperative threading-model, called \newterm{non-preemptive scheduling}.

Because the scheduler is special, it can either be a stackless or stackfull coroutine.
For stackless, the scheduler performs scheduling on the stack of the current coroutine and switches directly to the next coroutine, so there is one context switch.
For stackfull, the current coroutine switches to the scheduler, which performs scheduling, and it then switches to the next coroutine, so there are two context switches.
A stackfull scheduler is often used for simplicity and security, even through there is a slightly higher runtime-cost.

Regardless of the approach used, a subset of concurrency related challenges start to appear.
For the complete set of concurrency challenges to occur, the missing feature is \newterm{preemption}, where context switching occurs randomly between any two instructions, often based on a timer interrupt, called \newterm{preemptive scheduling}.
While a scheduler introduces uncertainty in the order of execution, preemption introduces uncertainty where context switches occur.
Interestingly, uncertainty is necessary for the runtime (operating) system to give the illusion of parallelism on a single processor and increase performance on multiple processors.
The reason is that only the runtime has complete knowledge about resources and how to best utilized them.
However, the introduction of unrestricted non-determinism results in the need for \newterm{mutual exclusion} and \newterm{synchronization} to restrict non-determinism for correctness;
otherwise, it is impossible to write meaningful programs.
Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows.


\subsection{\protect\CFA's Thread Building Blocks}

An important missing feature in C is threading\footnote{While the C11 standard defines a \protect\lstinline@threads.h@ header, it is minimal and defined as optional.
As such, library support for threading is far from widespread.
At the time of writing the paper, neither \protect\lstinline@gcc@ nor \protect\lstinline@clang@ support \protect\lstinline@threads.h@ in their standard libraries.}.
In modern programming languages, a lack of threading is unacceptable~\cite{Sutter05, Sutter05b}, and therefore existing and new programming languages must have tools for writing efficient concurrent programs to take advantage of parallelism.
As an extension of C, \CFA needs to express these concepts in a way that is as natural as possible to programmers familiar with imperative languages.
Furthermore, because C is a system-level language, programmers expect to choose precisely which features they need and which cost they are willing to pay.
Hence, concurrent programs should be written using high-level mechanisms, and only step down to lower-level mechanisms when performance bottlenecks are encountered.


\subsection{Coroutines: A Stepping Stone}\label{coroutine}

While the focus of this discussion is concurrency and parallelism, it is important to address coroutines, which are a significant building block of a concurrency system.
Coroutines are generalized routines allowing execution to be temporarily suspend and later resumed.
Hence, unlike a normal routine, a coroutine may not terminate when it returns to its caller, allowing it to be restarted with the values and execution location present at the point of suspension.
This capability is accomplish via the coroutine's stack, where suspend/resume context switch among stacks.
Because threading design-challenges are present in coroutines, their design effort is relevant, and this effort can be easily exposed to programmers giving them a useful new programming paradigm because a coroutine handles the class of problems that need to retain state between calls, \eg plugins, device drivers, and finite-state machines.
Therefore, the core \CFA coroutine-API for has two fundamental features: independent call-stacks and @suspend@/@resume@ operations.

For example, a problem made easier with coroutines is unbounded generators, \eg generating an infinite sequence of Fibonacci numbers, where Figure~\ref{f:C-fibonacci} shows conventional approaches for writing a Fibonacci generator in C.
\begin{displaymath}
\mathsf{fib}(n) = \left \{
\begin{array}{ll}
0					& n = 0		\\
1					& n = 1		\\
\mathsf{fib}(n-1) + \mathsf{fib}(n-2)	& n \ge 2	\\
\end{array}
\right.
\end{displaymath}
Figure~\ref{f:GlobalVariables} illustrates the following problems:
unique unencapsulated global variables necessary to retain state between calls;
only one Fibonacci generator;
execution state must be explicitly retained via explicit state variables.
Figure~\ref{f:ExternalState} addresses these issues:
unencapsulated program global variables become encapsulated structure variables;
unique global variables are replaced by multiple Fibonacci objects;
explicit execution state is removed by precomputing the first two Fibonacci numbers and returning $\mathsf{fib}(n-2)$.

\begin{figure}
\centering
\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`int f1, f2, state = 1;`   // single global variables
int fib() {
	int fn;
	`switch ( state )` {  // explicit execution state
	  case 1: fn = 0;  f1 = fn;  state = 2;  break;
	  case 2: fn = 1;  f2 = f1;  f1 = fn;  state = 3;  break;
	  case 3: fn = f1 + f2;  f2 = f1;  f1 = fn;  break;
	}
	return fn;
}
int main() {

	for ( int i = 0; i < 10; i += 1 ) {
		printf( "%d\n", fib() );
	}
}
\end{cfa}
\end{lrbox}

\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
#define FIB_INIT `{ 0, 1 }`
typedef struct { int f2, f1; } Fib;
int fib( Fib * f ) {

	int ret = f->f2;
	int fn = f->f1 + f->f2;
	f->f2 = f->f1; f->f1 = fn;

	return ret;
}
int main() {
	Fib f1 = FIB_INIT, f2 = FIB_INIT;
	for ( int i = 0; i < 10; i += 1 ) {
		printf( "%d %d\n", fib( &f1 ), fib( &f2 ) );
	}
}
\end{cfa}
\end{lrbox}

\subfloat[3 States: global variables]{\label{f:GlobalVariables}\usebox\myboxA}
\qquad
\subfloat[1 State: external variables]{\label{f:ExternalState}\usebox\myboxB}
\caption{C Fibonacci Implementations}
\label{f:C-fibonacci}

\bigskip

\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`coroutine` Fib { int fn; };
void main( Fib & fib ) with( fib ) {
	int f1, f2;
	fn = 0;  f1 = fn;  `suspend()`;
	fn = 1;  f2 = f1;  f1 = fn;  `suspend()`;
	for ( ;; ) {
		fn = f1 + f2;  f2 = f1;  f1 = fn;  `suspend()`;
	}
}
int next( Fib & fib ) with( fib ) {
	`resume( fib );`
	return fn;
}
int main() {
	Fib f1, f2;
	for ( int i = 1; i <= 10; i += 1 ) {
		sout | next( f1 ) | next( f2 ) | endl;
	}
}
\end{cfa}
\end{lrbox}
\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`coroutine` Fib { int ret; };
void main( Fib & f ) with( fib ) {
	int fn, f1 = 1, f2 = 0;
	for ( ;; ) {
		ret = f2;

		fn = f1 + f2;  f2 = f1;  f1 = fn; `suspend();`
	}
}
int next( Fib & fib ) with( fib ) {
	`resume( fib );`
	return ret;
}






\end{cfa}
\end{lrbox}
\subfloat[3 States, internal variables]{\label{f:Coroutine3States}\usebox\myboxA}
\qquad\qquad
\subfloat[1 State, internal variables]{\label{f:Coroutine1State}\usebox\myboxB}
\caption{\CFA Coroutine Fibonacci Implementations}
\label{f:fibonacci-cfa}
\end{figure}

Using a coroutine, it is possible to express the Fibonacci formula directly without any of the C problems.
Figure~\ref{f:Coroutine3States} creates a @coroutine@ type:
\begin{cfa}
`coroutine` Fib { int fn; };
\end{cfa}
which provides communication, @fn@, for the \newterm{coroutine main}, @main@, which runs on the coroutine stack, and possibly multiple interface routines @next@.
Like the structure in Figure~\ref{f:ExternalState}, the coroutine type allows multiple instances, where instances of this type are passed to the (overloaded) coroutine main.
The coroutine main's stack holds the state for the next generation, @f1@ and @f2@, and the code has the three suspend points, representing the three states in the Fibonacci formula, to context switch back to the caller's resume.
The interface routine @next@, takes a Fibonacci instance and context switches to it using @resume@;
on restart, the Fibonacci field, @fn@, contains the next value in the sequence, which is returned.
The first @resume@ is special because it cocalls the coroutine at its coroutine main and allocates the stack;
when the coroutine main returns, its stack is deallocated.
Hence, @Fib@ is an object at creation, transitions to a coroutine on its first resume, and transitions back to an object when the coroutine main finishes.
Figure~\ref{f:Coroutine1State} shows the coroutine version of the C version in Figure~\ref{f:ExternalState}.
Coroutine generators are called \newterm{output coroutines} because values are only returned.

Figure~\ref{f:CFAFmt} shows an \newterm{input coroutine}, @Format@, for restructuring text into groups of characters of fixed-size blocks.
For example, the input of the left is reformatted into the output on the right.
\begin{quote}
\tt
\begin{tabular}{@{}l|l@{}}
\multicolumn{1}{c|}{\textbf{\textrm{input}}} & \multicolumn{1}{c}{\textbf{\textrm{output}}} \\
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
&
\begin{tabular}[t]{@{}lllll@{}}
abcd	& efgh	& ijkl	& mnop	& qrst	\\
uvwx	& yzab	& cdef	& ghij	& klmn	\\
opqr	& stuv	& wxyz	&		&
\end{tabular}
\end{tabular}
\end{quote}
The example takes advantage of resuming a coroutine in the constructor to prime the loops so the first character sent for formatting appears inside the nested loops.
The destruction provides a newline if formatted text ends with a full line.
Figure~\ref{f:CFmt} shows the C equivalent formatter, where the loops of the coroutine are flatten (linearized) and rechecked on each call because execution location is not retained between calls.

\begin{figure}
\centering
\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`coroutine` Format {
	char ch;   // used for communication
	int g, b;  // global because used in destructor
};
void main( Format & fmt ) with( fmt ) {
	for ( ;; ) {	
		for ( g = 0; g < 5; g += 1 ) {      // group
			for ( b = 0; b < 4; b += 1 ) { // block
				`suspend();`
				sout | ch;              // separator
			}
			sout | "  ";               // separator
		}
		sout | endl;
	}
}
void ?{}( Format & fmt ) { `resume( fmt );` }
void ^?{}( Format & fmt ) with( fmt ) {
	if ( g != 0 || b != 0 ) sout | endl;
}
void format( Format & fmt ) {
	`resume( fmt );`
}
int main() {
	Format fmt;
	eof: for ( ;; ) {
		sin | fmt.ch;
	  if ( eof( sin ) ) break eof;
		format( fmt );
	}
}
\end{cfa}
\end{lrbox}

\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
struct Format {
	char ch;
	int g, b;
};
void format( struct Format * fmt ) {
	if ( fmt->ch != -1 ) {      // not EOF ?
		printf( "%c", fmt->ch );
		fmt->b += 1;
		if ( fmt->b == 4 ) {  // block
			printf( "  " );      // separator
			fmt->b = 0;
			fmt->g += 1;
		}
		if ( fmt->g == 5 ) {  // group
			printf( "\n" );     // separator
			fmt->g = 0;
		}
	} else {
		if ( fmt->g != 0 || fmt->b != 0 ) printf( "\n" );
	}
}
int main() {
	struct Format fmt = { 0, 0, 0 };
	for ( ;; ) {
		scanf( "%c", &fmt.ch );
	  if ( feof( stdin ) ) break;
		format( &fmt );
	}
	fmt.ch = -1;
	format( &fmt );
}
\end{cfa}
\end{lrbox}
\subfloat[\CFA Coroutine]{\label{f:CFAFmt}\usebox\myboxA}
\qquad
\subfloat[C Linearized]{\label{f:CFmt}\usebox\myboxB}
\caption{Formatting text into lines of 5 blocks of 4 characters.}
\label{f:fmt-line}
\end{figure}

The previous examples are \newterm{asymmetric (semi) coroutine}s because one coroutine always calls a resuming routine for another coroutine, and the resumed coroutine always suspends back to its last resumer, similar to call/return for normal routines
However, there is no stack growth because @resume@/@suspend@ context switch to existing stack-frames rather than create new ones.
\newterm{Symmetric (full) coroutine}s have a coroutine call a resuming routine for another coroutine, which eventually forms a resuming-call cycle.
(The trivial cycle is a coroutine resuming itself.)
This control flow is similar to recursion for normal routines, but again there is no stack growth from the context switch.

\begin{figure}
\centering
\lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $
\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
`coroutine` Prod {
	Cons & c;
	int N, money, receipt;
};
void main( Prod & prod ) with( prod ) {
	// 1st resume starts here
	for ( int i = 0; i < N; i += 1 ) {
		int p1 = random( 100 ), p2 = random( 100 );
		sout | p1 | " " | p2 | endl;
		int status = delivery( c, p1, p2 );
		sout | " $" | money | endl | status | endl;
		receipt += 1;
	}
	stop( c );
	sout | "prod stops" | endl;
}
int payment( Prod & prod, int money ) {
	prod.money = money;
	`resume( prod );`
	return prod.receipt;
}
void start( Prod & prod, int N, Cons &c ) {
	&prod.c = &c;
	prod.[N, receipt] = [N, 0];
	`resume( prod );`
}
int main() {
	Prod prod;
	Cons cons = { prod };
	start( prod, 5, cons );
}
\end{cfa}
&
\begin{cfa}
`coroutine` Cons {
	Prod & p;
	int p1, p2, status;
	_Bool done;
};
void ?{}( Cons & cons, Prod & p ) {
	&cons.p = &p;
	cons.[status, done ] = [0, false];
}
void ^?{}( Cons & cons ) {}
void main( Cons & cons ) with( cons ) {
	// 1st resume starts here
	int money = 1, receipt;
	for ( ; ! done; ) {
		sout | p1 | " " | p2 | endl | " $" | money | endl;
		status += 1;
		receipt = payment( p, money );
		sout | " #" | receipt | endl;
		money += 1;
	}
	sout | "cons stops" | endl;
}
int delivery( Cons & cons, int p1, int p2 ) {
	cons.[p1, p2] = [p1, p2];
	`resume( cons );`
	return cons.status;
}
void stop( Cons & cons ) {
	cons.done = true;
	`resume( cons );`
}
\end{cfa}
\end{tabular}
\caption{Producer / consumer: resume-resume cycle, bi-directional communication}
\label{f:ProdCons}
\end{figure}

Figure~\ref{f:ProdCons} shows a producer/consumer symmetric-coroutine performing bi-directional communication.
Since the solution involves a full-coroutining cycle, the program main creates one coroutine in isolation, passes this coroutine to its partner, and closes the cycle at the call to @start@.
The @start@ routine communicates both the number of elements to be produced and the consumer into the producer's coroutine structure.
Then the @resume@ to @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
@prod@'s coroutine main starts, creates local variables that are retained between coroutine activations, and executes $N$ iterations, each generating two random values, calling the consumer to deliver the values, and printing the status returned from the consumer.

The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
For the first resume, @cons@'s stack is initialized, creating local variables retained between subsequent activations of the coroutine.
The consumer iterates until the @done@ flag is set, prints, increments status, and calls back to the producer via @payment@, and on return from @payment@, prints the receipt from the producer and increments @money@ (inflation).
The call from the consumer to the @payment@ introduces the cycle between producer and consumer.
When @payment@ is called, the consumer copies values into the producer's communication variable and a resume is executed.
The context switch restarts the producer at the point where it was last context switched, so it continues in @delivery@ after the resume.

@delivery@ returns the status value in @prod@'s coroutine main, where the status is printed.
The loop then repeats calling @delivery@, where each call resumes the consumer coroutine.
The context switch to the consumer continues in @payment@.
The consumer increments and returns the receipt to the call in @cons@'s coroutine main.
The loop then repeats calling @payment@, where each call resumes the producer coroutine.

After iterating $N$ times, the producer calls @stop@.
The @done@ flag is set to stop the consumer's execution and a resume is executed.
The context switch restarts @cons@ in @payment@ and it returns with the last receipt.
The consumer terminates its loops because @done@ is true, its @main@ terminates, so @cons@ transitions from a coroutine back to an object, and @prod@ reactivates after the resume in @stop@.
@stop@ returns and @prod@'s coroutine main terminates.
The program main restarts after the resume in @start@.
@start@ returns and the program main terminates.


\subsection{Coroutine Implementation}

A significant implementation challenge for coroutines (and threads, see section \ref{threads}) is adding extra fields and executing code after/before the coroutine constructor/destructor and coroutine main to create/initialize/de-initialize/destroy extra fields and the stack.
There are several solutions to this problem and the chosen option forced the \CFA coroutine design.

Object-oriented inheritance provides extra fields and code in a restricted context, but it requires programmers to explicitly perform the inheritance:
\begin{cfa}
struct mycoroutine $\textbf{\textsf{inherits}}$ baseCoroutine { ... }
\end{cfa}
and the programming language (and possibly its tool set, \eg debugger) may need to understand @baseCoroutine@ because of the stack.
Furthermore, the execution of constructs/destructors is in the wrong order for certain operations, \eg for threads;
\eg, if the thread is implicitly started, it must start \emph{after} all constructors, because the thread relies on a completely initialized object, but the inherited constructor runs \emph{before} the derived.

An alternatively is composition:
\begin{cfa}
struct mycoroutine {
	... // declarations
	baseCoroutine dummy; // composition, last declaration
}
\end{cfa}
which also requires an explicit declaration that must be the last one to ensure correct initialization order.
However, there is nothing preventing wrong placement or multiple declarations.

For coroutines as for threads, many implementations are based on routine pointers or routine objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
For example, Boost implements coroutines in terms of four functor object-types:
\begin{cfa}
asymmetric_coroutine<>::pull_type
asymmetric_coroutine<>::push_type
symmetric_coroutine<>::call_type
symmetric_coroutine<>::yield_type
\end{cfa}
Similarly, the canonical threading paradigm is often based on routine pointers, \eg @pthread@~\cite{pthreads}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}.
However, the generic thread-handle (identifier) is limited (few operations), unless it is wrapped in a custom type.
\begin{cfa}
void mycor( coroutine_t cid, void * arg ) {
	int * value = (int *)arg;				$\C{// type unsafe, pointer-size only}$
	// Coroutine body
}
int main() {
	int input = 0, output;
	coroutine_t cid = coroutine_create( &mycor, (void *)&input ); $\C{// type unsafe, pointer-size only}$
	coroutine_resume( cid, (void *)input, (void **)&output ); $\C{// type unsafe, pointer-size only}$
}
\end{cfa}
Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda-based coroutines adds very little.

Note, the type @coroutine_t@ must be an abstract handle to the coroutine, because the coroutine descriptor and its stack are non-copyable.
Copying the coroutine descriptor results in copies being out of date with the current state of the stack.
Correspondingly, copying the stack results is copies being out of date with coroutine descriptor, and pointers in the stack being out of date to data on the stack.
(There is no mechanism in C to find all stack-specific pointers and update them as part of a copy.)

The selected approach is to use language support by introducing a new kind of aggregate (structure):
\begin{cfa}
coroutine Fibonacci {
	int fn; // communication variables
};
\end{cfa}
The @coroutine@ keyword means the compiler (and tool set) can find and inject code where needed.
The downside of this approach is that it makes coroutine a special case in the language.
Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language.
Furthermore, implementing coroutines without language supports also displays the power of a programming language.
While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can still be constructed without using the language support.
The reserved keyword eases use for the common cases.

Part of the mechanism to generalize coroutines is using a \CFA trait, which defines a coroutine as anything satisfying the trait @is_coroutine@, and this trait is used to restrict coroutine-manipulation routines:
\begin{cfa}
trait is_coroutine( `dtype` T ) {
	void main( T & );
	coroutine_desc * get_coroutine( T & );
};
forall( `dtype` T | is_coroutine(T) ) void suspend( T & );
forall( `dtype` T | is_coroutine(T) ) void resume( T & );
\end{cfa}
The @dtype@ property of the trait ensures the coroutine descriptor is non-copyable, so all coroutines must be passed by reference (pointer).
The routine definitions ensures there is a statically-typed @main@ routine that is the starting point (first stack frame) of a coroutine, and a mechanism to get (read) the currently executing coroutine handle.
The @main@ routine has no return value or additional parameters because the coroutine type allows an arbitrary number of interface routines with corresponding arbitrary typed input/output values versus fixed ones.
The generic routines @suspend@ and @resume@ can be redefined, but any object passed to them is a coroutine since it must satisfy the @is_coroutine@ trait to compile.
The advantage of this approach is that users can easily create different types of coroutines, for example, changing the memory layout of a coroutine is trivial when implementing the @get_coroutine@ routine, and possibly redefining @suspend@ and @resume@.
The \CFA keyword @coroutine@ implicitly implements the getter and forward declarations required for implementing the coroutine main:
\begin{cquote}
\begin{tabular}{@{}ccc@{}}
\begin{cfa}
coroutine MyCor {
	int value;

};
\end{cfa}
&
{\Large $\Rightarrow$}
&
\begin{tabular}{@{}ccc@{}}
\begin{cfa}
struct MyCor {
	int value;
	coroutine_desc cor;
};
\end{cfa}
&
\begin{cfa}
static inline coroutine_desc *
get_coroutine( MyCor & this ) {
	return &this.cor;
}
\end{cfa}
&
\begin{cfa}
void main( MyCor * this );



\end{cfa}
\end{tabular}
\end{tabular}
\end{cquote}
The combination of these two approaches allows an easy and concise specification to coroutining (and concurrency) for normal users, while more advanced users have tighter control on memory layout and initialization.


\subsection{Thread Interface}
\label{threads}

Both user and kernel threads are supported, where user threads provide concurrency and kernel threads provide parallelism.
Like coroutines and for the same design reasons, the selected approach for user threads is to use language support by introducing a new kind of aggregate (structure) and a \CFA trait:
\begin{cquote}
\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
\begin{cfa}
thread myThread {
	// communication variables
};


\end{cfa}
&
\begin{cfa}
trait is_thread( `dtype` T ) {
      void main( T & );
      thread_desc * get_thread( T & );
      void ^?{}( T & `mutex` );
};
\end{cfa}
\end{tabular}
\end{cquote}
(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitors}.)
Like a coroutine, the statically-typed @main@ routine is the starting point (first stack frame) of a user thread.
The difference is that a coroutine borrows a thread from its caller, so the first thread resuming a coroutine creates an instance of @main@;
whereas, a user thread receives its own thread from the runtime system, which starts in @main@ as some point after the thread constructor is run.\footnote{
The \lstinline@main@ routine is already a special routine in C (where the program begins), so it is a natural extension of the semantics to use overloading to declare mains for different coroutines/threads (the normal main being the main of the initial thread).}
No return value or additional parameters are necessary for this routine because the task type allows an arbitrary number of interface routines with corresponding arbitrary typed input/output values.

\begin{comment} % put in appendix with coroutine version ???
As such the @main@ routine of a thread can be defined as
\begin{cfa}
thread foo {};

void main(foo & this) {
	sout | "Hello World!" | endl;
}
\end{cfa}

In this example, threads of type @foo@ start execution in the @void main(foo &)@ routine, which prints @"Hello World!".@ While this paper encourages this approach to enforce strongly typed programming, users may prefer to use the routine-based thread semantics for the sake of simplicity.
With the static semantics it is trivial to write a thread type that takes a routine pointer as a parameter and executes it on its stack asynchronously.
\begin{cfa}
typedef void (*voidRtn)(int);

thread RtnRunner {
	voidRtn func;
	int arg;
};

void ?{}(RtnRunner & this, voidRtn inRtn, int arg) {
	this.func = inRtn;
	this.arg  = arg;
}

void main(RtnRunner & this) {
	// thread starts here and runs the routine
	this.func( this.arg );
}

void hello(/*unused*/ int) {
	sout | "Hello World!" | endl;
}

int main() {
	RtnRunner f = {hello, 42};
	return 0?
}
\end{cfa}
A consequence of the strongly typed approach to main is that memory layout of parameters and return values to/from a thread are now explicitly specified in the \textbf{API}.
\end{comment}

For user threads to be useful, it must be possible to start and stop the underlying thread, and wait for it to complete execution.
While using an API such as @fork@ and @join@ is relatively common, such an interface is awkward and unnecessary.
A simple approach is to use allocation/deallocation principles, and have threads implicitly @fork@ after construction and @join@ before destruction.
\begin{cfa}
thread World {};
void main( World & this ) {
	sout | "World!" | endl;
}
int main() {
	World w`[10]`;							$\C{// implicit forks after creation}$
	sout | "Hello " | endl;					$\C{// "Hello " and 10 "World!" printed concurrently}$
}											$\C{// implicit joins before destruction}$
\end{cfa}
This semantics ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
This tree-structure (lattice) create/delete from C block-structure is generalized by using dynamic allocation, so threads can outlive the scope in which they are created, much like dynamically allocating memory lets objects outlive the scope in which they are created.
\begin{cfa}
int main() {
	MyThread * heapLived;
	{
		MyThread blockLived;				$\C{// fork block-based thread}$
		heapLived = `new`( MyThread );		$\C{// fork heap-based thread}$
		...
	}										$\C{// join block-based thread}$
	...
	`delete`( heapLived );					$\C{// join heap-based thread}$
}
\end{cfa}
The heap-based approach allows arbitrary thread-creation topologies, with respect to fork/join-style concurrency.

Figure~\ref{s:ConcurrentMatrixSummation} shows concurrently adding the rows of a matrix and then totalling the subtotals sequential, after all the row threads have terminated.
The program uses heap-based threads because each thread needs different constructor values.
(Python provides a simple iteration mechanism to initialize array elements to different values allowing stack allocation.)
The allocation/deallocation pattern appears unusual because allocated objects are immediately deleted without any intervening code.
However, for threads, the deletion provides implicit synchronization, which is the intervening code.
While the subtotals are added in linear order rather than completion order, which slight inhibits concurrency, the computation is restricted by the critical-path thread (\ie the thread that takes the longest), and so any inhibited concurrency is very small as totalling the subtotals is trivial.

\begin{figure}
\begin{cfa}
thread Adder {
    int * row, cols, & subtotal;			$\C{// communication}$
};
void ?{}( Adder & adder, int row[], int cols, int & subtotal ) {
    adder.[ row, cols, &subtotal ] = [ row, cols, &subtotal ];
}
void main( Adder & adder ) with( adder ) {
    subtotal = 0;
    for ( int c = 0; c < cols; c += 1 ) {
		subtotal += row[c];
    }
}
int main() {
    const int rows = 10, cols = 1000;
    int matrix[rows][cols], subtotals[rows], total = 0;
    // read matrix
    Adder * adders[rows];
    for ( int r = 0; r < rows; r += 1 ) {	$\C{// start threads to sum rows}$
		adders[r] = new( matrix[r], cols, &subtotals[r] );
    }
    for ( int r = 0; r < rows; r += 1 ) {	$\C{// wait for threads to finish}$
		delete( adders[r] );				$\C{// termination join}$
		total += subtotals[r];				$\C{// total subtotal}$
    }
    sout | total | endl;
}
\end{cfa}
\caption{Concurrent Matrix Summation}
\label{s:ConcurrentMatrixSummation}
\end{figure}


\section{Mutual Exclusion / Synchronization}

Uncontrolled non-deterministic execution is meaningless.
To reestablish meaningful execution requires mechanisms to reintroduce determinism (\ie restrict non-determinism), called mutual exclusion and synchronization, where mutual exclusion is an access-control mechanism on data shared by threads, and synchronization is a timing relationship among threads~\cite[\S~4]{Buhr05a}.
Since many deterministic challenges appear with the use of mutable shared state, some languages/libraries disallow it, \eg Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, Akka~\cite{Akka} (Scala).
In these paradigms, interaction among concurrent objects is performed by stateless message-passing~\cite{Thoth,Harmony,V-Kernel} or other paradigms closely relate to networking concepts (\eg channels~\cite{CSP,Go}).
However, in call/return-based languages, these approaches force a clear distinction (\ie introduce a new programming paradigm) between regular and concurrent computation (\ie routine call versus message passing).
Hence, a programmer must learn and manipulate two sets of design patterns.
While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
In contrast, approaches based on statefull models more closely resemble the standard call/return programming-model, resulting in a single programming paradigm.

At the lowest level, concurrent control is implemented by atomic operations, upon which different kinds of locks mechanism are constructed, \eg semaphores~\cite{Dijkstra68b}, barriers, and path expressions~\cite{Campbell74}.
However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}.
A newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
While this approach is pursued in hardware~\cite{Nakaike15} and system languages, like \CC~\cite{Cpp-Transactions}, the performance and feature set is still too restrictive to be the main concurrency paradigm for system languages, which is why it was rejected as the core paradigm for concurrency in \CFA.

One of the most natural, elegant, and efficient mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor}.
First proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}, many concurrent programming-languages provide monitors as an explicit language construct: \eg Concurrent Pascal~\cite{ConcurrentPascal}, Mesa~\cite{Mesa}, Modula~\cite{Modula-2}, Turing~\cite{Turing:old}, Modula-3~\cite{Modula-3}, NeWS~\cite{NeWS}, Emerald~\cite{Emerald}, \uC~\cite{Buhr92a} and Java~\cite{Java}.
In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as mutex locks or semaphores to simulate monitors.
For these reasons, \CFA selected monitors as the core high-level concurrency-construct, upon which higher-level approaches can be easily constructed.


\subsection{Mutual Exclusion}

A group of instructions manipulating a specific instance of shared data that must be performed atomically is called an (individual) \newterm{critical-section}~\cite{Dijkstra65}.
The generalization is called a \newterm{group critical-section}~\cite{Joung00}, where multiple tasks with the same session may use the resource simultaneously, but different sessions may not use the resource simultaneously.
The readers/writer problem~\cite{Courtois71} is an instance of a group critical-section, where readers have the same session and all writers have a unique session.
\newterm{Mutual exclusion} enforces that the correct kind and number of threads are using a critical section.

However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
Methods range from low-level locks, which are fast and flexible but require significant attention for correctness, to higher-level concurrency techniques, which sacrifice some performance to improve ease of use.
Ease of use comes by either guaranteeing some problems cannot occur (\eg deadlock free), or by offering a more explicit coupling between shared data and critical section.
For example, the \CC @std::atomic<T>@ offers an easy way to express mutual-exclusion on a restricted set of operations (\eg reading/writing) for numerical types.
However, a significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock.
Easing composability is another feature higher-level mutual-exclusion mechanisms can offer.


\subsection{Synchronization}

Synchronization enforces relative ordering of execution, and synchronization tools provide numerous mechanisms to establish these timing relationships.
Low-level synchronization primitives offer good performance and flexibility at the cost of ease of use;
higher-level mechanisms often simplify usage by adding better coupling between synchronization and data (\eg message passing), or offering a simpler solution to otherwise involved challenges, \eg barrier lock.
Often synchronization is used to order access to a critical section, \eg ensuring a reader thread is the next kind of thread to enter a critical section.
If a writer thread is scheduled for next access, but another reader thread acquires the critical section first, that reader has \newterm{barged}.
Barging can result in staleness/freshness problems, where a reader barges ahead of a writer and reads temporally stale data, or a writer barges ahead of another writer overwriting data with a fresh value preventing the previous value from ever being read (lost computation).
Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
This challenge is often split into two different approaches: barging avoidance and barging prevention.
Algorithms that allow a barger, but divert it until later using current synchronization state (flags), are avoiding the barger;
algorithms that preclude a barger from entering during synchronization in the critical section prevent barging completely.
Techniques like baton-pass locks~\cite{Andrews89} between threads instead of unconditionally releasing locks is an example of barging prevention.


\section{Monitors}
\label{s:Monitors}

A \textbf{monitor} is a set of routines that ensure mutual exclusion when accessing shared state.
More precisely, a monitor is a programming technique that binds mutual exclusion to routine scope, as opposed to locks, where mutual-exclusion is defined by acquire/release calls, independent of lexical context (analogous to block and heap storage allocation).
The strong association with the call/return paradigm eases programmability, readability and maintainability, at a slight cost in flexibility and efficiency.

Note, like coroutines/threads, both locks and monitors require an abstract handle to reference them, because at their core, both mechanisms are manipulating non-copyable shared state.
Copying a lock is insecure because it is possible to copy an open lock and then use the open copy when the original lock is closed to simultaneously access the shared data.
Copying a monitor is secure because both the lock and shared data are copies, but copying the shared data is meaningless because it no longer represents a unique entity.
As for coroutines/tasks, a non-copyable (@dtype@) trait is used to capture this requirement, so all locks/monitors must be passed by reference (pointer).
\begin{cfa}
trait is_monitor( `dtype` T ) {
	monitor_desc * get_monitor( T & );
	void ^?{}( T & mutex );
};
\end{cfa}


\subsection{Mutex Acquisition}
\label{s:MutexAcquisition}

While correctness implicitly implies a monitor's mutual exclusion is acquired and released, there are implementation options about when and where the locking/unlocking occurs.
(Much of this discussion also applies to basic locks.)
For example, a monitor may need to be passed through multiple helper routines before it becomes necessary to acquire the monitor mutual-exclusion.
\begin{cfa}[morekeywords=nomutex]
monitor Aint { int cnt; };					$\C{// atomic integer counter}$
void ?{}( Aint & `nomutex` this ) with( this ) { cnt = 0; } $\C{// constructor}$
int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions}$
void ?{}( int & this, Aint & `mutex`$\(_{opt}\)$ v ) { this = v.cnt; }
int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; }
int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$
\end{cfa}
The @Aint@ constructor, @?{}@, uses the \lstinline[morekeywords=nomutex]@nomutex@ qualifier indicating mutual exclusion is unnecessary during construction because an object is inaccessible (private) until after it is initialized.
(While a constructor may publish its address into a global variable, doing so generates a race-condition.)
The conversion operators for initializing and assigning with a normal integer only need @mutex@, if reading/writing the implementation type is not atomic.
Finally, the prefix increment operato, @++?@, is normally @mutex@ to protect the incrementing from race conditions, unless there is an atomic increment instruction for the implementation type.

The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics, which is similar to the \CC template @std::atomic@.
\begin{cfa}
Aint x, y, z;
++x; ++y; ++z;								$\C{// safe increment by multiple threads}$
x = 2; y = 2; z = 2;						$\C{// conversions}$
int i = x, j = y, k = z;
i = x; j = y; k = z;
\end{cfa}

For maximum usability, monitors have \newterm{multi-acquire} semantics allowing a thread to acquire it multiple times without deadlock.
For example, atomically printing the contents of a binary tree:
\begin{cfa}
monitor Tree {
	Tree * left, right;
	// value
};
void print( Tree & mutex tree ) {			$\C{// prefix traversal}$
	// write value
	print( tree->left );					$\C{// multiply acquire monitor lock on each recursion}$
	print( tree->right );
}
\end{cfa}

Mandatory monitor qualifiers have the benefit of being self-documented, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameter is redundant.
Instead, one of qualifier semantics can be the default, and the other required.
For example, assume the safe @mutex@ option for a monitor parameter because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
On the other hand, assuming \lstinline[morekeywords=nomutex]@nomutex@ is the \emph{normal} parameter behaviour, stating explicitly ``this parameter is not special''.
Providing a default qualifier implies knowing whether a parameter is a monitor.
Since \CFA relies heavily on traits as an abstraction mechanism, the distinction between a type that is a monitor and a type that looks like a monitor can become blurred.
For this reason, \CFA requires programmers to identify the kind of parameter with the @mutex@ keyword and uses no keyword to mean \lstinline[morekeywords=nomutex]@nomutex@.

The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@.
Given:
\begin{cfa}
monitor M { ... }
int f1( M & mutex m );
int f2( M * mutex m );
int f3( M * mutex m[] );
int f4( stack( M * ) & mutex m );
\end{cfa}
the issue is that some of these parameter types are composed of multiple objects.
For @f1@, there is only a single parameter object.
Adding indirection in @f2@ still identifies a single object.
However, the matrix in @f3@ introduces multiple objects.
While shown shortly, multiple acquisition is possible;
however array lengths are often unknown in C.
This issue is exacerbated in @f4@, where the data structure must be safely traversed to acquire all of its elements.

To make the issue tractable, \CFA only acquires one monitor per parameter with at most one level of indirection.
However, the C type-system has an ambiguity with respects to arrays.
Is the argument for @f2@ a single object or an array of objects?
If it is an array, only the first element of the array is acquired, which seems unsafe;
hence, @mutex@ is disallowed for array parameters.
\begin{cfa}
int f1( M & mutex m );						$\C{// allowed: recommended case}$
int f2( M * mutex m );						$\C{// disallowed: could be an array}$
int f3( M mutex m[$\,$] );					$\C{// disallowed: array length unknown}$
int f4( M ** mutex m );						$\C{// disallowed: could be an array}$
int f5( M * mutex m[$\,$] );				$\C{// disallowed: array length unknown}$
\end{cfa}
% Note, not all array routines have distinct types: @f2@ and @f3@ have the same type, as do @f4@ and @f5@.
% However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.

For object-oriented monitors, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
\CFA has no receiver, and hence, must use an explicit mechanism to specify which object has mutual exclusion acquired.
A positive consequence of this design decision is the ability to support multi-monitor routines.
\begin{cfa}
int f( M & mutex x, M & mutex y );		$\C{// multiple monitor parameter of any type}$
M m1, m2;
f( m1, m2 );
\end{cfa}
(While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.)
In practice, writing multi-locking routines that do not deadlocks is tricky.
Having language support for such a feature is therefore a significant asset for \CFA.

The capability to acquire multiple locks before entering a critical section is called \newterm{bulk acquire}.
In previous example, \CFA guarantees the order of acquisition is consistent across calls to different routines using the same monitors as arguments.
This consistent ordering means acquiring multiple monitors is safe from deadlock.
However, users can force the acquiring order.
For example, notice the use of @mutex@/\lstinline[morekeywords=nomutex]@nomutex@ and how this affects the acquiring order:
\begin{cfa}
void foo( M & mutex m1, M & mutex m2 );		$\C{// acquire m1 and m2}$
void bar( M & mutex m1, M & /* nomutex */ m2 ) { $\C{// acquire m1}$
	... foo( m1, m2 ); ...					$\C{// acquire m2}$
}
void baz( M & /* nomutex */ m1, M & mutex m2 ) { $\C{// acquire m2}$
	... foo( m1, m2 ); ...					$\C{// acquire m1}$
}
\end{cfa}
The multi-acquire semantics allows @bar@ or @baz@ to acquire a monitor lock and reacquire it in @foo@.
In the calls to @bar@ and @baz@, the monitors are acquired in opposite order.

However, such use leads to lock acquiring order problems resulting in deadlock~\cite{Lister77}, where detecting it requires dynamically tracking of monitor calls, and dealing with it requires implement rollback semantics~\cite{Dice10}.
In \CFA, safety is guaranteed by using bulk acquire of all monitors to shared objects, whereas other monitor systems provide no aid.
While \CFA provides only a partial solution, the \CFA partial solution handles many useful cases.
\begin{cfa}
monitor Bank { ... };
void deposit( Bank & `mutex` b, int deposit );
void transfer( Bank & `mutex` mybank, Bank & `mutex` yourbank, int me2you) {
	deposit( mybank, `-`me2you );			$\C{// debit}$
	deposit( yourbank, me2you );			$\C{// credit}$
}
\end{cfa}
This example shows a trivial solution to the bank-account transfer problem~\cite{BankTransfer}.
Without multi- and bulk acquire, the solution to this problem requires careful engineering.


\subsection{\protect\lstinline|mutex| statement} \label{mutex-stmt}

The monitor call-semantics associate all locking semantics to routines.
Like Java, \CFA offers an alternative @mutex@ statement to reduce refactoring and naming.
\begin{cquote}
\begin{tabular}{@{}c|@{\hspace{\parindentlnth}}c@{}}
routine call & @mutex@ statement \\
\begin{cfa}
monitor M {};
void foo( M & mutex m1, M & mutex m2 ) {
	// critical section
}
void bar( M & m1, M & m2 ) {
	foo( m1, m2 );
}
\end{cfa}
&
\begin{cfa}

void bar( M & m1, M & m2 ) {
	mutex( m1, m2 ) {	// remove refactoring and naming
		// critical section
	}
}

\end{cfa}
\end{tabular}
\end{cquote}


\section{Internal Scheduling}
\label{s:InternalScheduling}

While monitor mutual-exclusion provides safe access to shared data, the monitor data may indicate that a thread accessing it cannot proceed.
For example, Figure~\ref{f:GenericBoundedBuffer} shows a bounded buffer that may be full/empty so produce/consumer threads must block.
Leaving the monitor and trying again (busy waiting) is impractical for high-level programming.
Monitors eliminate busy waiting by providing internal synchronization to schedule threads needing access to the shared data, where the synchronization is blocking (threads are parked) versus spinning.
Synchronization is generally achieved with internal~\cite{Hoare74} or external~\cite[\S~2.9.2]{uC++} scheduling, where \newterm{scheduling} defines which thread acquires the critical section next.
\newterm{Internal scheduling} is characterized by each thread entering the monitor and making an individual decision about proceeding or blocking, while \newterm{external scheduling} is characterized by an entering thread making a decision about proceeding for itself and on behalf of other threads attempting entry.

Figure~\ref{f:BBInt} shows a \CFA bounded-buffer with internal scheduling, where producers/consumers enter the monitor, see the buffer is full/empty, and block on an appropriate condition lock, @full@/@empty@.
The @wait@ routine atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the routine's parameter list.
The appropriate condition lock is signalled to unblock an opposite kind of thread after an element is inserted/removed from the buffer.
Signalling is unconditional, because signalling an empty condition lock does nothing.
Signalling semantics cannot have the signaller and signalled thread in the monitor simultaneously, which means:
\begin{enumerate}
\item
The signalling thread returns immediately, and the signalled thread continues.
\item
The signalling thread continues and the signalled thread is marked for urgent unblocking at the next scheduling point (exit/wait).
\item
The signalling thread blocks but is marked for urgrent unblocking at the next scheduling point and the signalled thread continues.
\end{enumerate}
The first approach is too restrictive, as it precludes solving a reasonable class of problems (\eg dating service).
\CFA supports the next two semantics as both are useful.
Finally, while it is common to store a @condition@ as a field of the monitor, in \CFA, a @condition@ variable can be created/stored independently.
Furthermore, a condition variable is tied to a \emph{group} of monitors on first use (called \newterm{branding}), which means that using internal scheduling with distinct sets of monitors requires one condition variable per set of monitors.

\begin{figure}
\centering
\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
forall( otype T ) { // distribute forall
	monitor Buffer {
		`condition` full, empty;
		int front, back, count;
		T elements[10];
	};
	void ?{}( Buffer(T) & buffer ) with(buffer) {
		[front, back, count] = 0;
	}

	void insert( Buffer(T) & mutex buffer, T elem )
				with(buffer) {
		if ( count == 10 ) `wait( empty )`;
		// insert elem into buffer
		`signal( full )`;
	}
	T remove( Buffer(T) & mutex buffer ) with(buffer) {
		if ( count == 0 ) `wait( full )`;
		// remove elem from buffer
		`signal( empty )`;
		return elem;
	}
}
\end{cfa}
\end{lrbox}

\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
forall( otype T ) { // distribute forall
	monitor Buffer {

		int front, back, count;
		T elements[10];
	};
	void ?{}( Buffer(T) & buffer ) with(buffer) {
		[front, back, count] = 0;
	}
	T remove( Buffer(T) & mutex buffer ); // forward
	void insert( Buffer(T) & mutex buffer, T elem )
				with(buffer) {
		if ( count == 10 ) `waitfor( remove, buffer )`;
		// insert elem into buffer

	}
	T remove( Buffer(T) & mutex buffer ) with(buffer) {
		if ( count == 0 ) `waitfor( insert, buffer )`;
		// remove elem from buffer

		return elem;
	}
}
\end{cfa}
\end{lrbox}

\subfloat[Internal Scheduling]{\label{f:BBInt}\usebox\myboxA}
%\qquad
\subfloat[External Scheduling]{\label{f:BBExt}\usebox\myboxB}
\caption{Generic Bounded-Buffer}
\label{f:GenericBoundedBuffer}
\end{figure}

Figure~\ref{f:BBExt} shows a \CFA bounded-buffer with external scheduling, where producers/consumers detecting a full/empty buffer block and prevent more producers/consumers from entering the monitor until the buffer has a free/empty slot.
External scheduling is controlled by the @waitfor@ statement, which atomically blocks the calling thread, releases the monitor lock, and restricts the routine calls that can next acquire mutual exclusion.
If the buffer is full, only calls to @remove@ can acquire the buffer, and if the buffer is empty, only calls to @insert@ can acquire the buffer.
Threads making calls to routines that are currently excluded block outside (external) of the monitor on a calling queue, versus blocking on condition queues inside (internal) of the monitor.

For internal scheduling, non-blocking signalling (as in the producer/consumer example) is used when the signaller is providing the cooperation for a waiting thread;
the signaller enters the monitor and changes state, detects a waiting threads that can use the state, performs a non-blocking signal on the condition queue for the waiting thread, and exits the monitor to run concurrently.
The waiter unblocks next, takes the state, and exits the monitor.
Blocking signalling is the reverse, where the waiter is providing the cooperation for the signalling thread;
the signaller enters the monitor, detects a waiting thread providing the necessary state, performs a blocking signal to place it on the urgent queue and unblock the waiter.
The waiter changes state and exits the monitor, and the signaller unblocks next from the urgent queue to take the state.

Figure~\ref{f:DatingService} shows a dating service demonstrating the two forms of signalling: non-blocking and blocking.
The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers.
A thread blocks until an appropriate partner arrives.
The complexity is exchanging phone number in the monitor, 
While the non-barging monitor prevents a caller from stealing a phone number, the monitor mutual-exclusion property 

The dating service is an example of a monitor that cannot be written using external scheduling because:

The example in table \ref{tbl:datingservice} highlights the difference in behaviour.
As mentioned, @signal@ only transfers ownership once the current critical section exits; this behaviour requires additional synchronization when a two-way handshake is needed.
To avoid this explicit synchronization, the @condition@ type offers the @signal_block@ routine, which handles the two-way handshake as shown in the example.
This feature removes the need for a second condition variables and simplifies programming.
Like every other monitor semantic, @signal_block@ uses barging prevention, which means mutual-exclusion is baton-passed both on the front end and the back end of the call to @signal_block@, meaning no other thread can acquire the monitor either before or after the call.

\begin{figure}
\centering
\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
enum { CCodes = 20 };
monitor DS {
	int GirlPhNo, BoyPhNo;
	condition Girls[CCodes], Boys[CCodes];
	condition exchange;
};
int girl( DS & mutex ds, int phNo, int ccode ) {
	if ( is_empty( Boys[ccode] ) ) {
		wait( Girls[ccode] );
		GirlPhNo = phNo;
		exchange.signal();
	} else {
		GirlPhNo = phNo;
		signal( Boys[ccode] );
		exchange.wait();
	} // if
	return BoyPhNo;
}
int boy( DS & mutex ds, int phNo, int ccode ) {
	// as above with boy/girl interchanged
}
\end{cfa}
\end{lrbox}

\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]

monitor DS {
	int GirlPhNo, BoyPhNo;
	condition Girls[CCodes], Boys[CCodes];

};
int girl( DS & mutex ds, int phNo, int ccode ) {
	if ( is_empty( Boys[ccode] ) ) { // no compatible
		wait( Girls[ccode] ); // wait for boy
		GirlPhNo = phNo; // make phone number available

	} else {
		GirlPhNo = phNo; // make phone number available
		signal_block( Boys[ccode] ); // restart boy

	} // if
	return BoyPhNo;
}
int boy( DS & mutex ds, int phNo, int ccode ) {
	// as above with boy/girl interchanged
}
\end{cfa}
\end{lrbox}

\subfloat[\lstinline@signal@]{\label{f:DatingSignal}\usebox\myboxA}
\qquad
\subfloat[\lstinline@signal_block@]{\label{f:DatingSignalBlock}\usebox\myboxB}
\caption{Dating service. }
\label{f:DatingService}
\end{figure}

Both internal and external scheduling extend to multiple monitors in a natural way.
\begin{cquote}
\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
\begin{cfa}
monitor M { `condition e`; ... };
void foo( M & mutex m1, M & mutex m2 ) {
	... wait( `e` ); ...   // wait( e, m1, m2 )
	... wait( `e, m1` ); ...
	... wait( `e, m2` ); ...
}
\end{cfa}
&
\begin{cfa}
void rtn$\(_1\)$( M & mutex m1, M & mutex m2 );
void rtn$\(_2\)$( M & mutex m1 );
void bar( M & mutex m1, M & mutex m2 ) {
	... waitfor( `rtn` ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\), m1, m2 )}$
	... waitfor( `rtn, m1` ); ... // $\LstCommentStyle{waitfor( rtn\(_2\), m1 )}$
}
\end{cfa}
\end{tabular}
\end{cquote}
For @wait( e )@, the default semantics is to atomically block the signaller and release all acquired mutex types in the parameter list, \ie @wait( e, m1, m2 )@.
To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
Wait statically verifies the released monitors are the acquired mutex-parameters so unconditional release is safe.
Finally, a signaller,
\begin{cfa}
void baz( M & mutex m1, M & mutex m2 ) {
	... signal( e ); ...
}
\end{cfa}
must have acquired monitor locks that are greater than or equal to the number of locks for the waiting thread signalled from the front of the condition queue.
In general, the signaller does not know the order of waiting threads, so in general, it must acquire the maximum number of mutex locks for the worst-case waiting thread.

Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex types in the parameter list, \ie @waitfor( rtn, m1, m2 )@.
To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn, m1 )@.
Waitfor statically verifies the released monitors are the same as the acquired mutex-parameters of the given routine or routine pointer.
To statically verify the released monitors match with the accepted routine's mutex parameters, the routine (pointer) prototype must be accessible.

Given the ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock.
\begin{cfa}
void foo( M & mutex m1, M & mutex m2 ) {
	... wait( `e, m1` ); ...				$\C{// release m1, keeping m2 acquired )}$
void baz( M & mutex m1, M & mutex m2 ) {	$\C{// must acquire m1 and m2 )}$
	... signal( `e` ); ...
\end{cfa}
The @wait@ only releases @m1@ so the signalling thread cannot acquire both @m1@ and @m2@ to  enter @baz@ to get to the @signal@.
While deadlock issues can occur with multiple/nesting acquisition, this issue results from the fact that locks, and by extension monitors, are not perfectly composable.

Finally, an important aspect of monitor implementation is barging, \ie can calling threads barge ahead of signalled threads?
If barging is allowed, synchronization between a singller and signallee is difficult, often requiring multiple unblock/block cycles (looping around a wait rechecking if a condition is met).
\begin{quote}
However, we decree that a signal operation be followed immediately by resumption of a waiting program, without possibility of an intervening procedure call from yet a third program.
It is only in this way that a waiting program has an absolute guarantee that it can acquire the resource just released by the signalling program without any danger that a third program will interpose a monitor entry and seize the resource instead.~\cite[p.~550]{Hoare74}
\end{quote}
\CFA scheduling \emph{precludes} barging, which simplifies synchronization among threads in the monitor and increases correctness.
For example, there are no loops in either bounded buffer solution in Figure~\ref{f:GenericBoundedBuffer}.
Supporting barging prevention as well as extending internal scheduling to multiple monitors is the main source of complexity in the design and implementation of \CFA concurrency.


\subsection{Barging Prevention}

Figure~\ref{f:BargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signalling semantics.
The complexity begins at the end of the inner @mutex@ statement, where the semantics of internal scheduling need to be extended for multiple monitors.
The problem is that bulk acquire is used in the inner @mutex@ statement where one of the monitors is already acquired.
When the signalling thread reaches the end of the inner @mutex@ statement, it should transfer ownership of @m1@ and @m2@ to the waiting threads to prevent barging into the outer @mutex@ statement by another thread.
However, both the signalling and waiting thread W1 still need monitor @m1@.

\begin{figure}
\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
monitor M m1, m2;
condition c;
mutex( m1 ) { // $\LstCommentStyle{\color{red}outer}$
	...
	mutex( m1, m2 ) { // $\LstCommentStyle{\color{red}inner}$
		... `signal( c )`; ...
		// m1, m2 acquired
	} // $\LstCommentStyle{\color{red}release m2}$
	// m1 acquired
} // release m1
\end{cfa}
\end{lrbox}

\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]


mutex( m1 ) {
	...
	mutex( m1, m2 ) {
		... `wait( c )`; // block and release m1, m2
		// m1, m2 acquired
	} // $\LstCommentStyle{\color{red}release m2}$
	// m1 acquired
} // release m1
\end{cfa}
\end{lrbox}

\newbox\myboxC
\begin{lrbox}{\myboxC}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]


mutex( m2 ) {
	... `wait( c )`; ...
	// m2 acquired
} // $\LstCommentStyle{\color{red}release m2}$




\end{cfa}
\end{lrbox}

\begin{cquote}
\subfloat[Signalling Thread]{\label{f:SignallingThread}\usebox\myboxA}
\hspace{2\parindentlnth}
\subfloat[Waiting Thread (W1)]{\label{f:WaitingThread}\usebox\myboxB}
\hspace{2\parindentlnth}
\subfloat[Waiting Thread (W2)]{\label{f:OtherWaitingThread}\usebox\myboxC}
\end{cquote}
\caption{Barging Prevention}
\label{f:BargingPrevention}
\end{figure}

One scheduling solution is for the signaller to keep ownership of all locks until the last lock is ready to be transferred, because this semantics fits most closely to the behaviour of single-monitor scheduling.
However, Figure~\ref{f:OtherWaitingThread} shows this solution is complex depending on other waiters, resulting is choices when the signaller finishes the inner mutex-statement.
The singaller can retain @m2@ until completion of the outer mutex statement and pass the locks to waiter W1, or it can pass @m2@ to waiter W2 after completing the inner mutex-statement, while continuing to hold @m1@.
In the latter case, waiter W2 must eventually pass @m2@ to waiter W1, which is complex because W2 may have waited before W1 so it is unaware of W1.
Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.

While a number of approaches were examined~\cite[\S~4.3]{Delisle18}, the solution chosen for \CFA is a novel techique called \newterm{partial signalling}.
Signalled threads are moved to an urgent queue and the waiter at the front defines the set of monitors necessary for it to unblock.
Partial signalling transfers ownership of monitors to the front waiter.
When the signaller thread exits or waits in the monitor the front waiter is unblocked if all its monitors are released.
This solution has the benefit that complexity is encapsulated into only two actions: passing monitors to the next owner when they should be released and conditionally waking threads if all conditions are met.

\begin{comment}
Figure~\ref{f:dependency} shows a slightly different example where a third thread is waiting on monitor @A@, using a different condition variable.
Because the third thread is signalled when secretly holding @B@, the goal  becomes unreachable.
Depending on the order of signals (listing \ref{f:dependency} line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen:

\paragraph{Case 1: thread $\alpha$ goes first.} In this case, the problem is that monitor @A@ needs to be passed to thread $\beta$ when thread $\alpha$ is done with it.
\paragraph{Case 2: thread $\beta$ goes first.} In this case, the problem is that monitor @B@ needs to be retained and passed to thread $\alpha$ along with monitor @A@, which can be done directly or possibly using thread $\beta$ as an intermediate.
\\

Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order.
However, regardless of the answer, users can move line \ref{line:signal-a} before line \ref{line:signal-ab} and get the reverse effect for listing \ref{f:dependency}.

In both cases, the threads need to be able to distinguish, on a per monitor basis, which ones need to be released and which ones need to be transferred, which means knowing when to release a group becomes complex and inefficient (see next section) and therefore effectively precludes this approach.


\subsubsection{Dependency graphs}

\begin{figure}
\begin{multicols}{3}
Thread $\alpha$
\begin{cfa}[numbers=left, firstnumber=1]
acquire A
	acquire A & B
		wait A & B
	release A & B
release A
\end{cfa}
\columnbreak
Thread $\gamma$
\begin{cfa}[numbers=left, firstnumber=6, escapechar=|]
acquire A
	acquire A & B
		|\label{line:signal-ab}|signal A & B
	|\label{line:release-ab}|release A & B
	|\label{line:signal-a}|signal A
|\label{line:release-a}|release A
\end{cfa}
\columnbreak
Thread $\beta$
\begin{cfa}[numbers=left, firstnumber=12, escapechar=|]
acquire A
	wait A
|\label{line:release-aa}|release A
\end{cfa}
\end{multicols}
\begin{cfa}[caption={Pseudo-code for the three thread example.},label={f:dependency}]
\end{cfa}
\begin{center}
\input{dependency}
\end{center}
\caption{Dependency graph of the statements in listing \ref{f:dependency}}
\label{fig:dependency}
\end{figure}

In listing \ref{f:int-bulk-cfa}, there is a solution that satisfies both barging prevention and mutual exclusion.
If ownership of both monitors is transferred to the waiter when the signaller releases @A & B@ and then the waiter transfers back ownership of @A@ back to the signaller when it releases it, then the problem is solved (@B@ is no longer in use at this point).
Dynamically finding the correct order is therefore the second possible solution.
The problem is effectively resolving a dependency graph of ownership requirements.
Here even the simplest of code snippets requires two transfers and has a super-linear complexity.
This complexity can be seen in listing \ref{f:explosion}, which is just a direct extension to three monitors, requires at least three ownership transfer and has multiple solutions.
Furthermore, the presence of multiple solutions for ownership transfer can cause deadlock problems if a specific solution is not consistently picked; In the same way that multiple lock acquiring order can cause deadlocks.
\begin{figure}
\begin{multicols}{2}
\begin{cfa}
acquire A
	acquire B
		acquire C
			wait A & B & C
		release C
	release B
release A
\end{cfa}

\columnbreak

\begin{cfa}
acquire A
	acquire B
		acquire C
			signal A & B & C
		release C
	release B
release A
\end{cfa}
\end{multicols}
\begin{cfa}[caption={Extension to three monitors of listing \ref{f:int-bulk-cfa}},label={f:explosion}]
\end{cfa}
\end{figure}

Given the three threads example in listing \ref{f:dependency}, figure \ref{fig:dependency} shows the corresponding dependency graph that results, where every node is a statement of one of the three threads, and the arrows the dependency of that statement (\eg $\alpha1$ must happen before $\alpha2$).
The extra challenge is that this dependency graph is effectively post-mortem, but the runtime system needs to be able to build and solve these graphs as the dependencies unfold.
Resolving dependency graphs being a complex and expensive endeavour, this solution is not the preferred one.

\subsubsection{Partial Signalling} \label{partial-sig}
\end{comment}


\section{External scheduling} \label{extsched}

An alternative to internal scheduling is external scheduling (see Table~\ref{tbl:sched}).

\begin{comment}
\begin{table}
\begin{tabular}{|c|c|c|}
Internal Scheduling & External Scheduling & Go\\
\hline
\begin{uC++}[tabsize=3]
_Monitor Semaphore {
	condition c;
	bool inUse;
public:
	void P() {
		if(inUse)
			wait(c);
		inUse = true;
	}
	void V() {
		inUse = false;
		signal(c);
	}
}
\end{uC++}&\begin{uC++}[tabsize=3]
_Monitor Semaphore {

	bool inUse;
public:
	void P() {
		if(inUse)
			_Accept(V);
		inUse = true;
	}
	void V() {
		inUse = false;

	}
}
\end{uC++}&\begin{Go}[tabsize=3]
type MySem struct {
	inUse bool
	c     chan bool
}

// acquire
func (s MySem) P() {
	if s.inUse {
		select {
		case <-s.c:
		}
	}
	s.inUse = true
}

// release
func (s MySem) V() {
	s.inUse = false

	// This actually deadlocks
	// when single thread
	s.c <- false
}
\end{Go}
\end{tabular}
\caption{Different forms of scheduling.}
\label{tbl:sched}
\end{table}
\end{comment}

This method is more constrained and explicit, which helps users reduce the non-deterministic nature of concurrency.
Indeed, as the following examples demonstrate, external scheduling allows users to wait for events from other threads without the concern of unrelated events occurring.
External scheduling can generally be done either in terms of control flow (\eg Ada with @accept@, \uC with @_Accept@) or in terms of data (\eg Go with channels).
Of course, both of these paradigms have their own strengths and weaknesses, but for this project, control-flow semantics was chosen to stay consistent with the rest of the languages semantics.
Two challenges specific to \CFA arise when trying to add external scheduling with loose object definitions and multiple-monitor routines.
The previous example shows a simple use @_Accept@ versus @wait@/@signal@ and its advantages.
Note that while other languages often use @accept@/@select@ as the core external scheduling keyword, \CFA uses @waitfor@ to prevent name collisions with existing socket \textbf{api}s.

For the @P@ member above using internal scheduling, the call to @wait@ only guarantees that @V@ is the last routine to access the monitor, allowing a third routine, say @isInUse()@, acquire mutual exclusion several times while routine @P@ is waiting.
On the other hand, external scheduling guarantees that while routine @P@ is waiting, no other routine than @V@ can acquire the monitor.

% ======================================================================
% ======================================================================
\subsection{Loose Object Definitions}
% ======================================================================
% ======================================================================
In \uC, a monitor class declaration includes an exhaustive list of monitor operations.
Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user:

\begin{cfa}
monitor A {};

void f(A & mutex a);
void g(A & mutex a) {
	waitfor(f); // Obvious which f() to wait for
}

void f(A & mutex a, int); // New different F added in scope
void h(A & mutex a) {
	waitfor(f); // Less obvious which f() to wait for
}
\end{cfa}

Furthermore, external scheduling is an example where implementation constraints become visible from the interface.
Here is the cfa-code for the entering phase of a monitor:
\begin{center}
\begin{tabular}{l}
\begin{cfa}
	if monitor is free
		enter
	elif already own the monitor
		continue
	elif monitor accepts me
		enter
	else
		block
\end{cfa}
\end{tabular}
\end{center}
For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions.
However, a fast check for @monitor accepts me@ is much harder to implement depending on the constraints put on the monitors.
Indeed, monitors are often expressed as an entry queue and some acceptor queue as in Figure~\ref{fig:ClassicalMonitor}.

\begin{figure}
\centering
\subfloat[Classical Monitor] {
\label{fig:ClassicalMonitor}
{\resizebox{0.45\textwidth}{!}{\input{monitor}}}
}% subfloat
\qquad
\subfloat[bulk acquire Monitor] {
\label{fig:BulkMonitor}
{\resizebox{0.45\textwidth}{!}{\input{ext_monitor}}}
}% subfloat
\caption{External Scheduling Monitor}
\end{figure}

There are other alternatives to these pictures, but in the case of the left picture, implementing a fast accept check is relatively easy.
Restricted to a fixed number of mutex members, N, the accept check reduces to updating a bitmask when the acceptor queue changes, a check that executes in a single instruction even with a fairly large number (\eg 128) of mutex members.
This approach requires a unique dense ordering of routines with an upper-bound and that ordering must be consistent across translation units.
For OO languages these constraints are common, since objects only offer adding member routines consistently across translation units via inheritance.
However, in \CFA users can extend objects with mutex routines that are only visible in certain translation unit.
This means that establishing a program-wide dense-ordering among mutex routines can only be done in the program linking phase, and still could have issues when using dynamically shared objects.

The alternative is to alter the implementation as in Figure~\ref{fig:BulkMonitor}.
Here, the mutex routine called is associated with a thread on the entry queue while a list of acceptable routines is kept separate.
Generating a mask dynamically means that the storage for the mask information can vary between calls to @waitfor@, allowing for more flexibility and extensions.
Storing an array of accepted routine pointers replaces the single instruction bitmask comparison with dereferencing a pointer followed by a linear search.
Furthermore, supporting nested external scheduling (\eg listing \ref{f:nest-ext}) may now require additional searches for the @waitfor@ statement to check if a routine is already queued.

\begin{figure}
\begin{cfa}[caption={Example of nested external scheduling},label={f:nest-ext}]
monitor M {};
void foo( M & mutex a ) {}
void bar( M & mutex b ) {
	// Nested in the waitfor(bar, c) call
	waitfor(foo, b);
}
void baz( M & mutex c ) {
	waitfor(bar, c);
}

\end{cfa}
\end{figure}

Note that in the right picture, tasks need to always keep track of the monitors associated with mutex routines, and the routine mask needs to have both a routine pointer and a set of monitors, as is discussed in the next section.
These details are omitted from the picture for the sake of simplicity.

At this point, a decision must be made between flexibility and performance.
Many design decisions in \CFA achieve both flexibility and performance, for example polymorphic routines add significant flexibility but inlining them means the optimizer can easily remove any runtime cost.
Here, however, the cost of flexibility cannot be trivially removed.
In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be  hard to write.
This decision is based on the assumption that writing fast but inflexible locks is closer to a solved problem than writing locks that are as flexible as external scheduling in \CFA.

% ======================================================================
% ======================================================================
\subsection{Multi-Monitor Scheduling}
% ======================================================================
% ======================================================================

External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax.
Even in the simplest possible case, some new semantics needs to be established:
\begin{cfa}
monitor M {};

void f(M & mutex a);

void g(M & mutex b, M & mutex c) {
	waitfor(f); // two monitors M => unknown which to pass to f(M & mutex)
}
\end{cfa}
The obvious solution is to specify the correct monitor as follows:

\begin{cfa}
monitor M {};

void f(M & mutex a);

void g(M & mutex a, M & mutex b) {
	// wait for call to f with argument b
	waitfor(f, b);
}
\end{cfa}
This syntax is unambiguous.
Both locks are acquired and kept by @g@.
When routine @f@ is called, the lock for monitor @b@ is temporarily transferred from @g@ to @f@ (while @g@ still holds lock @a@).
This behaviour can be extended to the multi-monitor @waitfor@ statement as follows.

\begin{cfa}
monitor M {};

void f(M & mutex a, M & mutex b);

void g(M & mutex a, M & mutex b) {
	// wait for call to f with arguments a and b
	waitfor(f, a, b);
}
\end{cfa}

Note that the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired in the routine. @waitfor@ used in any other context is undefined behaviour.

An important behaviour to note is when a set of monitors only match partially:

\begin{cfa}
mutex struct A {};

mutex struct B {};

void g(A & mutex a, B & mutex b) {
	waitfor(f, a, b);
}

A a1, a2;
B b;

void foo() {
	g(a1, b); // block on accept
}

void bar() {
	f(a2, b); // fulfill cooperation
}
\end{cfa}
While the equivalent can happen when using internal scheduling, the fact that conditions are specific to a set of monitors means that users have to use two different condition variables.
In both cases, partially matching monitor sets does not wakeup the waiting thread.
It is also important to note that in the case of external scheduling the order of parameters is irrelevant; @waitfor(f,a,b)@ and @waitfor(f,b,a)@ are indistinguishable waiting condition.

% ======================================================================
% ======================================================================
\subsection{\protect\lstinline|waitfor| Semantics}
% ======================================================================
% ======================================================================

Syntactically, the @waitfor@ statement takes a routine identifier and a set of monitors.
While the set of monitors can be any list of expressions, the routine name is more restricted because the compiler validates at compile time the validity of the routine type and the parameters used with the @waitfor@ statement.
It checks that the set of monitors passed in matches the requirements for a routine call.
Figure~\ref{f:waitfor} shows various usages of the waitfor statement and which are acceptable.
The choice of the routine type is made ignoring any non-@mutex@ parameter.
One limitation of the current implementation is that it does not handle overloading, but overloading is possible.
\begin{figure}
\begin{cfa}[caption={Various correct and incorrect uses of the waitfor statement},label={f:waitfor}]
monitor A{};
monitor B{};

void f1( A & mutex );
void f2( A & mutex, B & mutex );
void f3( A & mutex, int );
void f4( A & mutex, int );
void f4( A & mutex, double );

void foo( A & mutex a1, A & mutex a2, B & mutex b1, B & b2 ) {
	A * ap = & a1;
	void (*fp)( A & mutex ) = f1;

	waitfor(f1, a1);     // Correct : 1 monitor case
	waitfor(f2, a1, b1); // Correct : 2 monitor case
	waitfor(f3, a1);     // Correct : non-mutex arguments are ignored
	waitfor(f1, *ap);    // Correct : expression as argument

	waitfor(f1, a1, b1); // Incorrect : Too many mutex arguments
	waitfor(f2, a1);     // Incorrect : Too few mutex arguments
	waitfor(f2, a1, a2); // Incorrect : Mutex arguments don't match
	waitfor(f1, 1);      // Incorrect : 1 not a mutex argument
	waitfor(f9, a1);     // Incorrect : f9 routine does not exist
	waitfor(*fp, a1 );   // Incorrect : fp not an identifier
	waitfor(f4, a1);     // Incorrect : f4 ambiguous

	waitfor(f2, a1, b2); // Undefined behaviour : b2 not mutex
}
\end{cfa}
\end{figure}

Finally, for added flexibility, \CFA supports constructing a complex @waitfor@ statement using the @or@, @timeout@ and @else@.
Indeed, multiple @waitfor@ clauses can be chained together using @or@; this chain forms a single statement that uses baton pass to any routine that fits one of the routine+monitor set passed in.
To enable users to tell which accepted routine executed, @waitfor@s are followed by a statement (including the null statement @;@) or a compound statement, which is executed after the clause is triggered.
A @waitfor@ chain can also be followed by a @timeout@, to signify an upper bound on the wait, or an @else@, to signify that the call should be non-blocking, which checks for a matching routine call already arrived and otherwise continues.
Any and all of these clauses can be preceded by a @when@ condition to dynamically toggle the accept clauses on or off based on some current state.
Figure~\ref{f:waitfor2} demonstrates several complex masks and some incorrect ones.

\begin{figure}
\lstset{language=CFA,deletedelim=**[is][]{`}{`}}
\begin{cfa}
monitor A{};

void f1( A & mutex );
void f2( A & mutex );

void foo( A & mutex a, bool b, int t ) {
	waitfor(f1, a);							$\C{// Correct : blocking case}$

	waitfor(f1, a) {						$\C{// Correct : block with statement}$
		sout | "f1" | endl;
	}
	waitfor(f1, a) {						$\C{// Correct : block waiting for f1 or f2}$
		sout | "f1" | endl;
	} or waitfor(f2, a) {
		sout | "f2" | endl;
	}
	waitfor(f1, a); or else;				$\C{// Correct : non-blocking case}$

	waitfor(f1, a) {						$\C{// Correct : non-blocking case}$
		sout | "blocked" | endl;
	} or else {
		sout | "didn't block" | endl;
	}
	waitfor(f1, a) {						$\C{// Correct : block at most 10 seconds}$
		sout | "blocked" | endl;
	} or timeout( 10`s) {
		sout | "didn't block" | endl;
	}
	// Correct : block only if b == true if b == false, don't even make the call
	when(b) waitfor(f1, a);

	// Correct : block only if b == true if b == false, make non-blocking call
	waitfor(f1, a); or when(!b) else;

	// Correct : block only of t > 1
	waitfor(f1, a); or when(t > 1) timeout(t); or else;

	// Incorrect : timeout clause is dead code
	waitfor(f1, a); or timeout(t); or else;

	// Incorrect : order must be waitfor [or waitfor... [or timeout] [or else]]
	timeout(t); or waitfor(f1, a); or else;
}
\end{cfa}
\caption{Correct and incorrect uses of the or, else, and timeout clause around a waitfor statement}
\label{f:waitfor2}
\end{figure}

% ======================================================================
% ======================================================================
\subsection{Waiting For The Destructor}
% ======================================================================
% ======================================================================
An interesting use for the @waitfor@ statement is destructor semantics.
Indeed, the @waitfor@ statement can accept any @mutex@ routine, which includes the destructor (see section \ref{data}).
However, with the semantics discussed until now, waiting for the destructor does not make any sense, since using an object after its destructor is called is undefined behaviour.
The simplest approach is to disallow @waitfor@ on a destructor.
However, a more expressive approach is to flip ordering of execution when waiting for the destructor, meaning that waiting for the destructor allows the destructor to run after the current @mutex@ routine, similarly to how a condition is signalled.
\begin{figure}
\begin{cfa}[caption={Example of an executor which executes action in series until the destructor is called.},label={f:dtor-order}]
monitor Executer {};
struct  Action;

void ^?{}   (Executer & mutex this);
void execute(Executer & mutex this, const Action & );
void run    (Executer & mutex this) {
	while(true) {
		   waitfor(execute, this);
		or waitfor(^?{}   , this) {
			break;
		}
	}
}
\end{cfa}
\end{figure}
For example, listing \ref{f:dtor-order} shows an example of an executor with an infinite loop, which waits for the destructor to break out of this loop.
Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction.


% ######     #    ######     #    #       #       ####### #       ###  #####  #     #
% #     #   # #   #     #   # #   #       #       #       #        #  #     # ##   ##
% #     #  #   #  #     #  #   #  #       #       #       #        #  #       # # # #
% ######  #     # ######  #     # #       #       #####   #        #   #####  #  #  #
% #       ####### #   #   ####### #       #       #       #        #        # #     #
% #       #     # #    #  #     # #       #       #       #        #  #     # #     #
% #       #     # #     # #     # ####### ####### ####### ####### ###  #####  #     #
\section{Parallelism}
Historically, computer performance was about processor speeds and instruction counts.
However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}.
In this decade, it is no longer reasonable to create a high-performance application without caring about parallelism.
Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization.
The lowest-level approach of parallelism is to use \textbf{kthread} in combination with semantics like @fork@, @join@, \etc.
However, since these have significant costs and limitations, \textbf{kthread} are now mostly used as an implementation tool rather than a user oriented one.
There are several alternatives to solve these issues that all have strengths and weaknesses.
While there are many variations of the presented paradigms, most of these variations do not actually change the guarantees or the semantics, they simply move costs in order to achieve better performance for certain workloads.

\section{Paradigms}
\subsection{User-Level Threads}
A direct improvement on the \textbf{kthread} approach is to use \textbf{uthread}.
These threads offer most of the same features that the operating system already provides but can be used on a much larger scale.
This approach is the most powerful solution as it allows all the features of multithreading, while removing several of the more expensive costs of kernel threads.
The downside is that almost none of the low-level threading problems are hidden; users still have to think about data races, deadlocks and synchronization issues.
These issues can be somewhat alleviated by a concurrency toolkit with strong guarantees, but the parallelism toolkit offers very little to reduce complexity in itself.

Examples of languages that support \textbf{uthread} are Erlang~\cite{Erlang} and \uC~\cite{uC++book}.

\subsection{Fibers : User-Level Threads Without Preemption} \label{fibers}
A popular variant of \textbf{uthread} is what is often referred to as \textbf{fiber}.
However, \textbf{fiber} do not present meaningful semantic differences with \textbf{uthread}.
The significant difference between \textbf{uthread} and \textbf{fiber} is the lack of \textbf{preemption} in the latter.
Advocates of \textbf{fiber} list their high performance and ease of implementation as major strengths, but the performance difference between \textbf{uthread} and \textbf{fiber} is controversial, and the ease of implementation, while true, is a weak argument in the context of language design.
Therefore this proposal largely ignores fibers.

An example of a language that uses fibers is Go~\cite{Go}

\subsection{Jobs and Thread Pools}
An approach on the opposite end of the spectrum is to base parallelism on \textbf{pool}.
Indeed, \textbf{pool} offer limited flexibility but at the benefit of a simpler user interface.
In \textbf{pool} based systems, users express parallelism as units of work, called jobs, and a dependency graph (either explicit or implicit) that ties them together.
This approach means users need not worry about concurrency but significantly limit the interaction that can occur among jobs.
Indeed, any \textbf{job} that blocks also block the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably.
It can be argued that a solution to this problem is to use more workers than available cores.
However, unless the number of jobs and the number of workers are comparable, having a significant number of blocked jobs always results in idles cores.

The gold standard of this implementation is Intel's TBB library~\cite{TBB}.

\subsection{Paradigm Performance}
While the choice between the three paradigms listed above may have significant performance implications, it is difficult to pin down the performance implications of choosing a model at the language level.
Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload.
Having a large amount of mostly independent units of work to execute almost guarantees equivalent performance across paradigms and that the \textbf{pool}-based system has the best efficiency thanks to the lower memory overhead (\ie no thread stack per job).
However, interactions among jobs can easily exacerbate contention.
User-level threads allow fine-grain context switching, which results in better resource utilization, but a context switch is more expensive and the extra control means users need to tweak more variables to get the desired performance.
Finally, if the units of uninterrupted work are large, enough the paradigm choice is largely amortized by the actual work done.

\section{The \protect\CFA\ Kernel : Processors, Clusters and Threads}\label{kernel}
A \textbf{cfacluster} is a group of \textbf{kthread} executed in isolation. \textbf{uthread} are scheduled on the \textbf{kthread} of a given \textbf{cfacluster}, allowing organization between \textbf{uthread} and \textbf{kthread}.
It is important that \textbf{kthread} belonging to a same \textbf{cfacluster} have homogeneous settings, otherwise migrating a \textbf{uthread} from one \textbf{kthread} to the other can cause issues.
A \textbf{cfacluster} also offers a pluggable scheduler that can optimize the workload generated by the \textbf{uthread}.

\textbf{cfacluster} have not been fully implemented in the context of this paper.
Currently \CFA only supports one \textbf{cfacluster}, the initial one.

\subsection{Future Work: Machine Setup}\label{machine}
While this was not done in the context of this paper, another important aspect of clusters is affinity.
While many common desktop and laptop PCs have homogeneous CPUs, other devices often have more heterogeneous setups.
For example, a system using \textbf{numa} configurations may benefit from users being able to tie clusters and/or kernel threads to certain CPU cores.
OS support for CPU affinity is now common~\cite{affinityLinux, affinityWindows, affinityFreebsd, affinityNetbsd, affinityMacosx}, which means it is both possible and desirable for \CFA to offer an abstraction mechanism for portable CPU affinity.

\subsection{Paradigms}\label{cfaparadigms}
Given these building blocks, it is possible to reproduce all three of the popular paradigms.
Indeed, \textbf{uthread} is the default paradigm in \CFA.
However, disabling \textbf{preemption} on a cluster means threads effectively become fibers.
Since several \textbf{cfacluster} with different scheduling policy can coexist in the same application, this allows \textbf{fiber} and \textbf{uthread} to coexist in the runtime of an application.
Finally, it is possible to build executors for thread pools from \textbf{uthread} or \textbf{fiber}, which includes specialized jobs like actors~\cite{Actors}.



\section{Behind the Scenes}
There are several challenges specific to \CFA when implementing concurrency.
These challenges are a direct result of bulk acquire and loose object definitions.
These two constraints are the root cause of most design decisions in the implementation.
Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs.
This approach avoids the chicken and egg problem~\cite{Chicken} of having a memory allocator that relies on the threading system and a threading system that relies on the runtime.
This extra goal means that memory management is a constant concern in the design of the system.

The main memory concern for concurrency is queues.
All blocking operations are made by parking threads onto queues and all queues are designed with intrusive nodes, where each node has pre-allocated link fields for chaining, to avoid the need for memory allocation.
Since several concurrency operations can use an unbound amount of memory (depending on bulk acquire), statically defining information in the intrusive fields of threads is insufficient.The only way to use a variable amount of memory without requiring memory allocation is to pre-allocate large buffers of memory eagerly and store the information in these buffers.
Conveniently, the call stack fits that description and is easy to use, which is why it is used heavily in the implementation of internal scheduling, particularly variable-length arrays.
Since stack allocation is based on scopes, the first step of the implementation is to identify the scopes that are available to store the information, and which of these can have a variable-length array.
The threads and the condition both have a fixed amount of memory, while @mutex@ routines and blocking calls allow for an unbound amount, within the stack size.

Note that since the major contributions of this paper are extending monitor semantics to bulk acquire and loose object definitions, any challenges that are not resulting of these characteristics of \CFA are considered as solved problems and therefore not discussed.

% ======================================================================
% ======================================================================
\section{Mutex Routines}
% ======================================================================
% ======================================================================

The first step towards the monitor implementation is simple @mutex@ routines.
In the single monitor case, mutual-exclusion is done using the entry/exit procedure in listing \ref{f:entry1}.
The entry/exit procedures do not have to be extended to support multiple monitors.
Indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlock~\cite{Havender68}.
In \CFA, ordering of monitor acquisition relies on memory ordering.
This approach is sufficient because all objects are guaranteed to have distinct non-overlapping memory layouts and mutual-exclusion for a monitor is only defined for its lifetime, meaning that destroying a monitor while it is acquired is undefined behaviour.
When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer array and sorted based on pointer values.
This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively.
\begin{figure}
\begin{multicols}{2}
Entry
\begin{cfa}
if monitor is free
	enter
elif already own the monitor
	continue
else
	block
increment recursions
\end{cfa}
\columnbreak
Exit
\begin{cfa}
decrement recursion
if recursion == 0
	if entry queue not empty
		wake-up thread
\end{cfa}
\end{multicols}
\begin{cfa}[caption={Initial entry and exit routine for monitors},label={f:entry1}]
\end{cfa}
\end{figure}

\subsection{Details: Interaction with polymorphism}
Depending on the choice of semantics for when monitor locks are acquired, interaction between monitors and \CFA's concept of polymorphism can be more complex to support.
However, it is shown that entry-point locking solves most of the issues.

First of all, interaction between @otype@ polymorphism (see Section~\ref{s:ParametricPolymorphism}) and monitors is impossible since monitors do not support copying.
Therefore, the main question is how to support @dtype@ polymorphism.
It is important to present the difference between the two acquiring options: \textbf{callsite-locking} and entry-point locking, \ie acquiring the monitors before making a mutex routine-call or as the first operation of the mutex routine-call.
For example:
\begin{table}
\begin{center}
\begin{tabular}{|c|c|c|}
Mutex & \textbf{callsite-locking} & \textbf{entry-point-locking} \\
call & cfa-code & cfa-code \\
\hline
\begin{cfa}[tabsize=3]
void foo(monitor& mutex a){

	// Do Work
	//...

}

void main() {
	monitor a;

	foo(a);

}
\end{cfa} & \begin{cfa}[tabsize=3]
foo(& a) {

	// Do Work
	//...

}

main() {
	monitor a;
	acquire(a);
	foo(a);
	release(a);
}
\end{cfa} & \begin{cfa}[tabsize=3]
foo(& a) {
	acquire(a);
	// Do Work
	//...
	release(a);
}

main() {
	monitor a;

	foo(a);

}
\end{cfa}
\end{tabular}
\end{center}
\caption{Call-site vs entry-point locking for mutex calls}
\label{tbl:locking-site}
\end{table}

Note the @mutex@ keyword relies on the type system, which means that in cases where a generic monitor-routine is desired, writing the mutex routine is possible with the proper trait, \eg:
\begin{cfa}
// Incorrect: T may not be monitor
forall(dtype T)
void foo(T * mutex t);

// Correct: this routine only works on monitors (any monitor)
forall(dtype T | is_monitor(T))
void bar(T * mutex t));
\end{cfa}

Both entry point and \textbf{callsite-locking} are feasible implementations.
The current \CFA implementation uses entry-point locking because it requires less work when using \textbf{raii}, effectively transferring the burden of implementation to object construction/destruction.
It is harder to use \textbf{raii} for call-site locking, as it does not necessarily have an existing scope that matches exactly the scope of the mutual exclusion, \ie the routine body.
For example, the monitor call can appear in the middle of an expression.
Furthermore, entry-point locking requires less code generation since any useful routine is called multiple times but there is only one entry point for many call sites.

% ======================================================================
% ======================================================================
\section{Threading} \label{impl:thread}
% ======================================================================
% ======================================================================

Figure \ref{fig:system1} shows a high-level picture if the \CFA runtime system in regards to concurrency.
Each component of the picture is explained in detail in the flowing sections.

\begin{figure}
\begin{center}
{\resizebox{\textwidth}{!}{\input{system.pstex_t}}}
\end{center}
\caption{Overview of the entire system}
\label{fig:system1}
\end{figure}

\subsection{Processors}
Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically @pthread@s in the current implementation of \CFA.
Indeed, any parallelism must go through operating-system libraries.
However, \textbf{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism.
Indeed, processor \textbf{kthread} simply fetch a \textbf{uthread} from the scheduler and run it; they are effectively executers for user-threads.
The main benefit of this approach is that it offers a well-defined boundary between kernel code and user code, for example, kernel thread quiescing, scheduling and interrupt handling.
Processors internally use coroutines to take advantage of the existing context-switching semantics.

\subsection{Stack Management}
One of the challenges of this system is to reduce the footprint as much as possible.
Specifically, all @pthread@s created also have a stack created with them, which should be used as much as possible.
Normally, coroutines also create their own stack to run on, however, in the case of the coroutines used for processors, these coroutines run directly on the \textbf{kthread} stack, effectively stealing the processor stack.
The exception to this rule is the Main Processor, \ie the initial \textbf{kthread} that is given to any program.
In order to respect C user expectations, the stack of the initial kernel thread, the main stack of the program, is used by the main user thread rather than the main processor, which can grow very large.

\subsection{Context Switching}
As mentioned in section \ref{coroutine}, coroutines are a stepping stone for implementing threading, because they share the same mechanism for context-switching between different stacks.
To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific routine call.
This assumption means that the context-switch only has to copy the callee-saved registers onto the stack and then switch the stack registers with the ones of the target coroutine/thread.
Note that the instruction pointer can be left untouched since the context-switch is always inside the same routine
Threads, however, do not context-switch between each other directly.
They context-switch to the scheduler.
This method is called a 2-step context-switch and has the advantage of having a clear distinction between user code and the kernel where scheduling and other system operations happen.
Obviously, this doubles the context-switch cost because threads must context-switch to an intermediate stack.
The alternative 1-step context-switch uses the stack of the ``from'' thread to schedule and then context-switches directly to the ``to'' thread.
However, the performance of the 2-step context-switch is still superior to a @pthread_yield@ (see section \ref{results}).
Additionally, for users in need for optimal performance, it is important to note that having a 2-step context-switch as the default does not prevent \CFA from offering a 1-step context-switch (akin to the Microsoft @SwitchToFiber@~\cite{switchToWindows} routine).
This option is not currently present in \CFA, but the changes required to add it are strictly additive.

\subsection{Preemption} \label{preemption}
Finally, an important aspect for any complete threading system is preemption.
As mentioned in section \ref{basics}, preemption introduces an extra degree of uncertainty, which enables users to have multiple threads interleave transparently, rather than having to cooperate among threads for proper scheduling and CPU distribution.
Indeed, preemption is desirable because it adds a degree of isolation among threads.
In a fully cooperative system, any thread that runs a long loop can starve other threads, while in a preemptive system, starvation can still occur but it does not rely on every thread having to yield or block on a regular basis, which reduces significantly a programmer burden.
Obviously, preemption is not optimal for every workload.
However any preemptive system can become a cooperative system by making the time slices extremely large.
Therefore, \CFA uses a preemptive threading system.

Preemption in \CFA\footnote{Note that the implementation of preemption is strongly tied with the underlying threading system.
For this reason, only the Linux implementation is cover, \CFA does not run on Windows at the time of writting} is based on kernel timers, which are used to run a discrete-event simulation.
Every processor keeps track of the current time and registers an expiration time with the preemption system.
When the preemption system receives a change in preemption, it inserts the time in a sorted order and sets a kernel timer for the closest one, effectively stepping through preemption events on each signal sent by the timer.
These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread.
This results in an implementation problem, because when delivering signals to a process, the kernel can deliver the signal to any kernel thread for which the signal is not blocked, \ie:
\begin{quote}
A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
SIGNAL(7) - Linux Programmer's Manual
\end{quote}
For the sake of simplicity, and in order to prevent the case of having two threads receiving alarms simultaneously, \CFA programs block the {\tt SIGALRM} signal on every kernel thread except one.

Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread.
Hence, involuntary context-switching is done by sending signal {\tt SIGUSR1} to the corresponding proces\-sor and having the thread yield from inside the signal handler.
This approach effectively context-switches away from the signal handler back to the kernel and the signal handler frame is eventually unwound when the thread is scheduled again.
As a result, a signal handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread).
It is important to note that signal handlers save and restore signal masks because user-thread migration can cause a signal mask to migrate from one kernel thread to another.
This behaviour is only a problem if all kernel threads, among which a user thread can migrate, differ in terms of signal masks\footnote{Sadly, official POSIX documentation is silent on what distinguishes ``async-signal-safe'' routines from other routines}.
However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel-alarm thread can cause deadlocks.
For this reason, the alarm thread is in a tight loop around a system call to @sigwaitinfo@, requiring very little CPU time for preemption.
One final detail about the alarm thread is how to wake it when additional communication is required (\eg on thread termination).
This unblocking is also done using {\tt SIGALRM}, but sent through the @pthread_sigqueue@.
Indeed, @sigwait@ can differentiate signals sent from @pthread_sigqueue@ from signals sent from alarms or the kernel.

\subsection{Scheduler}
Finally, an aspect that was not mentioned yet is the scheduling algorithm.
Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling.
Further discussion on scheduling is present in section \ref{futur:sched}.

% ======================================================================
% ======================================================================
\section{Internal Scheduling} \label{impl:intsched}
% ======================================================================
% ======================================================================
The following figure is the traditional illustration of a monitor (repeated from page~\pageref{fig:ClassicalMonitor} for convenience):

\begin{figure}
\begin{center}
{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
\end{center}
\caption{Traditional illustration of a monitor}
\end{figure}

This picture has several components, the two most important being the entry queue and the AS-stack.
The entry queue is an (almost) FIFO list where threads waiting to enter are parked, while the acceptor/signaller (AS) stack is a FILO list used for threads that have been signalled or otherwise marked as running next.

For \CFA, this picture does not have support for blocking multiple monitors on a single condition.
To support bulk acquire two changes to this picture are required.
First, it is no longer helpful to attach the condition to \emph{a single} monitor.
Secondly, the thread waiting on the condition has to be separated across multiple monitors, seen in figure \ref{fig:monitor_cfa}.

\begin{figure}
\begin{center}
{\resizebox{0.8\textwidth}{!}{\input{int_monitor}}}
\end{center}
\caption{Illustration of \CFA Monitor}
\label{fig:monitor_cfa}
\end{figure}

This picture and the proper entry and leave algorithms (see listing \ref{f:entry2}) is the fundamental implementation of internal scheduling.
Note that when a thread is moved from the condition to the AS-stack, it is conceptually split into N pieces, where N is the number of monitors specified in the parameter list.
The thread is woken up when all the pieces have popped from the AS-stacks and made active.
In this picture, the threads are split into halves but this is only because there are two monitors.
For a specific signalling operation every monitor needs a piece of thread on its AS-stack.

\begin{figure}
\begin{multicols}{2}
Entry
\begin{cfa}
if monitor is free
	enter
elif already own the monitor
	continue
else
	block
increment recursion

\end{cfa}
\columnbreak
Exit
\begin{cfa}
decrement recursion
if recursion == 0
	if signal_stack not empty
		set_owner to thread
		if all monitors ready
			wake-up thread

	if entry queue not empty
		wake-up thread
\end{cfa}
\end{multicols}
\begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling},label={f:entry2}]
\end{cfa}
\end{figure}

The solution discussed in \ref{s:InternalScheduling} can be seen in the exit routine of listing \ref{f:entry2}.
Basically, the solution boils down to having a separate data structure for the condition queue and the AS-stack, and unconditionally transferring ownership of the monitors but only unblocking the thread when the last monitor has transferred ownership.
This solution is deadlock safe as well as preventing any potential barging.
The data structures used for the AS-stack are reused extensively for external scheduling, but in the case of internal scheduling, the data is allocated using variable-length arrays on the call stack of the @wait@ and @signal_block@ routines.

\begin{figure}
\begin{center}
{\resizebox{0.8\textwidth}{!}{\input{monitor_structs.pstex_t}}}
\end{center}
\caption{Data structures involved in internal/external scheduling}
\label{fig:structs}
\end{figure}

Figure \ref{fig:structs} shows a high-level representation of these data structures.
The main idea behind them is that, a thread cannot contain an arbitrary number of intrusive ``next'' pointers for linking onto monitors.
The @condition node@ is the data structure that is queued onto a condition variable and, when signalled, the condition queue is popped and each @condition criterion@ is moved to the AS-stack.
Once all the criteria have been popped from their respective AS-stacks, the thread is woken up, which is what is shown in listing \ref{f:entry2}.

% ======================================================================
% ======================================================================
\section{External Scheduling}
% ======================================================================
% ======================================================================
Similarly to internal scheduling, external scheduling for multiple monitors relies on the idea that waiting-thread queues are no longer specific to a single monitor, as mentioned in section \ref{extsched}.
For internal scheduling, these queues are part of condition variables, which are still unique for a given scheduling operation (\ie no signal statement uses multiple conditions).
However, in the case of external scheduling, there is no equivalent object which is associated with @waitfor@ statements.
This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired.
These monitors being the only objects that have sufficient lifetime and are available on both sides of the @waitfor@ statement.
This requires an algorithm to choose which monitor holds the relevant queue.
It is also important that said algorithm be independent of the order in which users list parameters.
The proposed algorithm is to fall back on monitor lock ordering (sorting by address) and specify that the monitor that is acquired first is the one with the relevant waiting queue.
This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint.

This algorithm choice has two consequences:
\begin{itemize}
	\item The queue of the monitor with the lowest address is no longer a true FIFO queue because threads can be moved to the front of the queue.
These queues need to contain a set of monitors for each of the waiting threads.
Therefore, another thread whose set contains the same lowest address monitor but different lower priority monitors may arrive first but enter the critical section after a thread with the correct pairing.
	\item The queue of the lowest priority monitor is both required and potentially unused.
Indeed, since it is not known at compile time which monitor is the monitor which has the lowest address, every monitor needs to have the correct queues even though it is possible that some queues go unused for the entire duration of the program, for example if a monitor is only used in a specific pair.
\end{itemize}
Therefore, the following modifications need to be made to support external scheduling:
\begin{itemize}
	\item The threads waiting on the entry queue need to keep track of which routine they are trying to enter, and using which set of monitors.
The @mutex@ routine already has all the required information on its stack, so the thread only needs to keep a pointer to that information.
	\item The monitors need to keep a mask of acceptable routines.
This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it.
It also needs storage to keep track of which routine was accepted.
Since this information is not specific to any monitor, the monitors actually contain a pointer to an integer on the stack of the waiting thread.
Note that if a thread has acquired two monitors but executes a @waitfor@ with only one monitor as a parameter, setting the mask of acceptable routines to both monitors will not cause any problems since the extra monitor will not change ownership regardless.
This becomes relevant when @when@ clauses affect the number of monitors passed to a @waitfor@ statement.
	\item The entry/exit routines need to be updated as shown in listing \ref{f:entry3}.
\end{itemize}

\subsection{External Scheduling - Destructors}
Finally, to support the ordering inversion of destructors, the code generation needs to be modified to use a special entry routine.
This routine is needed because of the storage requirements of the call order inversion.
Indeed, when waiting for the destructors, storage is needed for the waiting context and the lifetime of said storage needs to outlive the waiting operation it is needed for.
For regular @waitfor@ statements, the call stack of the routine itself matches this requirement but it is no longer the case when waiting for the destructor since it is pushed on to the AS-stack for later.
The @waitfor@ semantics can then be adjusted correspondingly, as seen in listing \ref{f:entry-dtor}

\begin{figure}
\begin{multicols}{2}
Entry
\begin{cfa}
if monitor is free
	enter
elif already own the monitor
	continue
elif matches waitfor mask
	push criteria to AS-stack
	continue
else
	block
increment recursion
\end{cfa}
\columnbreak
Exit
\begin{cfa}
decrement recursion
if recursion == 0
	if signal_stack not empty
		set_owner to thread
		if all monitors ready
			wake-up thread
		endif
	endif

	if entry queue not empty
		wake-up thread
	endif
\end{cfa}
\end{multicols}
\begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling and external scheduling},label={f:entry3}]
\end{cfa}
\end{figure}

\begin{figure}
\begin{multicols}{2}
Destructor Entry
\begin{cfa}
if monitor is free
	enter
elif already own the monitor
	increment recursion
	return
create wait context
if matches waitfor mask
	reset mask
	push self to AS-stack
	baton pass
else
	wait
increment recursion
\end{cfa}
\columnbreak
Waitfor
\begin{cfa}
if matching thread is already there
	if found destructor
		push destructor to AS-stack
		unlock all monitors
	else
		push self to AS-stack
		baton pass
	endif
	return
endif
if non-blocking
	Unlock all monitors
	Return
endif

push self to AS-stack
set waitfor mask
block
return
\end{cfa}
\end{multicols}
\begin{cfa}[caption={Pseudo code for the \protect\lstinline|waitfor| routine and the \protect\lstinline|mutex| entry routine for destructors},label={f:entry-dtor}]
\end{cfa}
\end{figure}


% ======================================================================
% ======================================================================
\section{Putting It All Together}
% ======================================================================
% ======================================================================


\section{Threads As Monitors}
As it was subtly alluded in section \ref{threads}, @thread@s in \CFA are in fact monitors, which means that all monitor 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{figure}
\begin{cfa}[caption={Toy simulator using \protect\lstinline|thread|s and \protect\lstinline|monitor|s.},label={f:engine-v1}]
// 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 );

// Simulation 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{cfa}
\end{figure}
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 forever.
Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner:
\begin{figure}
\begin{cfa}[caption={Same toy simulator with proper termination condition.},label={f:engine-v2}]
// 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 );

// Simulation 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 );
	}
}

// Call destructor for simulator once simulator finishes
// Call destructor for renderer to signify shutdown
\end{cfa}
\end{figure}

\section{Fibers \& Threads}
As mentioned in section \ref{preemption}, \CFA uses preemptive threads by default but can use fibers on demand.
Currently, using fibers is done by adding the following line of code to the program~:
\begin{cfa}
unsigned int default_preemption() {
	return 0;
}
\end{cfa}
This routine is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice, \ie no preemption.
However, once clusters are fully implemented, it will be possible to create fibers and \textbf{uthread} in the same system, as in listing \ref{f:fiber-uthread}
\begin{figure}
\lstset{language=CFA,deletedelim=**[is][]{`}{`}}
\begin{cfa}[caption={Using fibers and \textbf{uthread} side-by-side in \CFA},label={f:fiber-uthread}]
// Cluster forward declaration
struct cluster;

// Processor forward declaration
struct processor;

// Construct clusters with a preemption rate
void ?{}(cluster& this, unsigned int rate);
// Construct processor and add it to cluster
void ?{}(processor& this, cluster& cluster);
// Construct thread and schedule it on cluster
void ?{}(thread& this, cluster& cluster);

// Declare two clusters
cluster thread_cluster = { 10`ms };			// Preempt every 10 ms
cluster fibers_cluster = { 0 };				// Never preempt

// Construct 4 processors
processor processors[4] = {
	//2 for the thread cluster
	thread_cluster;
	thread_cluster;
	//2 for the fibers cluster
	fibers_cluster;
	fibers_cluster;
};

// Declares thread
thread UThread {};
void ?{}(UThread& this) {
	// Construct underlying thread to automatically
	// be scheduled on the thread cluster
	(this){ thread_cluster }
}

void main(UThread & this);

// Declares fibers
thread Fiber {};
void ?{}(Fiber& this) {
	// Construct underlying thread to automatically
	// be scheduled on the fiber cluster
	(this.__thread){ fibers_cluster }
}

void main(Fiber & this);
\end{cfa}
\end{figure}


% ======================================================================
% ======================================================================
\section{Performance Results} \label{results}
% ======================================================================
% ======================================================================
\section{Machine Setup}
Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks.
All tests were made on this machine.
\begin{table}
\begin{center}
\begin{tabular}{| l | r | l | r |}
\hline
Architecture		& x86\_64 			& NUMA node(s) 	& 8 \\
\hline
CPU op-mode(s)		& 32-bit, 64-bit 		& Model name 	& AMD Opteron\texttrademark  Processor 6380 \\
\hline
Byte Order			& Little Endian 		& CPU Freq 		& 2.5\si{\giga\hertz} \\
\hline
CPU(s)			& 64 				& L1d cache 	& \SI{16}{\kibi\byte} \\
\hline
Thread(s) per core	& 2 				& L1i cache 	& \SI{64}{\kibi\byte} \\
\hline
Core(s) per socket	& 8 				& L2 cache 		& \SI{2048}{\kibi\byte} \\
\hline
Socket(s)			& 4 				& L3 cache 		& \SI{6144}{\kibi\byte} \\
\hline
\hline
Operating system		& Ubuntu 16.04.3 LTS	& Kernel		& Linux 4.4-97-generic \\
\hline
Compiler			& GCC 6.3 		& Translator	& CFA 1 \\
\hline
Java version		& OpenJDK-9 		& Go version	& 1.9.2 \\
\hline
\end{tabular}
\end{center}
\caption{Machine setup used for the tests}
\label{tab:machine}
\end{table}

\section{Micro Benchmarks}
All benchmarks are run using the same harness to produce the results, seen as the @BENCH()@ macro in the following examples.
This macro uses the following logic to benchmark the code:
\begin{cfa}
#define BENCH(run, result) \
	before = gettime(); \
	run; \
	after  = gettime(); \
	result = (after - before) / N;
\end{cfa}
The method used to get time is @clock_gettime(CLOCK_THREAD_CPUTIME_ID);@.
Each benchmark is using many iterations of a simple call to measure the cost of the call.
The specific number of iterations depends on the specific benchmark.

\subsection{Context-Switching}
The first interesting benchmark is to measure how long context-switches take.
The simplest approach to do this is to yield on a thread, which executes a 2-step context switch.
Yielding causes the thread to context-switch to the scheduler and back, more precisely: from the \textbf{uthread} to the \textbf{kthread} then from the \textbf{kthread} back to the same \textbf{uthread} (or a different one in the general case).
In order to make the comparison fair, coroutines also execute a 2-step context-switch by resuming another coroutine which does nothing but suspending in a tight loop, which is a resume/suspend cycle instead of a yield.
Figure~\ref{f:ctx-switch} shows the code for coroutines and threads with the results in table \ref{tab:ctx-switch}.
All omitted tests are functionally identical to one of these tests.
The difference between coroutines and threads can be attributed to the cost of scheduling.
\begin{figure}
\begin{multicols}{2}
\CFA Coroutines
\begin{cfa}
coroutine GreatSuspender {};
void main(GreatSuspender& this) {
	while(true) { suspend(); }
}
int main() {
	GreatSuspender s;
	resume(s);
	BENCH(
		for(size_t i=0; i<n; i++) {
			resume(s);
		},
		result
	)
	printf("%llu\n", result);
}
\end{cfa}
\columnbreak
\CFA Threads
\begin{cfa}




int main() {


	BENCH(
		for(size_t i=0; i<n; i++) {
			yield();
		},
		result
	)
	printf("%llu\n", result);
}
\end{cfa}
\end{multicols}
\begin{cfa}[caption={\CFA benchmark code used to measure context-switches for coroutines and threads.},label={f:ctx-switch}]
\end{cfa}
\end{figure}

\begin{table}
\begin{center}
\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
\cline{2-4}
\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
\hline
Kernel Thread	& 241.5	& 243.86	& 5.08 \\
\CFA Coroutine	& 38		& 38		& 0    \\
\CFA Thread		& 103		& 102.96	& 2.96 \\
\uC Coroutine	& 46		& 45.86	& 0.35 \\
\uC Thread		& 98		& 99.11	& 1.42 \\
Goroutine		& 150		& 149.96	& 3.16 \\
Java Thread		& 289		& 290.68	& 8.72 \\
\hline
\end{tabular}
\end{center}
\caption{Context Switch comparison.
All numbers are in nanoseconds(\si{\nano\second})}
\label{tab:ctx-switch}
\end{table}

\subsection{Mutual-Exclusion}
The next interesting benchmark is to measure the overhead to enter/leave a critical-section.
For monitors, the simplest approach is to measure how long it takes to enter and leave a monitor routine.
Figure~\ref{f:mutex} shows the code for \CFA.
To put the results in context, the cost of entering a non-inline routine and the cost of acquiring and releasing a @pthread_mutex@ lock is also measured.
The results can be shown in table \ref{tab:mutex}.

\begin{figure}
\begin{cfa}[caption={\CFA benchmark code used to measure mutex routines.},label={f:mutex}]
monitor M {};
void __attribute__((noinline)) call( M & mutex m /*, m2, m3, m4*/ ) {}

int main() {
	M m/*, m2, m3, m4*/;
	BENCH(
		for(size_t i=0; i<n; i++) {
			call(m/*, m2, m3, m4*/);
		},
		result
	)
	printf("%llu\n", result);
}
\end{cfa}
\end{figure}

\begin{table}
\begin{center}
\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
\cline{2-4}
\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
\hline
C routine						& 2		& 2		& 0    \\
FetchAdd + FetchSub				& 26		& 26		& 0    \\
Pthreads Mutex Lock				& 31		& 31.86	& 0.99 \\
\uC @monitor@ member routine		& 30		& 30		& 0    \\
\CFA @mutex@ routine, 1 argument	& 41		& 41.57	& 0.9  \\
\CFA @mutex@ routine, 2 argument	& 76		& 76.96	& 1.57 \\
\CFA @mutex@ routine, 4 argument	& 145		& 146.68	& 3.85 \\
Java synchronized routine			& 27		& 28.57	& 2.6  \\
\hline
\end{tabular}
\end{center}
\caption{Mutex routine comparison.
All numbers are in nanoseconds(\si{\nano\second})}
\label{tab:mutex}
\end{table}

\subsection{Internal Scheduling}
The internal-scheduling benchmark measures the cost of waiting on and signalling a condition variable.
Figure~\ref{f:int-sched} shows the code for \CFA, with results table \ref{tab:int-sched}.
As with all other benchmarks, all omitted tests are functionally identical to one of these tests.

\begin{figure}
\begin{cfa}[caption={Benchmark code for internal scheduling},label={f:int-sched}]
volatile int go = 0;
condition c;
monitor M {};
M m1;

void __attribute__((noinline)) do_call( M & mutex a1 ) { signal(c); }

thread T {};
void ^?{}( T & mutex this ) {}
void main( T & this ) {
	while(go == 0) { yield(); }
	while(go == 1) { do_call(m1); }
}
int  __attribute__((noinline)) do_wait( M & mutex a1 ) {
	go = 1;
	BENCH(
		for(size_t i=0; i<n; i++) {
			wait(c);
		},
		result
	)
	printf("%llu\n", result);
	go = 0;
	return 0;
}
int main() {
	T t;
	return do_wait(m1);
}
\end{cfa}
\end{figure}

\begin{table}
\begin{center}
\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
\cline{2-4}
\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
\hline
Pthreads Condition Variable			& 5902.5	& 6093.29 	& 714.78 \\
\uC @signal@					& 322		& 323 	& 3.36   \\
\CFA @signal@, 1 @monitor@	& 352.5	& 353.11	& 3.66   \\
\CFA @signal@, 2 @monitor@	& 430		& 430.29	& 8.97   \\
\CFA @signal@, 4 @monitor@	& 594.5	& 606.57	& 18.33  \\
Java @notify@				& 13831.5	& 15698.21	& 4782.3 \\
\hline
\end{tabular}
\end{center}
\caption{Internal scheduling comparison.
All numbers are in nanoseconds(\si{\nano\second})}
\label{tab:int-sched}
\end{table}

\subsection{External Scheduling}
The Internal scheduling benchmark measures the cost of the @waitfor@ statement (@_Accept@ in \uC).
Figure~\ref{f:ext-sched} shows the code for \CFA, with results in table \ref{tab:ext-sched}.
As with all other benchmarks, all omitted tests are functionally identical to one of these tests.

\begin{figure}
\begin{cfa}[caption={Benchmark code for external scheduling},label={f:ext-sched}]
volatile int go = 0;
monitor M {};
M m1;
thread T {};

void __attribute__((noinline)) do_call( M & mutex a1 ) {}

void ^?{}( T & mutex this ) {}
void main( T & this ) {
	while(go == 0) { yield(); }
	while(go == 1) { do_call(m1); }
}
int  __attribute__((noinline)) do_wait( M & mutex a1 ) {
	go = 1;
	BENCH(
		for(size_t i=0; i<n; i++) {
			waitfor(call, a1);
		},
		result
	)
	printf("%llu\n", result);
	go = 0;
	return 0;
}
int main() {
	T t;
	return do_wait(m1);
}
\end{cfa}
\end{figure}

\begin{table}
\begin{center}
\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
\cline{2-4}
\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
\hline
\uC @Accept@					& 350		& 350.61	& 3.11  \\
\CFA @waitfor@, 1 @monitor@	& 358.5	& 358.36	& 3.82  \\
\CFA @waitfor@, 2 @monitor@	& 422		& 426.79	& 7.95  \\
\CFA @waitfor@, 4 @monitor@	& 579.5	& 585.46	& 11.25 \\
\hline
\end{tabular}
\end{center}
\caption{External scheduling comparison.
All numbers are in nanoseconds(\si{\nano\second})}
\label{tab:ext-sched}
\end{table}


\subsection{Object Creation}
Finally, the last benchmark measures the cost of creation for concurrent objects.
Figure~\ref{f:creation} shows the code for @pthread@s and \CFA threads, with results shown in table \ref{tab:creation}.
As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
The only note here is that the call stacks of \CFA coroutines are lazily created, therefore without priming the coroutine, the creation cost is very low.

\begin{figure}
\begin{center}
@pthread@
\begin{cfa}
int main() {
	BENCH(
		for(size_t i=0; i<n; i++) {
			pthread_t thread;
			if(pthread_create(&thread,NULL,foo,NULL)<0) {
				perror( "failure" );
				return 1;
			}

			if(pthread_join(thread, NULL)<0) {
				perror( "failure" );
				return 1;
			}
		},
		result
	)
	printf("%llu\n", result);
}
\end{cfa}



\CFA Threads
\begin{cfa}
int main() {
	BENCH(
		for(size_t i=0; i<n; i++) {
			MyThread m;
		},
		result
	)
	printf("%llu\n", result);
}
\end{cfa}
\end{center}
\caption{Benchmark code for \protect\lstinline|pthread|s and \CFA to measure object creation}
\label{f:creation}
\end{figure}

\begin{table}
\begin{center}
\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
\cline{2-4}
\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
\hline
Pthreads			& 26996	& 26984.71	& 156.6  \\
\CFA Coroutine Lazy	& 6		& 5.71	& 0.45   \\
\CFA Coroutine Eager	& 708		& 706.68	& 4.82   \\
\CFA Thread			& 1173.5	& 1176.18	& 15.18  \\
\uC Coroutine		& 109		& 107.46	& 1.74   \\
\uC Thread			& 526		& 530.89	& 9.73   \\
Goroutine			& 2520.5	& 2530.93	& 61,56  \\
Java Thread			& 91114.5	& 92272.79	& 961.58 \\
\hline
\end{tabular}
\end{center}
\caption{Creation comparison.
All numbers are in nanoseconds(\si{\nano\second}).}
\label{tab:creation}
\end{table}



\section{Conclusion}
This paper has achieved a minimal concurrency \textbf{api} that is simple, efficient and usable as the basis for higher-level features.
The approach presented is based on a lightweight thread-system for parallelism, which sits on top of clusters of processors.
This M:N model is judged to be both more efficient and allow more flexibility for users.
Furthermore, this document introduces monitors as the main concurrency tool for users.
This paper also offers a novel approach allowing multiple monitors to be accessed simultaneously without running into the Nested Monitor Problem~\cite{Lister77}.
It also offers a full implementation of the concurrency runtime written entirely in \CFA, effectively the largest \CFA code base to date.


% ======================================================================
% ======================================================================
\section{Future Work}
% ======================================================================
% ======================================================================

\subsection{Performance} \label{futur:perf}
This paper presents a first implementation of the \CFA concurrency runtime.
Therefore, there is still significant work to improve performance.
Many of the data structures and algorithms may change in the future to more efficient versions.
For example, the number of monitors in a single bulk acquire is only bound by the stack size, this is probably unnecessarily generous.
It may be possible that limiting the number helps increase performance.
However, it is not obvious that the benefit would be significant.

\subsection{Flexible Scheduling} \label{futur:sched}
An important part of concurrency is scheduling.
Different scheduling algorithms can affect performance (both in terms of average and variation).
However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted to the requirements of the workload.
However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms.
For example, a web server could attach Type-of-Service information to threads and have a ``ToS aware'' scheduling algorithm tailored to this specific web server.
This path of flexible schedulers will be explored for \CFA.

\subsection{Non-Blocking I/O} \label{futur:nbio}
While most of the parallelism tools are aimed at data parallelism and control-flow parallelism, many modern workloads are not bound on computation but on IO operations, a common case being web servers and XaaS (anything as a service).
These types of workloads often require significant engineering around amortizing costs of blocking IO operations.
At its core, non-blocking I/O is an operating system level feature that allows queuing IO operations (\eg network operations) and registering for notifications instead of waiting for requests to complete.
In this context, the role of the language makes Non-Blocking IO easily available and with low overhead.
The current trend is to use asynchronous programming using tools like callbacks and/or futures and promises, which can be seen in frameworks like Node.js~\cite{NodeJs} for JavaScript, Spring MVC~\cite{SpringMVC} for Java and Django~\cite{Django} for Python.
However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear.

\subsection{Other Concurrency Tools} \label{futur:tools}
While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
Examples of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, executors and actors.
These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.

\subsection{Implicit Threading} \label{futur:implcit}
Simpler applications can benefit greatly from having implicit parallelism.
That is, parallelism that does not rely on the user to write concurrency.
This type of parallelism can be achieved both at the language level and at the library level.
The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithms~\cite{uC++book}.
Table \ref{f:parfor} shows three different code examples that accomplish point-wise sums of large arrays.
Note that none of these examples explicitly declare any concurrency or parallelism objects.

\begin{table}
\begin{center}
\begin{tabular}[t]{|c|c|c|}
Sequential & Library Parallel & Language Parallel \\
\begin{cfa}[tabsize=3]
void big_sum(
	int* a, int* b,
	int* o,
	size_t len)
{
	for(
		int i = 0;
		i < len;
		++i )
	{
		o[i]=a[i]+b[i];
	}
}





int* a[10000];
int* b[10000];
int* c[10000];
//... fill in a & b
big_sum(a,b,c,10000);
\end{cfa} &\begin{cfa}[tabsize=3]
void big_sum(
	int* a, int* b,
	int* o,
	size_t len)
{
	range ar(a, a+len);
	range br(b, b+len);
	range or(o, o+len);
	parfor( ai, bi, oi,
	[](	int* ai,
		int* bi,
		int* oi)
	{
		oi=ai+bi;
	});
}


int* a[10000];
int* b[10000];
int* c[10000];
//... fill in a & b
big_sum(a,b,c,10000);
\end{cfa}&\begin{cfa}[tabsize=3]
void big_sum(
	int* a, int* b,
	int* o,
	size_t len)
{
	parfor (ai,bi,oi)
	    in (a, b, o )
	{
		oi = ai + bi;
	}
}







int* a[10000];
int* b[10000];
int* c[10000];
//... fill in a & b
big_sum(a,b,c,10000);
\end{cfa}
\end{tabular}
\end{center}
\caption{For loop to sum numbers: Sequential, using library parallelism and language parallelism.}
\label{f:parfor}
\end{table}

Implicit parallelism is a restrictive solution and therefore has its limitations.
However, it is a quick and simple approach to parallelism, which may very well be sufficient for smaller applications and reduces the amount of boilerplate needed to start benefiting from parallelism in modern CPUs.


% A C K N O W L E D G E M E N T S
% -------------------------------
\section{Acknowledgements}

Thanks to Aaron Moss, Rob Schluntz and Andrew Beach for their work on the \CFA project as well as all the discussions which helped concretize the ideas in this paper.
Partial funding was supplied by the Natural Sciences and Engineering Research Council of Canada and a corporate partnership with Huawei Ltd.


% B I B L I O G R A P H Y
% -----------------------------
%\bibliographystyle{plain}
\bibliography{pl,local}


\end{document}

% Local Variables: %
% tab-width: 4 %
% fill-column: 120 %
% compile-command: "make" %
% End: %
