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

\articletype{RESEARCH ARTICLE}%

\received{XXXXX}
\revised{XXXXX}
\accepted{XXXXX}

\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{dcolumn}						% align decimal points in tables
\usepackage{capt-of}

\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{\topfraction}{0.8}			% float must be greater than X of the page before it is forced onto its own page
\renewcommand{\bottomfraction}{0.8}			% float must be greater than X of the page before it is forced onto its own page
\renewcommand{\floatpagefraction}{0.8}		% float must be greater than X of the page before it is forced onto its own page
\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}

%\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, generator, _Generic, _Imaginary, __imag, __imag__,
		inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
		otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, suspend, 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{language=go,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
{}
\lstnewenvironment{python}[1][]
{\lstset{language=python,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
{}

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

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

\newbox\myboxA
\newbox\myboxB
\newbox\myboxC
\newbox\myboxD

\title{\texorpdfstring{Advanced Control-flow and Concurrency in \protect\CFA}{Advanced Control-flow 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 polymorphic, non-object-oriented, concurrent, backwards-compatible extension of the C programming language.
This paper discusses the design philosophy and implementation of its advanced control-flow and concurrent/parallel features, along with the supporting runtime.
These features are created from scratch as ISO C has only low-level and/or unimplemented concurrency, so C programmers continue to rely on library features like C pthreads.
\CFA introduces modern language-level control-flow mechanisms, like generators, coroutines, user-level threading, and monitors for mutual exclusion and synchronization.
Library extension for executors, futures, and actors are built on these basic mechanisms.
The runtime provides significant programmer simplification and safety by eliminating spurious wakeup and optional monitor barging.
The runtime also ensures multiple monitors can be safely acquired \emph{simultaneously} (deadlock free), and this feature is fully integrated with all monitor synchronization mechanisms.
All control-flow features integrate with the \CFA polymorphic type-system and exception handling, while respecting the expectations and style of C programmers.
Experimental results show comparable performance of the new features with similar mechanisms in other concurrent programming-languages.
}%

\keywords{generator, coroutine, concurrency, parallelism, thread, monitor, runtime, C, \CFA (Cforall)}


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

\maketitle


\section{Introduction}

This paper discusses the design philosophy and implementation of advanced language-level control-flow and concurrent/parallel features in \CFA~\cite{Moss18} and its runtime.
\CFA is a modern, polymorphic, non-object-oriented\footnote{
\CFA has features often associated with object-oriented programming languages, such as constructors, destructors, virtuals and simple inheritance.
However, functions \emph{cannot} be nested in structures, so there is no lexical binding between a structure and set of functions (member/method) implemented by an implicit \lstinline@this@ (receiver) parameter.},
backwards-compatible extension of the C programming language.
Within the \CFA framework, new control-flow features are created from scratch.
ISO \Celeven defines only a subset of the \CFA extensions, where the overlapping features are concurrency~\cite[\S~7.26]{C11}.
However, \Celeven concurrency is largely wrappers for a subset of the pthreads library~\cite{Butenhof97,Pthreads}.
Furthermore, \Celeven and pthreads concurrency is simple, based on thread fork/join in a function and a few locks, which is low-level and error prone;
no high-level language concurrency features are defined.
Interestingly, almost a decade after publication of the \Celeven standard, neither gcc-8, clang-8 nor msvc-19 (most recent versions) support the \Celeven include @threads.h@, indicating little interest in the C11 concurrency approach.
Finally, while the \Celeven standard does not state a threading model, the historical association with pthreads suggests implementations would adopt kernel-level threading (1:1)~\cite{ThreadModel}.

In contrast, there has been a renewed interest during the past decade in user-level (M:N, green) threading in old and new programming languages.
As multi-core hardware became available in the 1980/90s, both user and kernel threading were examined.
Kernel threading was chosen, largely because of its simplicity and fit with the simpler operating systems and hardware architectures at the time, which gave it a performance advantage~\cite{Drepper03}.
Libraries like pthreads were developed for C, and the Solaris operating-system switched from user (JDK 1.1~\cite{JDK1.1}) to kernel threads.
As a result, languages like Java, Scala~\cite{Scala}, Objective-C~\cite{obj-c-book}, \CCeleven~\cite{C11}, and C\#~\cite{Csharp} adopt the 1:1 kernel-threading model, with a variety of presentation mechanisms.
From 2000 onwards, languages like Go~\cite{Go}, Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, D~\cite{D}, and \uC~\cite{uC++,uC++book} have championed the M:N user-threading model, and many user-threading libraries have appeared~\cite{Qthreads,MPC,BoostThreads}, including putting green threads back into Java~\cite{Quasar}.
The main argument for user-level threading is that they are lighter weight than kernel threads (locking and context switching do not cross the kernel boundary), so there is less restriction on programming styles that encourage large numbers of threads performing medium work-units to facilitate load balancing by the runtime~\cite{Verch12}.
As well, user-threading facilitates a simpler concurrency approach using thread objects that leverage sequential patterns versus events with call-backs~\cite{vonBehren03}.
Finally, performant user-threading implementations (both time and space) are largely competitive with direct kernel-threading implementations, while achieving the programming advantages of high concurrency levels and safety.

A further effort over the past two decades is the development of language memory-models to deal with the conflict between language features and compiler/hardware optimizations, i.e., some language features are unsafe in the presence of aggressive sequential optimizations~\cite{Buhr95a,Boehm05}.
The consequence is that a language must provide sufficient tools to program around safety issues, as inline and library code is all sequential to the compiler.
One solution is low-level qualifiers and functions (e.g., @volatile@ and atomics) allowing \emph{programmers} to explicitly write safe (race-free~\cite{Boehm12}) programs.
A safer solution is high-level language constructs so the \emph{compiler} knows the optimization boundaries, and hence, provides implicit safety.
This problem is best know with respect to concurrency, but applies to other complex control-flow, like exceptions\footnote{
\CFA exception handling will be presented in a separate paper.
The key feature that dovetails with this paper is non-local exceptions allowing exceptions to be raised across stacks, with synchronous exceptions raised among coroutines and asynchronous exceptions raised among threads, similar to that in \uC~\cite[\S~5]{uC++}
} and coroutines.
Finally, solutions in the language allows matching constructs with language paradigm, i.e., imperative and functional languages have different presentations of the same concept.

Finally, it is important for a language to provide safety over performance \emph{as the default}, allowing careful reduction of safety for performance when necessary.
Two concurrency violations of this philosophy are \emph{spurious wakeup} and \emph{barging}, i.e., random wakeup~\cite[\S~8]{Buhr05a} and signals-as-hints~\cite[\S~8]{Buhr05a}, where one is a consequence of the other, i.e., once there is spurious wakeup, signals-as-hints follows.
However, spurious wakeup is \emph{not} a foundational concurrency property~\cite[\S~8]{Buhr05a}, it is a performance design choice.
Similarly, signals-as-hints is also a performance decision.
We argue removing spurious wakeup and signals-as-hints makes concurrent programming significantly safer because it removes local non-determinism and matches with programmer expectation.
(Experience by the authors teaching concurrency is that students are highly confused by these semantics.)
Clawing back performance, when local non-determinism is unimportant, should be an option not the default.

\begin{comment}
For example, it is possible to provide exceptions, coroutines, monitors, and tasks as specialized types in an object-oriented language, integrating these constructs to allow leveraging the type-system (static type-checking) and all other object-oriented capabilities~\cite{uC++}.
It is also possible to leverage call/return for blocking communication via new control structures, versus switching to alternative communication paradigms, like channels or message passing.
As well, user threading is often a complementary feature, allowing light-weight threading to match with low-cost objects, while hiding the application/kernel boundary.
User threading also allows layering of implicit concurrency models (no explicit thread creation), such executors, data-flow, actors, into a single language, so programmers can chose the model that best fits an algorithm.\footnote{
All implicit concurrency models have explicit threading in their implementation, and hence, can be build from explicit threading;
however, the reverse is seldom true, i.e., given implicit concurrency, e.g., actors, it is virtually impossible to create explicit concurrency, e.g., blocking thread objects.}
Finally, with extended language features and user-level threading it is possible to discretely fold locking and non-blocking I/O multiplexing into the language's I/O libraries, so threading implicitly dovetails with the I/O subsystem.
\CFA embraces language extensions and user-level threading to provide advanced control-flow (exception handling\footnote{
\CFA exception handling will be presented in a separate paper.
The key feature that dovetails with this paper is non-local exceptions allowing exceptions to be raised across stacks, with synchronous exceptions raised among coroutines and asynchronous exceptions raised among threads, similar to that in \uC~\cite[\S~5]{uC++}
} and coroutines) and concurrency.

Most augmented traditional (Fortran 18~\cite{Fortran18}, Cobol 14~\cite{Cobol14}, Ada 12~\cite{Ada12}, Java 11~\cite{Java11}) and new languages (Go~\cite{Go}, Rust~\cite{Rust}, and D~\cite{D}), except \CC, diverge from C with different syntax and semantics, only interoperate indirectly with C, and are not systems languages, for those with managed memory.
As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten.
While \CC, like \CFA, takes an evolutionary approach to extend C, \CC's constantly growing complex and interdependent features-set (e.g., objects, inheritance, templates, etc.) mean idiomatic \CC code is difficult to use from C, and C programmers must expend significant effort learning \CC.
Hence, rewriting and retraining costs for these languages, even \CC, are prohibitive for companies with a large C software-base.
\CFA with its orthogonal feature-set, its high-performance runtime, and direct access to all existing C libraries circumvents these problems.
\end{comment}

\CFA embraces user-level threading, language extensions for advanced control-flow, and safety as the default.
We present comparative examples so the reader can judge if the \CFA control-flow extensions are better and safer than those in or proposed for \Celeven, \CC, and other concurrent, imperative programming-languages, and perform experiments to show the \CFA runtime is competitive with other similar mechanisms.
The main contributions of this work are:
\begin{itemize}
\item
language-level generators, coroutines and user-level threading, which respect the expectations of C programmers.
\item
monitor synchronization without barging, and the ability to safely acquiring multiple monitors \emph{simultaneously} (deadlock free), while seamlessly integrating these capability with all monitor synchronization mechanisms.
\item
providing statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features.
\item
library extensions for executors, futures, and actors built on the basic mechanisms.
\item
a runtime system with no spurious wakeup.
\item
a dynamic partitioning mechanism to segregate the execution environment for specialized requirements.
\item
a non-blocking I/O library
\item
experimental results showing comparable performance of the new features with similar mechanisms in other programming languages.
\end{itemize}


\section{Stateful Function}

The generator/coroutine provides a stateful function, which is an old idea~\cite{Conway63,Marlin80} that is new again~\cite{C++20Coroutine19}.
A stateful function allows execution to be temporarily suspended and later resumed, e.g., plugin, device driver, finite-state machine.
Hence, a stateful function may not end when it returns to its caller, allowing it to be restarted with the data and execution location present at the point of suspension.
This capability is accomplished by retaining a data/execution \emph{closure} between invocations.
If the closure is fixed size, we call it a \emph{generator} (or \emph{stackless}), and its control flow is restricted, e.g., suspending outside the generator is prohibited.
If the closure is variable sized, we call it a \emph{coroutine} (or \emph{stackful}), and as the names implies, often implemented with a separate stack with no programming restrictions.
Hence, refactoring a stackless coroutine may require changing it to stackful.
A foundational property of all \emph{stateful functions} is that resume/suspend \emph{do not} cause incremental stack growth, i.e., resume/suspend operations are remembered through the closure not the stack.
As well, activating a stateful function is \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles).
A fixed closure activated by modified call/return is faster than a variable closure activated by context switching.
Additionally, any storage management for the closure (especially in unmanaged languages, i.e., no garbage collection) must also be factored into design and performance.
Therefore, selecting between stackless and stackful semantics is a tradeoff between programming requirements and performance, where stackless is faster and stackful is more general.
Note, creation cost is amortized across usage, so activation cost is usually the dominant factor.


\begin{figure}
\centering
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
typedef struct {
	int fn1, fn;
} Fib;
#define FibCtor { 1, 0 }
int fib( Fib * f ) {



	int fn = f->fn; f->fn = f->fn1;
		f->fn1 = f->fn + fn;
	return fn;

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

\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`generator` Fib {
	int fn1, fn;
};

void `main(Fib & fib)` with(fib) {

	[fn1, fn] = [1, 0];
	for () {
		`suspend;`
		[fn1, fn] = [fn, fn + fn1];

	}
}
int main() {
	Fib f1, f2;
	for ( 10 )
		sout | `resume( f1 )`.fn
			 | `resume( f2 )`.fn;
}
\end{cfa}
\end{lrbox}

\begin{lrbox}{\myboxC}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
typedef struct {
	int fn1, fn;  void * `next`;
} Fib;
#define FibCtor { 1, 0, NULL }
Fib * comain( Fib * f ) {
	if ( f->next ) goto *f->next;
	f->next = &&s1;
	for ( ;; ) {
		return f;
	  s1:; int fn = f->fn + f->fn1;
			f->fn1 = f->fn; f->fn = fn;
	}
}
int main() {
	Fib f1 = FibCtor, f2 = FibCtor;
	for ( int i = 0; i < 10; i += 1 )
		printf("%d %d\n",comain(&f1)->fn,
				 comain(&f2)->fn);
}
\end{cfa}
\end{lrbox}

\subfloat[C asymmetric generator]{\label{f:CFibonacci}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[\CFA asymmetric generator]{\label{f:CFAFibonacciGen}\usebox\myboxB}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[C generator implementation]{\label{f:CFibonacciSim}\usebox\myboxC}
\caption{Fibonacci (output) Asymmetric Generator}
\label{f:FibonacciAsymmetricGenerator}

\bigskip

\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`generator Fmt` {
	char ch;
	int g, b;
};
void ?{}( Fmt & fmt ) { `resume(fmt);` } // constructor
void ^?{}( Fmt & f ) with(f) { $\C[1.75in]{// destructor}$
	if ( g != 0 || b != 0 ) sout | nl; }
void `main( Fmt & f )` with(f) {
	for () { $\C{// until destructor call}$
		for ( ; g < 5; g += 1 ) { $\C{// groups}$
			for ( ; b < 4; b += 1 ) { $\C{// blocks}$
				`suspend;` $\C{// wait for character}$
				while ( ch == '\n' ) `suspend;` // ignore
				sout | ch;						// newline
			} sout | " ";  // block spacer
		} sout | nl; // group newline
	}
}
int main() {
	Fmt fmt; $\C{// fmt constructor called}$
	for () {
		sin | fmt.ch; $\C{// read into generator}$
	  if ( eof( sin ) ) break;
		`resume( fmt );`
	}

} $\C{// fmt destructor called}\CRT$
\end{cfa}
\end{lrbox}

\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
typedef struct {
	void * next;
	char ch;
	int g, b;
} Fmt;
void comain( Fmt * f ) {
	if ( f->next ) goto *f->next;
	f->next = &&s1;
	for ( ;; ) {
		for ( f->g = 0; f->g < 5; f->g += 1 ) {
			for ( f->b = 0; f->b < 4; f->b += 1 ) {
				return;
			  s1:;  while ( f->ch == '\n' ) return;
				printf( "%c", f->ch );
			} printf( " " );
		} printf( "\n" );
	}
}
int main() {
	Fmt fmt = { NULL };  comain( &fmt ); // prime
	for ( ;; ) {
		scanf( "%c", &fmt.ch );
	  if ( feof( stdin ) ) break;
		comain( &fmt );
	}
	if ( fmt.g != 0 || fmt.b != 0 ) printf( "\n" );
}
\end{cfa}
\end{lrbox}

\subfloat[\CFA asymmetric generator]{\label{f:CFAFormatGen}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[C generator simulation]{\label{f:CFormatSim}\usebox\myboxB}
\hspace{3pt}
\caption{Formatter (input) Asymmetric Generator}
\label{f:FormatterAsymmetricGenerator}
\end{figure}


\subsection{Generator}

Stackless generators have the potential to be very small and fast, \ie as small and fast as function call/return for both creation and execution.
The \CFA goal is to achieve this performance target, possibly at the cost of some semantic complexity.
How this goal is accomplished is done through a series of different kinds of generators and their implementation. 

Figure~\ref{f:FibonacciAsymmetricGenerator} shows an unbounded asymmetric generator for an infinite sequence of Fibonacci numbers written in C and \CFA, with a simple C implementation for the \CFA version.
This kind of generator is an \emph{output generator}, producing a new result on each resumption.
To compute Fibonacci, the previous two values in the sequence are retained to generate the next value, \ie @fn1@ and @fn@, plus the execution location where control restarts when the generator is resumed, \ie top or middle.
An additional requirement is the ability to create an arbitrary number of generators (of any kind), \ie retaining state in global variables is insufficient;
hence, state is retained in a closure between calls.
Figure~\ref{f:CFibonacci} shows the C approach of manually creating the closure in structure @Fib@, and multiple instances of this closure provide multiple Fibonacci generators.
The C version only has the middle execution state because the top execution state becomes declaration initialization.
Figure~\ref{f:CFAFibonacciGen} shows the \CFA approach, which also has a manual closure, but replaces the structure with a special \CFA @generator@ type.
This generator type is then connected to a function named @main@ that takes as its only parameter a reference to the generator type, called a \emph{generator main}.
The generator main contains @suspend@ statements that suspend execution without ending the generator versus @return@.
For the Fibonacci generator-main,\footnote{
The \CFA \lstinline|with| opens an aggregate scope making its fields directly accessible, like Pascal \lstinline|with|, but using parallel semantics.
Multiple aggregates may be opened.}
the top initialization state appears at the start and the middle execution state is denoted by statement @suspend@.
Any local variables in @main@ \emph{are not retained} between calls;
hence local variable are only for temporary computations \emph{between} suspends.
All retained state \emph{must} appear in the generator's type.
As well, generator code containing a @suspend@ cannot be refactored into a helper function called by the generator, because @suspend@ is implemented via @return@, so a return from the helper function goes back to the current generator not the resumer.
The generator is started by calling function @resume@ with a generator instance, which begins execution at the top of the generator main, and subsequent @resume@ calls restart the generator at its point of last suspension.
Resuming an ended (returned) generator is undefined.
Function @resume@ returns its argument generator so it can be cascaded in an expression, in this case to print the next Fibonacci value @fn@ computed in the generator instance.
Figure~\ref{f:CFibonacciSim} shows the C implementation of the \CFA generator only needs one additional field, @next@, to handle retention of execution state.
The computed @goto@ at the start of the generator main, which branches after the previous suspend, adds very little cost to the resume call.
Finally, an explicit generator type provides both design and performance benefits, such as multiple type-safe interface functions taking and returning arbitrary types.
\begin{cfa}
int ?()( Fib & fib ) with( fib ) { return `resume( fib )`.fn; }   // function-call interface
int ?()( Fib & fib, int N ) with( fib ) { for ( N - 1 ) `fib()`; return `fib()`; }   // use simple interface
double ?()( Fib & fib ) with( fib ) { return (int)`fib()` / 3.14159; } // cast prevents recursive call
sout | (int)f1() | (double)f1() | f2( 2 );   // simple interface, cast selects call based on return type, step 2 values
\end{cfa}
Now, the generator can be a separately-compiled opaque-type only accessed through its interface functions.
For contrast, Figure~\ref{f:PythonFibonacci} shows the equivalent Python Fibonacci generator, which does not use a generator type, and hence only has a single interface, but an implicit closure.

Having to manually create the generator closure by moving local-state variables into the generator type is an additional programmer burden and possible point of error.
(This restriction is removed by the coroutine, see Section~\ref{s:Coroutine}.)
Our concern is that static analysis to discriminate local state from temporary variables is complex and beyond the current scope of the \CFA project.
As well, supporting variable-size local-state, like variable-length arrays, requires dynamic allocation of the local state, which significantly increases the cost of generator creation/destruction, and is a show-stopper for embedded programming.
But more importantly, the size of the generator type is tied to the local state in the generator main, which precludes separate compilation of the generator main, \ie a generator must be inlined or local state must be dynamically allocated.
Our current experience is that most generator problems have simple data state, including local state, but complex execution state.
As well, C programmers are not afraid with this kind of semantic programming requirement, if it results in very small, fast generators.

Figure~\ref{f:CFAFormatGen} shows an asymmetric \newterm{input generator}, @Fmt@, for restructuring text into groups of characters of fixed-size blocks, \ie the input on the left is reformatted into the output on the right, where newlines are ignored.
\begin{center}
\tt
\begin{tabular}{@{}l|l@{}}
\multicolumn{1}{c|}{\textbf{\textrm{input}}} & \multicolumn{1}{c}{\textbf{\textrm{output}}} \\
\begin{tabular}[t]{@{}ll@{}}
abcdefghijklmnopqrstuvwxyz \\
abcdefghijklmnopqrstuvwxyz
\end{tabular}
&
\begin{tabular}[t]{@{}lllll@{}}
abcd	& efgh	& ijkl	& mnop	& qrst	\\
uvwx	& yzab	& cdef	& ghij	& klmn	\\
opqr	& stuv	& wxyz	&		&
\end{tabular}
\end{tabular}
\end{center}
The example takes advantage of resuming a generator in the constructor to prime the loops so the first character sent for formatting appears inside the nested loops.
The destructor provides a newline, if formatted text ends with a full line.
Figure~\ref{f:CFormatSim} shows the C implementation of the \CFA input generator with one additional field and the computed @goto@.
For contrast, Figure~\ref{f:PythonFormatter} shows the equivalent Python format generator with the same properties as the Fibonacci generator.

Figure~\ref{f:DeviceDriverGen} shows a \emph{killer} asymmetric generator, a device-driver, because device drivers caused 70\%-85\% of failures in Windows/Linux~\cite{Swift05}.
Device drives follow the pattern of simple data state but complex execution state, \ie finite state-machine (FSM) parsing a protocol.
For example, the following protocol:
\begin{center}
\ldots\, STX \ldots\, message \ldots\, ESC ETX \ldots\, message \ldots\, ETX 2-byte crc \ldots
\end{center}
is a network message beginning with the control character STX, ending with an ETX, and followed by a 2-byte cyclic-redundancy check.
Control characters may appear in a message if preceded by an ESC.
When a message byte arrives, it triggers an interrupt, and the operating system services the interrupt by calling the device driver with the byte read from a hardware register.
The device driver returns a status code of its current state, and when a complete message is obtained, the operating system knows the message is in the message buffer.
Hence, the device driver is an input/output generator.

Note, the cost of creating and resuming the device-driver generator, @Driver@, is virtually identical to call/return, so performance in an operating-system kernel is excellent.
As well, the data state is small, where variables @byte@ and @msg@ are communication variables for passing in message bytes and returning the message, and variables @lnth@, @crc@, and @sum@ are local variable that must be retained between calls and are hoisted into the generator type.
Manually, detecting and hoisting local-state variables is easy when the number is small.
Finally, the execution state is large, with one @resume@ and seven @suspend@s.
Hence, the key benefits of the generator are correctness, safety, and maintenance because the execution states of the FSM are transcribed directly into the programming language rather than using a table-driven approach.
Because FSMs can be complex and occur frequently in important domains, direct support of the generator is crucial in a systems programming-language.

\begin{figure}
\centering
\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{python}[aboveskip=0pt,belowskip=0pt]
def Fib():
    fn1, fn = 0, 1
    while True:
        `yield fn1`
        fn1, fn = fn, fn1 + fn
f1 = Fib()
f2 = Fib()
for i in range( 10 ):
	print( next( f1 ), next( f2 ) )






\end{python}
\end{lrbox}

\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{python}[aboveskip=0pt,belowskip=0pt]
def Fmt():
	try:
		while True:
			for g in range( 5 ):
				for b in range( 4 ):
					print( `(yield)`, end='' )
				print( '  ', end='' )
			print()
	except GeneratorExit:
		if g != 0 | b != 0:
			print()
fmt = Fmt()
`next( fmt )`			 # prime, next prewritten
for i in range( 41 ):
	`fmt.send( 'a' );`	# send to yield
\end{python}
\end{lrbox}
\subfloat[Fibonacci]{\label{f:PythonFibonacci}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[Formatter]{\label{f:PythonFormatter}\usebox\myboxB}
\caption{Python Generator}
\label{f:PythonGenerator}

\bigskip

\begin{tabular}{@{}l|l@{}}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
enum Status { CONT, MSG, ESTX,
				ELNTH, ECRC };
`generator` Driver {
	Status status;
	unsigned char byte, * msg; // communication
	unsigned int lnth, sum;      // local state
	unsigned short int crc;
};
void ?{}( Driver & d, char * m ) { d.msg = m; }
Status next( Driver & d, char b ) with( d ) {
	byte = b; `resume( d );` return status;
}
void main( Driver & d ) with( d ) {
	enum { STX = '\002', ESC = '\033',
			ETX = '\003', MaxMsg = 64 };
  msg: for () { // parse message
		status = CONT;
		lnth = 0; sum = 0;
		while ( byte != STX ) `suspend;`
	  emsg: for () {
			`suspend;` // process byte
\end{cfa}
&
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
			choose ( byte ) { // switch with implicit break
			  case STX:
				status = ESTX; `suspend;` continue msg;
			  case ETX:
				break emsg;
			  case ESC:
				`suspend;`
			}
			if ( lnth >= MaxMsg ) { // buffer full ?
				status = ELNTH; `suspend;` continue msg; }
			msg[lnth++] = byte;
			sum += byte;
		}
		msg[lnth] = '\0'; // terminate string
		`suspend;`
		crc = byte << 8;
		`suspend;`
		status = (crc | byte) == sum ? MSG : ECRC;
		`suspend;`
	}
}
\end{cfa}
\end{tabular}
\caption{Device-driver generator for communication protocol}
\label{f:DeviceDriverGen}
\end{figure}

Figure~\ref{f:CFAPingPongGen} shows a symmetric generator, where the generator resumes another generator, forming a resume/resume cycle.
(The trivial cycle is a generator resuming itself.)
This control flow is similar to recursion for functions, but without stack growth.
The steps for symmetric control-flow are creating, executing, and terminating the cycle.
Constructing the cycle must deal with definition-before-use to close the cycle, \ie, the first generator must know about the last generator, which is not within scope.
(This issues occurs for any cyclic data-structure.)
% The example creates all the generators and then assigns the partners that form the cycle.
% Alternatively, the constructor can assign the partners as they are declared, except the first, and the first-generator partner is set after the last generator declaration to close the cycle.
Once the cycle is formed, the program main resumes one of the generators, and the generators can then traverse an arbitrary cycle using @resume@ to activate partner generator(s).
Terminating the cycle is accomplished by @suspend@ or @return@, both of which go back to the stack frame that started the cycle (program main in the example).
The starting stack-frame is below the last active generator because the resume/resume cycle does not grow the stack.
Also, since local variables are not retained in the generator function, it does not contain an objects with destructors that must be called, so the  cost is the same as a function return.
Destructor cost occurs when the generator instance is deallocated, which is easily controlled by the programmer.

Figure~\ref{f:CPingPongSim} shows the implementation of the symmetric generator, where the complexity is the @resume@, which needs an extension to the calling convention to perform a forward rather than backward jump.
This jump starts at the top of the next generator main to re-execute the normal calling convention to make space on the stack for its local variables.
However, before the jump, the caller must reset its stack (and any registers) equivalent to a @return@, but subsequently jump forward not backwards.
This semantics is basically a tail-call optimization, which compilers already perform.
Hence, assembly code is manually insert in the example to undo the generator's entry code before the direct jump.
This assembly code is fragile as it depends on what entry code is generated, specifically if there are local variables and the level of optimization.
To provide this new calling convention requires a mechanism built into the compiler, which is beyond the scope of \CFA at this time.
Nevertheless, it is possible to hand generate any symmetric generators for proof of concept and performance testing.
A compiler could also eliminate other artifacts in the generator simulation to further increase performance.

\begin{figure}
\centering
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`generator PingPong` {
	const char * name;
	PingPong & partner; // rebindable reference
	int N, i;
};
void ?{}(PingPong & pp, char * nm, int N) with(pp) {
	name = nm;  partner = 0p;  pp.N = N;  i = 0; }
void `main( PingPong & pp )` with(pp) {
	for ( ; i < N; i += 1 ) {
		sout | name | i;
		`resume( partner );`
	}
}
int main() {
	enum { N = 5 };
	PingPong ping = {"ping", N}, pong = {"pong", N};
	&ping.partner = &pong;  &pong.partner = &ping;
	`resume( ping );`
}
\end{cfa}
\end{lrbox}

\begin{lrbox}{\myboxB}
\begin{cfa}[escapechar={},aboveskip=0pt,belowskip=0pt]
typedef struct PingPong {
	const char * name;
	struct PingPong * partner;
	int N, i;
	void * next;
} PingPong;
#define PPCtor(name, N) { name, NULL, N, 0, NULL }
void comain( PingPong * pp ) {
	if ( pp->next ) goto *pp->next;
	pp->next = &&cycle;
	for ( ; pp->i < pp->N; pp->i += 1 ) {
		printf( "%s %d\n", pp->name, pp->i );
		asm( "mov  %0,%%rdi" : "=m" (pp->partner) );
		asm( "mov  %rdi,%rax" );
		asm( "popq %rbx" );
		asm( "jmp  comain" );
	  cycle: ;
	}
}
\end{cfa}
\end{lrbox}

\subfloat[\CFA symmetric generator]{\label{f:CFAPingPongGen}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[C generator simulation]{\label{f:CPingPongSim}\usebox\myboxB}
\hspace{3pt}
\caption{Ping-Pong Symmetric Generator}
\label{f:PingPongSymmetricGenerator}
\end{figure}

Finally, part of this generator work was inspired by the recent \CCtwenty generator proposal~\cite{C++20Coroutine19} (which they call coroutines).
Our work provides the same high-performance asymmetric-generators as \CCtwenty, and extends their work with symmetric generators.
An additional \CCtwenty generator feature allows @suspend@ and @resume@ to be followed by a restricted compound-statement that is executed after the current generator has reset its stack but before calling the next generator, specified with the following \CFA syntax.
\begin{cfa}
... suspend`{ ... }`;
... resume( C )`{ ... }` ...
\end{cfa}
Since the current generator's stack is released before calling the compound statement, the compound statement can only reference variables in the generator's type.
This feature is useful when a generator is used in a concurrent context to ensure it is stopped before releasing a lock in the compound statement, which might immediately allow another thread to resume the generator.
Hence, this mechanism provides a general and safe handoff of the generator among competing threads.


\subsection{Coroutine}
\label{s:Coroutine}

Stackful coroutines extend generator semantics, \ie there is an implicit closure and @suspend@ may appear in a helper function called from the coroutine main.
A coroutine is specified by replacing @generator@ with @coroutine@ for the type.
This generality results in higher cost for creation, due to dynamic stack allocation, execution, due to context switching among stacks, and terminating, due to possible stack unwinding and dynamic stack deallocation.
How coroutines differ from generators is done through a series of examples.

First, the previous generator examples are converted to their coroutine counterparts, allowing local-state variables to be moved from the generator type into the coroutine main.
\begin{description}
\item[Fibonacci]
Move the declaration of @fn1@ to the start of coroutine main.
\begin{cfa}[xleftmargin=0pt]
void main( Fib & fib ) with(fib) {
	`int fn1;`
\end{cfa}
\item[Formatter]
Move the declaration of @g@ and @b@ to the for loops in the coroutine main.
\begin{cfa}[xleftmargin=0pt]
for ( `g`; 5 ) {
	for ( `b`; 4 ) {
\end{cfa}
\item[Device Driver]
Move the declaration of @lnth@ and @sum@ to their points of initialization.
\begin{cfa}[xleftmargin=0pt]
	status = CONT;
	`unsigned int lnth = 0, sum = 0;`
	...
	`unsigned short int crc = byte << 8;`
\end{cfa}
\item[PingPong]
Move the declaration of @i@ to the for loop in the coroutine main.
\begin{cfa}[xleftmargin=0pt]
void main( PingPong & pp ) with(pp) {
	for ( `i`; N ) {
\end{cfa}
\end{description}
It is also possible to refactor code containing local-state and @suspend@ statements into a helper routine, like the computation of the CRC for the device driver.
\begin{cfa}
unsigned int Crc() {
	`suspend;`
	unsigned short int crc = byte << 8;
	`suspend;`
	status = (crc | byte) == sum ? MSG : ECRC;
	return crc;
}
\end{cfa}
A call to this function is placed at the end of the driver's coroutine-main.
For complex finite-state machines, refactoring is part of normal program abstraction, especially when code is used in multiple places.
Again, this complexity is usually associated with execution state rather than data state.

\begin{comment}
Figure~\ref{f:Coroutine3States} creates a @coroutine@ type, @`coroutine` Fib { int fn; }@, which provides communication, @fn@, for the \newterm{coroutine main}, @main@, which runs on the coroutine stack, and possibly multiple interface routines, \eg @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 represents the three states in the Fibonacci formula via the three suspend points, 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 allocates the coroutine stack and cocalls its coroutine main on that 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.

\begin{figure}
\centering
\newbox\myboxA
% \begin{lrbox}{\myboxA}
% \begin{cfa}[aboveskip=0pt,belowskip=0pt]
% `int fn1, fn2, state = 1;`   // single global variables
% int fib() {
% 	int fn;
% 	`switch ( state )` {  // explicit execution state
% 	  case 1: fn = 0;  fn1 = fn;  state = 2;  break;
% 	  case 2: fn = 1;  fn2 = fn1;  fn1 = fn;  state = 3;  break;
% 	  case 3: fn = fn1 + fn2;  fn2 = fn1;  fn1 = fn;  break;
% 	}
% 	return fn;
% }
% int main() {
% 
% 	for ( int i = 0; i < 10; i += 1 ) {
% 		printf( "%d\n", fib() );
% 	}
% }
% \end{cfa}
% \end{lrbox}
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
#define FibCtor { 0, 1 }
typedef struct { int fn1, fn; } Fib;
int fib( Fib * f ) {

	int ret = f->fn1;
	f->fn1 = f->fn;
	f->fn = ret + f->fn;
	return ret;
}



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

\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`coroutine` Fib { int fn1; };
void main( Fib & fib ) with( fib ) {
	int fn;
	[fn1, fn] = [0, 1];
	for () {
		`suspend;`
		[fn1, fn] = [fn, fn1 + fn];
	}
}
int ?()( Fib & fib ) with( fib ) {
	return `resume( fib )`.fn1;
}
int main() {
	Fib f1, f2;
	for ( 10 ) {
		sout | f1() | f2();
}


\end{cfa}
\end{lrbox}

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

def Fib():

    fn1, fn = 0, 1
    while True:
        `yield fn1`
        fn1, fn = fn, fn1 + fn


// next prewritten


f1 = Fib()
f2 = Fib()
for i in range( 10 ):
	print( next( f1 ), next( f2 ) )



\end{python}
\end{lrbox}

\subfloat[C]{\label{f:GlobalVariables}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[\CFA]{\label{f:ExternalState}\usebox\myboxB}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[Python]{\label{f:ExternalState}\usebox\myboxC}
\caption{Fibonacci Generator}
\label{f:C-fibonacci}
\end{figure}

\bigskip

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

def Fibonacci():
	fn = 0;	fn1 = fn; `yield fn`  # suspend
	fn = 1; fn2 = fn1; fn1 = fn; `yield fn`
	while True:
		fn = fn1 + fn2; fn2 = fn1; fn1 = fn; `yield fn`


f1 = Fibonacci()
f2 = Fibonacci()
for i in range( 10 ):
	print( `next( f1 )`, `next( f2 )` ) # resume

\end{python}
\end{lrbox}
\subfloat[\CFA]{\label{f:Coroutine3States}\usebox\myboxA}
\qquad
\subfloat[Python]{\label{f:Coroutine1State}\usebox\myboxB}
\caption{Fibonacci input coroutine, 3 states, internal variables}
\label{f:cfa-fibonacci}
\end{figure}
\end{comment}

\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;			// communication
	int N, money, receipt;
};
void main( Prod & prod ) with( prod ) {
	// 1st resume starts here
	for ( i; N ) {
		int p1 = random( 100 ), p2 = random( 100 );
		sout | p1 | " " | p2;
		int status = delivery( c, p1, p2 );
		sout | " $" | money | nl | status;
		receipt += 1;
	}
	stop( c );
	sout | "prod stops";
}
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;			// communication
	int p1, p2, status;
	bool done;
};
void ?{}( Cons & cons, Prod & p ) {
	&cons.p = &p; // reassignable reference
	cons.[status, done ] = [0, false];
}
void main( Cons & cons ) with( cons ) {
	// 1st resume starts here
	int money = 1, receipt;
	for ( ; ! done; ) {
		sout | p1 | " " | p2 | nl | " $" | money;
		status += 1;
		receipt = payment( p, money );
		sout | " #" | receipt;
		money += 1;
	}
	sout | "cons stops";
}
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}

\medskip

\begin{center}
\input{FullProdConsStack.pstex_t}
\end{center}
\vspace*{-10pt}
\caption{Producer / consumer runtime stacks}
\label{f:ProdConsRuntimeStacks}

\medskip

\begin{center}
\input{FullCoroutinePhases.pstex_t}
\end{center}
\vspace*{-10pt}
\caption{Ping / Pong coroutine steps}
\label{f:PingPongFullCoroutineSteps}
\end{figure}

Figure~\ref{f:ProdCons} shows the ping-pong example in Figure~\ref{f:CFAPingPongGen} extended into a producer/consumer symmetric-coroutine performing bidirectional communication.
This example is illustrative because both producer/consumer have two interface functions with @resume@s that suspend execution in these interface (helper) functions.
The program main creates the producer coroutine, passes it to the consumer coroutine in its initialization, and closes the cycle at the call to @start@ along with the number of items to be produced.
The first @resume@ of @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-state 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.
On the first resume, @cons@'s stack is created and initialized, holding local-state variables retained between subsequent activations of the coroutine.
The consumer iterates until the @done@ flag is set, prints the values delivered by the producer, 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 @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 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.
Figure~\ref{f:ProdConsRuntimeStacks} shows the runtime stacks of the program main, and the coroutine mains for @prod@ and @cons@ during the cycling.

Terminating a coroutine cycle is more complex than a generator cycle, because it requires context switching to the program main's \emph{stack} to shutdown the program, whereas generators started by the program main run on its stack.
Furthermore, each deallocated coroutine must guarantee all destructors are run for object allocated in the coroutine type \emph{and} allocated on the coroutine's stack at the point of suspension, which can be arbitrarily deep.
When a coroutine's main ends, its stack is already unwound so any stack allocated objects with destructors have been finalized.
The na\"{i}ve semantics for coroutine-cycle termination is context switch to the last resumer, like executing a @suspend@/@return@ in a generator.
However, for coroutines, the last resumer is \emph{not} implicitly below the current stack frame, as for generators, because each coroutine's stack is independent.
Unfortunately, it is impossible to determine statically if a coroutine is in a cycle and unrealistic to check dynamically (graph-cycle problem).
Hence, a compromise solution is necessary that works for asymmetric (acyclic) and symmetric (cyclic) coroutines.

Our solution for coroutine termination works well for the most common asymmetric and symmetric coroutine usage-patterns.
For asymmetric coroutines, it is common for the first resumer (starter) coroutine to be the only resumer.
All previous generators converted to coroutines have this property.
For symmetric coroutines, it is common for the cycle creator to persist for the life-time of the cycle.
Hence, the starter coroutine is remembered on the first resume and ending the coroutine resumes the starter.
Figure~\ref{f:ProdConsRuntimeStacks} shows this semantic by the dashed lines from the end of the coroutine mains: @prod@ starts @cons@ so @cons@ resumes @prod@ at the end, and the program main starts @prod@ so @prod@ resumes the program main at the end.
For other scenarios, it is always possible to devise a solution with additional programming effort.

The producer/consumer example does not illustrate the full power of the starter semantics because @cons@ always ends first.
Assume generator @PingPong@ is converted to a coroutine.
Figure~\ref{f:PingPongFullCoroutineSteps} shows the creation, starter, and cyclic execution steps of the coroutine version.
The program main creates (declares) coroutine instances @ping@ and @pong@.
Next, program main resumes @ping@, making it @ping@'s starter, and @ping@'s main resumes @pong@'s main, making it @pong@'s starter.
Execution forms a cycle when @pong@ resumes @ping@, and cycles $N$ times.
By adjusting $N$ for either @ping@/@pong@, it is possible to have either one finish first, instead of @pong@ always ending first.
If @pong@ ends first, it resumes its starter @ping@ in its coroutine main, then @ping@ ends and resumes its starter the program main in function @start@.
If @ping@ ends first, it resumes its starter the program main in function @start@.
Regardless of the cycle complexity, the starter stack always leads back to the program main, but the stack can be entered at an arbitrary point.
Once back at the program main, coroutines @ping@ and @pong@ are deallocated.
For generators, deallocation runs the destructors for all objects in the generator type.
For coroutines, deallocation deals with objects in the coroutine type and must also run the destructors for any objects pending on the coroutine's stack for any unterminated coroutine.
Hence, if a coroutine's destructor detects the coroutine is not ended, it implicitly raises a cancellation exception (uncatchable exception) at the coroutine and resumes it so the cancellation exception can propagate to the root of the coroutine's stack destroying all local variable on the stack.
So the \CFA semantics for the generator and coroutine, ensure both can be safely deallocated at any time, regardless of their current state, like any other aggregate object.
Explicitly raising normal exceptions at another coroutine can replace flag variables, like @stop@, \eg @prod@ raises a @stop@ exception at @cons@ after it finishes generating values and resumes @cons@, which catches the @stop@exception to terminate its loop.

Finally, there is an interesting effect for @suspend@ with symmetric coroutines.
A coroutine must retain its last resumer to suspend back because the resumer is on a different stack.
These reverse pointers allow @suspend@ to cycle \emph{backwards}, which may be useful in certain cases.
However, there is an anomaly if a coroutine resumes itself, because it overwrites its last resumer with itself, losing the ability to resume the last external resumer.
To prevent losing this information, a self-resume does not overwrite the last resumer.


\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 directed the \CFA coroutine design.

For object-oriented languages, inheritance can be used to provide extra fields and code, but it requires explicitly writing the inheritance:
\begin{cfa}[morekeywords={class,inherits}]
class mycoroutine inherits baseCoroutine { ... }
\end{cfa}
In addition, the programming language and possibly its tool set, \eg debugger, @valgrind@ need to understand @baseCoroutine@ because of special stack property of coroutines.
Furthermore, the execution of constructors/destructors is in the wrong order for certain operations.
For example, for threads 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 alternative is composition:
\begin{cfa}
struct mycoroutine {
	... // declarations
	baseCoroutine dummy; // composition, last declaration
}
\end{cfa}
which also requires an explicit declaration that must be last to ensure correct initialization order.
However, there is nothing preventing wrong placement or multiple declarations of @baseCoroutine@.

For coroutines, as for threads, many implementations are based on function pointers or function 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}

Figure~\ref{f:CoroutineMemoryLayout} shows different memory-layout options for a coroutine (where a task is similar).
The coroutine handle is the @coroutine@ instance containing programmer specified global/communication variables.
The coroutine descriptor contains all implicit declarations needed by the runtime, \eg @suspend@/@resume@, and can be part of the coroutine handle or separate.\footnote{
We are examining variable-sized structures (VLS), where fields can be variable-sized structures or arrays.
Once allocated, a VLS is fixed sized.}
The coroutine stack can appear in a number of locations and forms, fixed or variable sized.
Hence, the coroutine's stack could be a VLS on the allocating stack, provided the allocating stack is large enough.
For stack allocation, allocation/deallocation only requires a few arithmetic operation to compute the size and adjust the stack point, modulo any constructor costs.
For heap allocation, allocation/deallocation is an expensive heap operation (where the heap can be a shared resource), modulo any constructor costs.
For heap stack allocation, it is also possible to use a split (segmented) stack calling-convention, available with gcc and clang, so the stack is variable sized.
Currently, \CFA supports stack/heap allocated descriptors but only heap allocated stacks;
split-stack allocation is under development.
In \CFA debug-mode, a fixed-sized stack is terminated with a write-only page, which catches most stack overflows.

\begin{figure}
\centering
\input{corlayout.pstex_t}
\caption{Coroutine memory layout}
\label{f:CoroutineMemoryLayout}
\end{figure}

Similarly, the canonical threading paradigm is often based on function pointers, \eg @pthreads@~\cite{Butenhof97}, \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, as in the pthreads approach.
\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 function/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 the 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 language support.
The reserved keyword simply eases use for the common case.

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 restricts the available set of 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 provides no implicit copying operations and the @is_coroutine@ trait provides no explicit copying operations, 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 advantage of this approach is that users can easily create different types of coroutines, \eg 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.


\section{Concurrency}
\label{s:Concurrency}

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 the execution path from input to output 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{stackful} coroutine executes on its own stack, allowing full generality.
Only stackful 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 \newterm{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 stackful 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 stackful, 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 stackful scheduler is often used for simplicity and security.

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 about 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.

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{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:Monitor}.)
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, \ie where the program's initial thread begins, so it is a natural extension of this semantics to use overloading to declare \lstinline@main@s for user coroutines and threads.}
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!";
}
\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!";
}

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!";
}
int main() {
	World w`[10]`;							$\C{// implicit forks after creation}$
	sout | "Hello ";					$\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 * heapLive;
	{
		MyThread blockLive;					$\C{// fork block-based thread}$
		heapLive = `new`( MyThread );		$\C{// fork heap-based thread}$
		...
	}										$\C{// join block-based thread}$
	...
	`delete`( heapLive );					$\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 sequentially, 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 deallocated 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 slightly 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 variables}$
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;
}
\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 related 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, \eg 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 stateful 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 locking mechanisms 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 is 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 \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-passing locks~\cite{Andrews89} between threads instead of unconditionally releasing locks is an example of barging prevention.


\section{Monitor}
\label{s:Monitor}

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, the @dtype@ property provides no implicit copying operations and the @is_monitor@ trait provides no explicit copying operations, 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 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.
\begin{cfa}
monitor M { ... } m;
void foo( M & mutex m ) { ... }				$\C{// acquire mutual exclusion}$
void bar( M & mutex m ) {					$\C{// acquire mutual exclusion}$
	... `foo( m );` ...						$\C{// reacquire mutual exclusion}$
}
`bar( m );`									$\C{// nested monitor call}$
\end{cfa}

The benefit of mandatory monitor qualifiers is self-documentation, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameters is redundant.
Instead, the semantics have one qualifier as the default, and the other required.
For example, make the safe @mutex@ qualifier the default because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
Alternatively, make the unsafe \lstinline[morekeywords=nomutex]@nomutex@ qualifier the default because it is the \emph{normal} parameter semantics while @mutex@ parameters are rare.
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, there is an ambiguity in the C type-system 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 acquires mutual exclusion.
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 deadlock 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} (see Section~\ref{s:Implementation} for implementation details).
In the 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 dynamic tracking of monitor calls, and dealing with it requires rollback semantics~\cite{Dice10}.
In \CFA, a safety aid is provided by using bulk acquire of all monitors to shared objects, whereas other monitor systems provide no aid.
While \CFA provides only a partial solution, it handles many useful cases, \eg:
\begin{cfa}
monitor BankAccount { ... };
void deposit( BankAccount & `mutex` b, int deposit );
void transfer( BankAccount & `mutex` my, BankAccount & `mutex` your, int me2you ) {
	deposit( my, `-`me2you );				$\C{// debit}$
	deposit( your, me2you );				$\C{// credit}$
}
\end{cfa}
This example shows a trivial solution to the bank-account transfer problem.
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}{@{}l@{\hspace{3\parindentlnth}}l@{}}
\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}
\\
\multicolumn{1}{c}{\textbf{routine call}} & \multicolumn{1}{c}{\lstinline@mutex@ \textbf{statement}}
\end{tabular}
\end{cquote}


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

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 synchronization to schedule threads needing access to the shared data, where threads block 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 generic 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 (see Figure~\ref{f:DatingService}).
\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 generic bounded-buffer with external scheduling, where producers/consumers detecting a full/empty buffer block and prevent more producers/consumers from entering the monitor until there is a free/empty slot in the buffer.
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 of (external to) the monitor on a calling queue, versus blocking on condition queues inside of (internal to) the monitor.
External scheduling allows users to wait for events from other threads without concern of unrelated events occurring.
The mechnaism can be done in terms of control flow, \eg Ada @accept@ or \uC @_Accept@, or in terms of data, \eg Go channels.
While both mechanisms have strengths and weaknesses, this project uses a control-flow mechanism to stay consistent with other language semantics.
Two challenges specific to \CFA for external scheduling are loose object-definitions (see Section~\ref{s:LooseObjectDefinitions}) and multiple-monitor routines (see Section~\ref{s:Multi-MonitorScheduling}).

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 from the urgent queue, uses/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 use/take the state.

Figure~\ref{f:DatingService} shows a dating service demonstrating non-blocking and blocking signalling.
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 numbers in the monitor because of the mutual-exclusion property.
For signal scheduling, the @exchange@ condition is necessary to block the thread finding the match, while the matcher unblocks to take the opposite number, post its phone number, and unblock the partner.
For signal-block scheduling, the implicit urgent-queue replaces the explict @exchange@-condition and @signal_block@ puts the finding thread on the urgent condition and unblocks the matcher.

The dating service is an example of a monitor that cannot be written using external scheduling because it requires knowledge of calling parameters to make scheduling decisions, and parameters of waiting threads are unavailable;
as well, an arriving thread may not find a partner and must wait, which requires a condition variable, and condition variables imply internal scheduling.

\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;
		`signal( exchange );`
	} else {
		GirlPhNo = phNo;
		`signal( Boys[ccode] );`
		`wait( exchange );`
	} // 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 at least the same locks as the waiting thread signalled from the condition queue.

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.
% When an overloaded routine appears in an @waitfor@ statement, calls to any routine with that name are accepted.
% The rationale is that members with the same name should perform a similar function, and therefore, all should be eligible to accept a call.
Overloaded routines can be disambiguated using a cast:
\begin{cfa}
void rtn( M & mutex m );
`int` rtn( M & mutex m );
waitfor( (`int` (*)( M & mutex ))rtn, m );
\end{cfa}

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 bar( 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 @bar@ 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 signaller and signallee is difficult, often requiring multiple unblock/block cycles (looping around a wait rechecking if a condition is met).
In fact, signals-as-hints is completely opposite from that proposed by Hoare in the seminal paper on monitors:
\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.
Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implict form of barging.
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 in options when the signaller finishes the inner mutex-statement.
The signaller 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 W1 may have waited before W2, so W2 is unaware of it.
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 the 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.
The benefit is encapsulating complexity into only two actions: passing monitors to the next owner when they should be released and conditionally waking threads if all conditions are met.


\subsection{Loose Object Definitions}
\label{s:LooseObjectDefinitions}

In an object-oriented programming-language, a class includes an exhaustive list of operations.
However, new members can be added via static inheritance or dynamic members, \eg JavaScript~\cite{JavaScript}.
Similarly, monitor routines can be added at any time in \CFA, making it less clear for programmers and more difficult to implement.
\begin{cfa}
monitor M { ... };
void `f`( M & mutex m );
void g( M & mutex m ) { waitfor( `f` ); }	$\C{// clear which f}$
void `f`( M & mutex m, int );				$\C{// different f}$
void h( M & mutex m ) { waitfor( `f` ); }	$\C{// unclear which f}$
\end{cfa}
Hence, the cfa-code for entering a monitor looks like:
\begin{cfa}
if ( $\textrm{\textit{monitor is free}}$ ) $\LstCommentStyle{// \color{red}enter}$
else if ( $\textrm{\textit{already own monitor}}$ ) $\LstCommentStyle{// \color{red}continue}$
else if ( $\textrm{\textit{monitor accepts me}}$ ) $\LstCommentStyle{// \color{red}enter}$
else $\LstCommentStyle{// \color{red}block}$
\end{cfa}
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 \emph{monitor accepts me} is much harder to implement depending on the constraints put on the monitors.
Figure~\ref{fig:ClassicalMonitor} shows monitors are often expressed as an entry (calling) queue, some acceptor queues, and an urgent stack/queue.

\begin{figure}
\centering
\subfloat[Classical monitor] {
\label{fig:ClassicalMonitor}
{\resizebox{0.45\textwidth}{!}{\input{monitor.pstex_t}}}
}% subfloat
\quad
\subfloat[Bulk acquire monitor] {
\label{fig:BulkMonitor}
{\resizebox{0.45\textwidth}{!}{\input{ext_monitor.pstex_t}}}
}% subfloat
\caption{Monitor Implementation}
\label{f:MonitorImplementation}
\end{figure}

For a fixed (small) number of mutex routines (\eg 128), the accept check reduces to a bitmask of allowed callers, which can be checked with a single instruction.
This approach requires a unique dense ordering of routines with a small upper-bound and the ordering must be consistent across translation units.
For object-oriented languages these constraints are common, but \CFA mutex routines can be added in any scope and are only visible in certain translation unit, precluding program-wide dense-ordering among mutex routines.

Figure~\ref{fig:BulkMonitor} shows the \CFA monitor implementation.
The mutex routine called is associated with each thread on the entry queue, while a list of acceptable routines is kept separately.
The accepted list is a variable-sized array of accepted routine pointers, so the single instruction bitmask comparison is replaced by dereferencing a pointer followed by a (usually short) linear search.


\subsection{Multi-Monitor Scheduling}
\label{s:Multi-MonitorScheduling}

External scheduling, like internal scheduling, becomes significantly more complex for multi-monitor semantics.
Even in the simplest case, new semantics needs to be established.
\newpage
\begin{cfa}
monitor M { ... };
void f( M & mutex m1 );
void g( M & mutex m1, M & mutex m2 ) {
	waitfor( f ); 							$\C{\color{red}// pass m1 or m2 to f?}$
}
\end{cfa}
The solution is for the programmer to disambiguate:
\begin{cfa}
	waitfor( f, m2 );						$\C{\color{red}// wait for call to f with argument m2}$
\end{cfa}
Both locks are acquired by routine @g@, so when routine @f@ is called, the lock for monitor @m2@ is passed from @g@ to @f@, while @g@ still holds lock @m1@.
This behaviour can be extended to the multi-monitor @waitfor@ statement.
\begin{cfa}
monitor M { ... };
void f( M & mutex m1, M & mutex m2 );
void g( M & mutex m1, M & mutex m2 ) {
	waitfor( f, m1, m2 );					$\C{\color{red}// wait for call to f with arguments m1 and m2}$
}
\end{cfa}
Again, the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired by the accepting routine.
Also, the order of the monitors in a @waitfor@ statement is unimportant.

Figure~\ref{f:UnmatchedMutexSets} shows an example where, for internal and external scheduling with multiple monitors, a signalling or accepting thread must match exactly, \ie partial matching results in waiting.
For both examples, the set of monitors is disjoint so unblocking is impossible.

\begin{figure}
\lstDeleteShortInline@%
\begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
\begin{cfa}
monitor M1 {} m11, m12;
monitor M2 {} m2;
condition c;
void f( M1 & mutex m1, M2 & mutex m2 ) {
	signal( c );
}
void g( M1 & mutex m1, M2 & mutex m2 ) {
	wait( c );
}
g( `m11`, m2 ); // block on wait
f( `m12`, m2 ); // cannot fulfil
\end{cfa}
&
\begin{cfa}
monitor M1 {} m11, m12;
monitor M2 {} m2;

void f( M1 & mutex m1, M2 & mutex m2 ) {

}
void g( M1 & mutex m1, M2 & mutex m2 ) {
	waitfor( f, m1, m2 );
}
g( `m11`, m2 ); // block on accept
f( `m12`, m2 ); // cannot fulfil
\end{cfa}
\end{tabular}
\lstMakeShortInline@%
\caption{Unmatched \protect\lstinline@mutex@ sets}
\label{f:UnmatchedMutexSets}
\end{figure}


\subsection{Extended \protect\lstinline@waitfor@}

Figure~\ref{f:ExtendedWaitfor} show the extended form of the @waitfor@ statement to conditionally accept one of a group of mutex routines, with a specific action to be performed \emph{after} the mutex routine finishes.
For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding member(s) must exist.
The \emph{conditional-expression} of a @when@ may call a routine, but the routine must not block or context switch.
If there are multiple acceptable mutex calls, selection occurs top-to-bottom (prioritized) in the @waitfor@ clauses, whereas some programming languages with similar mechanisms accept non-deterministically for this case, \eg Go \lstinline[morekeywords=select]@select@.
If some accept guards are true and there are no outstanding calls to these members, the acceptor is accept-blocked until a call to one of these members is made.
If all the accept guards are false, the statement does nothing, unless there is a terminating @else@ clause with a true guard, which is executed instead.
Hence, the terminating @else@ clause allows a conditional attempt to accept a call without blocking.
If there is a @timeout@ clause, it provides an upper bound on waiting.
If both a @timeout@ clause and an @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered.
In all cases, the statement following is executed \emph{after} a clause is executed to know which of the clauses executed.

\begin{figure}
\begin{cfa}
`when` ( $\emph{conditional-expression}$ )	$\C{// optional guard}$
	waitfor( $\emph{mutex-member-name}$ )
		$\emph{statement}$					$\C{// action after call}$
`or` `when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
	waitfor( $\emph{mutex-member-name}$ )
		$\emph{statement}$					$\C{// action after call}$
`or`	...									$\C{// list of waitfor clauses}$
`when` ( $\emph{conditional-expression}$ )	$\C{// optional guard}$
	`timeout`								$\C{// optional terminating timeout clause}$
		$\emph{statement}$					$\C{// action after timeout}$
`when` ( $\emph{conditional-expression}$ )	$\C{// optional guard}$
	`else`									$\C{// optional terminating clause}$
		$\emph{statement}$					$\C{// action when no immediate calls}$
\end{cfa}
\caption{Extended \protect\lstinline@waitfor@}
\label{f:ExtendedWaitfor}
\end{figure}

Note, a group of conditional @waitfor@ clauses is \emph{not} the same as a group of @if@ statements, e.g.:
\begin{cfa}
if ( C1 ) waitfor( mem1 );			 when ( C1 ) waitfor( mem1 );
else if ( C2 ) waitfor( mem2 );		or when ( C2 ) waitfor( mem2 );
\end{cfa}
The left example accepts only @mem1@ if @C1@ is true or only @mem2@ if @C2@ is true.
The right example accepts either @mem1@ or @mem2@ if @C1@ and @C2@ are true.

An interesting use of @waitfor@ is accepting the @mutex@ destructor to know when an object is deallocated.
\begin{cfa}
void insert( Buffer(T) & mutex buffer, T elem ) with( buffer ) {
	if ( count == 10 )
		waitfor( remove, buffer ) {
			// insert elem into buffer
		} or `waitfor( ^?{}, buffer )` throw insertFail;
}
\end{cfa}
When the buffer is deallocated, the current waiter is unblocked and informed, so it can perform an appropriate action.
However, the basic @waitfor@ semantics do not support this functionality, since using an object after its destructor is called is undefined.
Therefore, to make this useful capability work, the semantics for accepting the destructor is the same as @signal@, \ie the call to the destructor is placed on the urgent queue and the acceptor continues execution, which throws an exception to the acceptor and then the caller is unblocked from the urgent queue to deallocate the object.
Accepting the destructor is an idiomatic way to terminate a thread in \CFA.


\subsection{\protect\lstinline@mutex@ Threads}

Threads in \CFA are monitors to allow direct communication among threads, \ie threads can have mutex routines that are called by other threads.
Hence, all monitor features are available when using threads.
The following shows an example of two threads directly calling each other and accepting calls from each other in a cycle.
\begin{cfa}
thread Ping {} pi;
thread Pong {} po;
void ping( Ping & mutex ) {}
void pong( Pong & mutex ) {}
int main() {}
\end{cfa}
\vspace{-0.8\baselineskip}
\begin{cquote}
\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
\begin{cfa}
void main( Ping & pi ) {
	for ( int i = 0; i < 10; i += 1 ) {
		`waitfor( ping, pi );`
		`pong( po );`
	}
}
\end{cfa}
&
\begin{cfa}
void main( Pong & po ) {
	for ( int i = 0; i < 10; i += 1 ) {
		`ping( pi );`
		`waitfor( pong, po );`
	}
}
\end{cfa}
\end{tabular}
\end{cquote}
% \lstMakeShortInline@%
% \caption{Threads ping/pong using external scheduling}
% \label{f:pingpong}
% \end{figure}
Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start (and possibly complete) before the program main starts.


\subsection{Low-level Locks}

For completeness and efficiency, \CFA provides a standard set of low-level locks: recursive mutex, condition, semaphore, barrier, \etc, and atomic instructions: @fetchAssign@, @fetchAdd@, @testSet@, @compareSet@, \etc.


\section{Parallelism}

Historically, computer performance was about processor speeds.
However, with heat dissipation being a direct consequence of speed increase, parallelism is the new source for increased performance~\cite{Sutter05, Sutter05b}.
Now, high-performance applications must care about parallelism, which requires concurrency.
The lowest-level approach of parallelism is to use \newterm{kernel threads} in combination with semantics like @fork@, @join@, \etc.
However, kernel threads are better as an implementation tool because of complexity and higher cost.
Therefore, different abstractions are often layered onto kernel threads to simplify them, \eg pthreads.


\subsection{User Threads with Preemption}

A direct improvement on kernel threads is user threads, \eg Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
This approach provides an interface that matches the language paradigms, more control over concurrency by the language runtime, and an abstract (and portable) interface to the underlying kernel threads across operating systems.
In many cases, user threads can be used on a much larger scale (100,000 threads).
Like kernel threads, user threads support preemption, which maximizes nondeterminism, but introduces the same concurrency errors: race, livelock, starvation, and deadlock.
\CFA adopts user-threads as they represent the truest realization of concurrency and can build any other concurrency approach, \eg thread pools and actors~\cite{Actors}.


\subsection{User Threads without Preemption (Fiber)}
\label{s:fibers}

A variant of user thread is \newterm{fibers}, which removes preemption, \eg Go~\cite{Go} @goroutine@s.
Like functional programming, which removes mutation and its associated problems, removing preemption from concurrency reduces nondeterminism, making race and deadlock errors more difficult to generate.
However, preemption is necessary for concurrency that relies on spinning, so there are a class of problems that cannot be programmed without preemption.


\subsection{Thread Pools}

In contrast to direct threading is indirect \newterm{thread pools}, where small jobs (work units) are inserted into a work pool for execution.
If the jobs are dependent, \ie interact, there is an implicit/explicit dependency graph that ties them together.
While removing direct concurrency, and hence the amount of context switching, thread pools significantly limit the interaction that can occur among jobs.
Indeed, jobs should not block because that also blocks the underlying thread, which effectively means the CPU utilization, and therefore throughput, suffers.
While it is possible to tune the thread pool with sufficient threads, it becomes difficult to obtain high throughput and good core utilization as job interaction increases.
As well, concurrency errors return, which threads pools are suppose to mitigate.


\section{\protect\CFA Runtime Structure}

Figure~\ref{f:RunTimeStructure} illustrates the runtime structure of a \CFA program.
In addition to the new kinds of objects introduced by \CFA, there are two more runtime entities used to control parallel execution: cluster and (virtual) processor.
An executing thread is illustrated by its containment in a processor.

\begin{figure}
\centering
\input{RunTimeStructure}
\caption{\CFA Runtime Structure}
\label{f:RunTimeStructure}
\end{figure}


\subsection{Cluster}
\label{s:RuntimeStructureCluster}

A \newterm{cluster} is a collection of threads and virtual processors (abstract kernel-thread) that execute the threads (like a virtual machine).
The purpose of a cluster is to control the amount of parallelism that is possible among threads, plus scheduling and other execution defaults.
The default cluster-scheduler is single-queue multi-server, which provides automatic load-balancing of threads on processors.
However, the scheduler is pluggable, supporting alternative schedulers.
If several clusters exist, both threads and virtual processors, can be explicitly migrated from one cluster to another.
No automatic load balancing among clusters is performed by \CFA.

When a \CFA program begins execution, it creates a user cluster with a single processor and a special processor to handle preemption that does not execute user threads.
The user cluster is created to contain the application user-threads.
Having all threads execute on the one cluster often maximizes utilization of processors, which minimizes runtime.
However, because of limitations of the underlying operating system, heterogeneous hardware, or scheduling requirements (real-time), multiple clusters are sometimes necessary.


\subsection{Virtual Processor}
\label{s:RuntimeStructureProcessor}

A virtual processor is implemented by a kernel thread (\eg UNIX process), which is subsequently scheduled for execution on a hardware processor by the underlying operating system.
Programs may use more virtual processors than hardware processors.
On a multiprocessor, kernel threads are distributed across the hardware processors resulting in virtual processors executing in parallel.
(It is possible to use affinity to lock a virtual processor onto a particular hardware processor~\cite{affinityLinux, affinityWindows, affinityFreebsd, affinityNetbsd, affinityMacosx}, which is used when caching issues occur or for heterogeneous hardware processors.)
The \CFA runtime attempts to block unused processors and unblock processors as the system load increases;
balancing the workload with processors is difficult.
Preemption occurs on virtual processors rather than user threads, via operating-system interrupts.
Thus virtual processors execute user threads, where preemption frequency applies to a virtual processor, so preemption occurs randomly across the executed user threads.
Turning off preemption transforms user threads into fibers.


\subsection{Debug Kernel}

There are two versions of the \CFA runtime kernel: debug and non-debug.
The debugging version has many runtime checks and internal assertions, \eg stack (non-writable) guard page, and checks for stack overflow whenever context switches occur among coroutines and threads, which catches most stack overflows.
After a program is debugged, the non-debugging version can be used to decrease space and increase performance.


\section{Implementation}
\label{s:Implementation}

Currently, \CFA has fixed-sized stacks, where the stack size can be set at coroutine/thread creation but with no subsequent growth.
Schemes exist for dynamic stack-growth, such as stack copying and chained stacks.
However, stack copying requires pointer adjustment to items on the stack, which is impossible without some form of garbage collection.
As well, chained stacks require all modules be recompiled to use this feature, which breaks backward compatibility with existing C libraries.
In the long term, it is likely C libraries will migrate to stack chaining to support concurrency, at only a minimal cost to sequential programs.
Nevertheless, experience teaching \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue in most concurrent programs.

A primary implementation challenge is avoiding contention from dynamically allocating memory because of bulk acquire, \eg the internal-scheduling design is (almost) free of allocations.
All blocking operations are made by parking threads onto queues, therefore all queues are designed with intrusive nodes, where each node has preallocated link fields for chaining.
Furthermore, several bulk-acquire operations need a variable amount of memory.
This storage is allocated at the base of a thread's stack before blocking, which means programmers must add a small amount of extra space for stacks.

In \CFA, ordering of monitor acquisition relies on memory ordering to prevent deadlock~\cite{Havender68}, because all objects have distinct non-overlapping memory layouts, and mutual-exclusion for a monitor is only defined for its lifetime.
When a mutex call is made, pointers to the concerned monitors are aggregated into a variable-length array and sorted.
This array persists for the entire duration of the mutual exclusion and is used extensively for synchronization operations.

To improve performance and simplicity, context switching occurs inside a routine call, so only callee-saved registers are copied onto the stack and then the stack register is switched;
the corresponding registers are then restored for the other context.
Note, the instruction pointer is untouched since the context switch is always inside the same routine.
Unlike coroutines, threads do not context switch among each other;
they context switch to the cluster scheduler.
This method is a 2-step context-switch and provides a clear distinction between user and kernel code, where scheduling and other system operations happen.
The alternative 1-step context-switch uses the \emph{from} thread's stack to schedule and then context-switches directly to the \emph{to} thread's stack.
Experimental results (not presented) show the performance of these two approaches is virtually equivalent, because both approaches are dominated by locking to prevent a race condition.

All kernel threads (@pthreads@) created a stack.
Each \CFA virtual processor is implemented as a coroutine and these coroutines run directly on the kernel-thread stack, effectively stealing this stack.
The exception to this rule is the program main, \ie the initial kernel thread that is given to any program.
In order to respect C expectations, the stack of the initial kernel thread is used by program main rather than the main processor, allowing it to grow dynamically as in a normal C program.

Finally, an important aspect for a complete threading system is preemption, which introduces extra non-determinism via transparent interleaving, rather than cooperation among threads for proper scheduling and processor fairness from long-running threads.
Because preemption frequency is usually long (1 millisecond) performance cost is negligible.
Preemption is normally handled by setting a count-down timer on each virtual processor.
When the timer expires, an interrupt is delivered, and the interrupt handler resets the count-down timer, and if the virtual processor is executing in user code, the signal handler performs a user-level context-switch, or if executing in the language runtime-kernel, the preemption is ignored or rolled forward to the point where the runtime kernel context switches back to user code.
Multiple signal handlers may be pending.
When control eventually switches back to the signal handler, it returns normally, and execution continues in the interrupted user thread, even though the return from the signal handler may be on a different kernel thread than the one where the signal is delivered.
The only issue with this approach is that signal masks from one kernel thread may be restored on another as part of returning from the signal handler;
therefore, the same signal mask is required for all virtual processors in a cluster.

However, on current UNIX systems:
\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}
Hence, the timer-expiry signal, which is generated \emph{externally} by the UNIX kernel to the UNIX process, is delivered to any of its UNIX subprocesses (kernel threads).
To ensure each virtual processor receives its own preemption signals, a discrete-event simulation is run on a special virtual processor, and only it sets and receives timer events.
Virtual processors register an expiration time with the discrete-event simulator, which is inserted in sorted order.
The simulation sets the count-down timer to the value at the head of the event list, and when the timer expires, all events less than or equal to the current time are processed.
Processing a preemption event sends an \emph{internal} @SIGUSR1@ signal to the registered virtual processor, which is always delivered to that processor.


\section{Performance}
\label{results}

To verify the implementation of the \CFA runtime, a series of microbenchmarks are performed comparing \CFA with other widely used programming languages with concurrency.
Table~\ref{t:machine} shows the specifications of the computer used to run the benchmarks, and the versions of the software used in the comparison.

\begin{table}
\centering
\caption{Experiment environment}
\label{t:machine}

\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 GHz \\
\hline
CPU(s)				& 64 					& L1d cache 	& 16 KiB \\
\hline
Thread(s) per core	& 2 					& L1i cache 	& 64 KiB \\
\hline
Core(s) per socket	& 8 					& L2 cache 		& 2048 KiB \\
\hline
Socket(s)			& 4 					& L3 cache 		& 6144 KiB \\
\hline
\hline
Operating system	& Ubuntu 16.04.3 LTS	& Kernel		& Linux 4.4-97-generic \\
\hline
gcc					& 6.3	 				& \CFA			& 1.0.0 \\
\hline
Java				& OpenJDK-9 			& Go			& 1.9.2 \\
\hline
\end{tabular}
\end{table}

All benchmarks are run using the following harness:
\begin{cfa}
unsigned int N = 10_000_000;
#define BENCH( run ) Time before = getTimeNsec(); run; Duration result = (getTimeNsec() - before) / N;
\end{cfa}
The method used to get time is @clock_gettime( CLOCK_REALTIME )@.
Each benchmark is performed @N@ times, where @N@ varies depending on the benchmark;
the total time is divided by @N@ to obtain the average time for a benchmark.
All omitted tests for other languages are functionally identical to the shown \CFA test.


\paragraph{Context-Switching}

In procedural programming, the cost of a routine call is important as modularization (refactoring) increases.
(In many cases, a compiler inlines routine calls to eliminate this cost.)
Similarly, when modularization extends to coroutines/tasks, the time for a context switch becomes a relevant factor.
The coroutine context-switch is 2-step using resume/suspend, \ie from resumer to suspender and from suspender to resumer.
The thread context switch is 2-step using yield, \ie enter and return from the runtime kernel.
Figure~\ref{f:ctx-switch} shows the code for coroutines/threads with all results in Table~\ref{tab:ctx-switch}.
The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling.

\begin{figure}
\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}

\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
coroutine C {} c;
void main( C & ) { for ( ;; ) { @suspend();@ } }
int main() {
	BENCH(
		for ( size_t i = 0; i < N; i += 1 ) { @resume( c );@ } )
	sout | result`ns;
}
\end{cfa}
\end{lrbox}

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


int main() {
	BENCH(
		for ( size_t i = 0; i < N; i += 1 ) { @yield();@ } )
	sout | result`ns;
}
\end{cfa}
\end{lrbox}

\subfloat[Coroutine]{\usebox\myboxA}
\quad
\subfloat[Thread]{\usebox\myboxB}
\captionof{figure}{\CFA context-switch benchmark}
\label{f:ctx-switch}

\centering

\captionof{table}{Context switch comparison (nanoseconds)}
\label{tab:ctx-switch}
\bigskip
\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
\cline{2-4}
\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
\hline
Kernel Thread	& 333.5	& 332.96	& 4.1 \\
\CFA Coroutine	& 49		& 48.68	& 0.47    \\
\CFA Thread		& 105		& 105.57	& 1.37 \\
\uC Coroutine	& 44		& 44		& 0 \\
\uC Thread		& 100		& 99.29	& 0.96 \\
Goroutine		& 145		& 147.25	& 4.15 \\
Java Thread		& 373.5	& 375.14	& 8.72 \\
\hline
\end{tabular}

\bigskip
\bigskip

\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
\begin{cfa}
monitor M { ... } m1/*, m2, m3, m4*/;
void __attribute__((noinline)) do_call( M & mutex m/*, m2, m3, m4*/ ) {}
int main() {
	BENCH( for( size_t i = 0; i < N; i += 1 ) { @do_call( m1/*, m2, m3, m4*/ );@ } )
	sout | result`ns;
}
\end{cfa}
\captionof{figure}{\CFA acquire/release mutex benchmark}
\label{f:mutex}

\centering

\captionof{table}{Mutex comparison (nanoseconds)}
\label{tab:mutex}
\bigskip

\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
\cline{2-4}
\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
\hline
C routine					& 2		& 2		& 0    \\
FetchAdd + FetchSub			& 26		& 26		& 0    \\
Pthreads Mutex Lock			& 31		& 31.71	& 0.97 \\
\uC @monitor@ member routine		& 31		& 31		& 0    \\
\CFA @mutex@ routine, 1 argument	& 46		& 46.68	& 0.93  \\
\CFA @mutex@ routine, 2 argument	& 84		& 85.36	& 1.99 \\
\CFA @mutex@ routine, 4 argument	& 158		& 161		& 4.22 \\
Java synchronized routine		& 27.5	& 29.79	& 2.93  \\
\hline
\end{tabular}
\end{figure}


\paragraph{Mutual-Exclusion}

Mutual exclusion is measured by entering/leaving a critical section.
For monitors, entering and leaving a monitor routine is measured.
Figure~\ref{f:mutex} shows the code for \CFA with all results in Table~\ref{tab:mutex}.
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.
Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.


\paragraph{Internal Scheduling}

Internal scheduling is measured by waiting on and signalling a condition variable.
Figure~\ref{f:int-sched} shows the code for \CFA, with results in Table~\ref{tab:int-sched}.
Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
Java scheduling is significantly greater because the benchmark explicitly creates multiple thread in order to prevent the JIT from making the program sequential, \ie removing all locking.

\begin{figure}
\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
\begin{cfa}
volatile int go = 0;
condition c;
monitor M { ... } m;
void __attribute__((noinline)) do_call( M & mutex a1 ) { signal( c ); }
thread T {};
void main( T & this ) {
	while ( go == 0 ) { yield(); }	// wait for other thread to start
	while ( go == 1 ) { @do_call( m );@ }
}
int  __attribute__((noinline)) do_wait( M & mutex m ) {
	go = 1;	// continue other thread
	BENCH( for ( size_t i = 0; i < N; i += 1 ) { @wait( c );@ } );
	go = 0;	// stop other thread
	sout | result`ns;
}
int main() {
	T t;
	do_wait( m );
}
\end{cfa}
\captionof{figure}{\CFA Internal-scheduling benchmark}
\label{f:int-sched}

\centering
\captionof{table}{Internal-scheduling comparison (nanoseconds)}
\label{tab:int-sched}
\bigskip

\begin{tabular}{|r|*{3}{D{.}{.}{5.2}|}}
\cline{2-4}
\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
\hline
Pthreads Condition Variable		& 6005	& 5681.43 	& 835.45 \\
\uC @signal@					& 324		& 325.54 	& 3,02   \\
\CFA @signal@, 1 @monitor@		& 368.5		& 370.61	& 4.77   \\
\CFA @signal@, 2 @monitor@		& 467		& 470.5	& 6.79   \\
\CFA @signal@, 4 @monitor@		& 700.5		& 702.46	& 7.23  \\
Java @notify@					& 15471	& 172511	& 5689 \\
\hline
\end{tabular}
\end{figure}


\paragraph{External Scheduling}

External scheduling is measured by accepting a call using the @waitfor@ statement (@_Accept@ in \uC).
Figure~\ref{f:ext-sched} shows the code for \CFA, with results in Table~\ref{tab:ext-sched}.
Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.

\begin{figure}
\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
\begin{cfa}
volatile int go = 0;
monitor M { ... } m;
thread T {};
void __attribute__((noinline)) do_call( M & mutex ) {}
void main( T & ) {
	while ( go == 0 ) { yield(); }	// wait for other thread to start
	while ( go == 1 ) { @do_call( m );@ }
}
int __attribute__((noinline)) do_wait( M & mutex m ) {
	go = 1;	// continue other thread
	BENCH( for ( size_t i = 0; i < N; i += 1 ) { @waitfor( do_call, m );@ } )
	go = 0;	// stop other thread
	sout | result`ns;
}
int main() {
	T t;
	do_wait( m );
}
\end{cfa}
\captionof{figure}{\CFA external-scheduling benchmark}
\label{f:ext-sched}

\centering

\captionof{table}{External-scheduling comparison (nanoseconds)}
\label{tab:ext-sched}
\bigskip
\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
\cline{2-4}
\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
\hline
\uC @_Accept@				& 358		& 359.11	& 2.53  \\
\CFA @waitfor@, 1 @monitor@	& 359		& 360.93	& 4.07  \\
\CFA @waitfor@, 2 @monitor@	& 450		& 449.39	& 6.62  \\
\CFA @waitfor@, 4 @monitor@	& 652		& 655.64	& 7.73 \\
\hline
\end{tabular}

\bigskip
\medskip

\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
\begin{cfa}
thread MyThread {};
void main( MyThread & ) {}
int main() {
	BENCH( for ( size_t i = 0; i < N; i += 1 ) { @MyThread m;@ } )
	sout | result`ns;
}
\end{cfa}
\captionof{figure}{\CFA object-creation benchmark}
\label{f:creation}

\centering

\captionof{table}{Creation comparison (nanoseconds)}
\label{tab:creation}
\bigskip

\begin{tabular}{|r|*{3}{D{.}{.}{5.2}|}}
\cline{2-4}
\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} & \multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
\hline
Pthreads				& 28091		& 28073.39	& 163.1  \\
\CFA Coroutine Lazy		& 6			& 6.07		& 0.26   \\
\CFA Coroutine Eager	& 520		& 520.61	& 2.04   \\
\CFA Thread				& 2032	& 2016.29	& 112.07  \\
\uC Coroutine			& 106		& 107.36	& 1.47   \\
\uC Thread				& 536.5	& 537.07	& 4.64   \\
Goroutine				& 3103	& 3086.29	& 90.25  \\
Java Thread				& 103416.5	& 103732.29	& 1137 \\
\hline
\end{tabular}
\end{figure}


\paragraph{Object Creation}

Object creation is measured by creating/deleting the specific kind of concurrent object.
Figure~\ref{f:creation} shows the code for \CFA, with results in Table~\ref{tab:creation}.
The only note here is that the call stacks of \CFA coroutines are lazily created, therefore without priming the coroutine to force stack creation, the creation cost is artificially low.


\section{Conclusion}

This paper demonstrates a concurrency API that is simple, efficient, and able to build higher-level concurrency features.
The approach provides concurrency based on a preemptive M:N user-level threading-system, executing in clusters, which encapsulate scheduling of work on multiple kernel threads providing parallelism.
The M:N model is judged to be efficient and provide greater flexibility than a 1:1 threading model.
High-level objects (monitor/task) are the core mechanism for mutual exclusion and synchronization.
A novel aspect is allowing multiple mutex-objects to be accessed simultaneously reducing the potential for deadlock for this complex scenario.
These concepts and the entire \CFA runtime-system are written in the \CFA language, demonstrating the expressiveness of the \CFA language.
Performance comparisons with other concurrent systems/languages show the \CFA approach is competitive across all low-level operations, which translates directly into good performance in well-written concurrent applications.
C programmers should feel comfortable using these mechanisms for developing concurrent applications, with the ability to obtain maximum available performance by mechanisms at the appropriate level.


\section{Future Work}

While concurrency in \CFA has a strong start, development is still underway and there are missing features.

\paragraph{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, allowing the scheduler to be adjusted to the requirements of the workload.
However, to be truly flexible, a pluggable scheduler is necessary.
Currently, the \CFA pluggable scheduler is too simple to handle complex scheduling, \eg quality of service and real-time, where the scheduler must interact with mutex objects to deal with issues like priority inversion.

\paragraph{Non-Blocking I/O}
\label{futur:nbio}

Many modern workloads are not bound by computation but IO operations, a common case being web servers and XaaS~\cite{XaaS} (anything as a service).
These types of workloads require significant engineering to amortizing costs of blocking IO-operations.
At its core, non-blocking I/O is an operating-system level feature queuing IO operations, \eg network operations, and registering for notifications instead of waiting for requests to complete.
Current trends use asynchronous programming like callbacks, futures, and/or promises, \eg Node.js~\cite{NodeJs} for JavaScript, Spring MVC~\cite{SpringMVC} for Java, and Django~\cite{Django} for Python.
However, these solutions lead to code that is hard to create, read and maintain.
A better approach is to tie non-blocking I/O into the concurrency system to provide ease of use with low overhead, \eg thread-per-connection web-services.
A non-blocking I/O library is currently under development for \CFA.

\paragraph{Other Concurrency Tools}
\label{futur:tools}

While monitors offer flexible and powerful concurrency for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
Examples of such tools can include 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.
As well, new \CFA extensions should make it possible to create a uniform interface for virtually all mutual exclusion, including monitors and low-level locks.

\paragraph{Implicit Threading}
\label{futur:implcit}

Basic concurrent (embarrassingly parallel) applications can benefit greatly from implicit concurrency, where sequential programs are converted to concurrent, possibly with some help from pragmas to guide the conversion.
This type of concurrency can be achieved both at the language level and at the library level.
The canonical example of implicit concurrency is concurrent nested @for@ loops, which are amenable to divide and conquer algorithms~\cite{uC++book}.
The \CFA language features should make it possible to develop a reasonable number of implicit concurrency mechanism to solve basic HPC data-concurrency problems.
However, implicit concurrency is a restrictive solution with significant limitations, so it can never replace explicit concurrent programming.


\section{Acknowledgements}

The authors would like to recognize the design assistance of Aaron Moss, Rob Schluntz and Andrew Beach on the features described in this paper.
Funding for this project has been provided by Huawei Ltd.\ (\url{http://www.huawei.com}), and Peter Buhr is partially funded by the Natural Sciences and Engineering Research Council of Canada.

{%
\fontsize{9bp}{12bp}\selectfont%
\bibliography{pl,local}
}%

\end{document}

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