\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{enumitem}
\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}
\setlength{\multicolsep}{6.0pt plus 2.0pt minus 1.5pt}

\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, thread,
		_Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
		virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
	moredirectives={defined,include_next},
	% 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,
}

\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,
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]{`}{`},
}

% Go programming language: https://github.com/julienc91/listings-golang/blob/master/listings-golang.sty
\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]{`}{`},
	% 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
		{<-}{\makebox[2ex][c]{\textrm{\textless}\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}}2,
}

\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=Golang,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 written in \CFA.
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 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 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,Cforall} and its runtime, which is written entirely in \CFA.
\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.
In many ways, \CFA is to C as Scala~\cite{Scala} is to Java, providing a \emph{research vehicle} for new typing and control-flow capabilities on top of a highly popular programming language allowing immediate dissemination.
Within the \CFA framework, new control-flow features are created from scratch because 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}, and \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-9 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, 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,Marcel}, 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{Adya02,vonBehren03}.
Finally, performant user-threading implementations (both time and space) meet or exceed 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, language solutions allow matching constructs with language paradigm, i.e., imperative and functional languages often have different presentations of the same concept to fit their programming model.

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} (random wakeup~\cite[\S~8]{Buhr05a}) and \emph{barging} (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 often 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.
(Author experience 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}
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 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 stateful function is an old idea~\cite{Conway63,Marlin80} that is new again~\cite{C++20Coroutine19}, where execution is 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}

Stateful functions appear as generators, coroutines, and threads, where presentations are based on function objects or pointers~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
For example, Python presents generators as a function object:
\begin{python}
def Gen():
	... `yield val` ...
gen = Gen()
for i in range( 10 ):
	print( next( gen ) )
\end{python}
Boost presents 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}
and many languages present threading using function pointers, @pthreads@~\cite{Butenhof97}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}, \eg pthreads:
\begin{cfa}
void * rtn( void * arg ) { ... }
int i = 3, rc;
pthread_t t; $\C{// thread id}$
`rc = pthread_create( &t, rtn, (void *)i );` $\C{// create and initialized task, type-unsafe input parameter}$
\end{cfa}
% void mycor( pthread_t cid, void * arg ) {
% 	int * value = (int *)arg;				$\C{// type unsafe, pointer-size only}$
% 	// thread 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}$
% }
\CFA's preferred presentation model for generators/coroutines/threads is a hybrid of objects and functions, with an object-oriented flavour.
Essentially, the generator/coroutine/thread function is semantically coupled with a generator/coroutine/thread custom type.
The custom type solves several issues, while accessing the underlying mechanisms used by the custom types is still allowed.


\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.
A series of different kinds of generators and their implementation demonstrate how this goal is accomplished.

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 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 one 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 is declaration initialization.
Figure~\ref{f:CFAFibonacciGen} shows the \CFA approach, which also has a manual closure, but replaces the structure with a custom \CFA @generator@ type.
This generator type is then connected to a function that \emph{must be named \lstinline|main|},\footnote{
The name \lstinline|main| has special meaning in C, specifically the function where a program starts execution.
Hence, overloading this name for other starting points (generator/coroutine/thread) is a logical extension.}
called a \emph{generator main},which takes as its only parameter a reference to the generator type.
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 ) { return `resume( fib )`.fn; } $\C[3.9in]{// function-call interface}$
int ?()( Fib & fib, int N ) { for ( N - 1 ) `fib()`; return `fib()`; } $\C{// use function-call interface to skip N values}$
double ?()( Fib & fib ) { return (int)`fib()` / 3.14159; } $\C{// different return type, cast prevents recursive call}\CRT$
sout | (int)f1() | (double)f1() | f2( 2 ); // alternative 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.
(This restriction is removed by the coroutine in Section~\ref{s:Coroutine}.)
This requirement follows from the generality of variable-size local-state, \eg local state with a variable-length array requires dynamic allocation because the array size is unknown at compile time.
However, dynamic allocation significantly increases the cost of generator creation/destruction and is a show-stopper for embedded real-time 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.
With respect to safety, we believe static analysis can discriminate local state from temporary variables in a generator, \ie variable usage spanning @suspend@, and generate a compile-time error.
Finally, our current experience is that most generator problems have simple data state, including local state, but complex execution state, so the burden of creating the generator type is small.
As well, C programmers are not afraid of 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 manually hoisted into the generator type.
% Manually, detecting and hoisting local-state variables is easy when the number is small.
In contrast, 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 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 any 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.
This semantics is basically a tail-call optimization, which compilers already perform.
The example shows the assembly code to undo the generator's entry code before the direct jump.
This assembly code 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, \eg LLVM has various coroutine support~\cite{CoroutineTS}, and \CFA can leverage this support should it fork @clang@.

\begin{figure}
\centering
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`generator PingPong` {
	const char * name;
	int N;
	int i;				// local state
	PingPong & partner; // rebindable reference
};

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,0}, pong = {"pong",N,0};
	&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;
	int N, i;
	struct PingPong * partner;
	void * next;
} PingPong;
#define PPCtor(name, N) {name,N,0,NULL,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 \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.
Coroutine 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.
A series of different kinds of coroutines and their implementation demonstrate how coroutines extend generators.

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 function, 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 functions, \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 function @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}
\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.

\begin{figure}
\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}

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 is to context switch back to the first resumer (starter) once the coroutine ends.
This semantics 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, such as forcing the cycle forward (backward) to a safe point before starting termination.

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{Generator / Coroutine Implementation}

A significant implementation challenge for generators/coroutines (and threads in Section~\ref{s:threads}) is adding extra fields to the custom types and related functions, \eg inserting code after/before the coroutine constructor/destructor and @main@ to create/initialize/de-initialize/destroy any extra fields, \eg stack.
There are several solutions to these problem, which follow from the object-oriented flavour of adopting custom types.

For object-oriented languages, inheritance is used to provide extra fields and code via explicit inheritance:
\begin{cfa}[morekeywords={class,inherits}]
class myCoroutine inherits baseCoroutine { ... }
\end{cfa}
% The problem is that the programming language and its tool chain, \eg debugger, @valgrind@, need to understand @baseCoroutine@ because it infers special property, so type @baseCoroutine@ becomes a de facto keyword and all types inheriting from it are implicitly custom types.
The problem is that some special properties are not handled by existing language semantics, \eg the execution of constructors/destructors is in the wrong order to implicitly start threads because the thread must start \emph{after} all constructors as it relies on a completely initialized object, but the inherited constructor runs \emph{before} the derived.
Alternatives, such as explicitly starting threads as in Java, are repetitive and forgetting to call start is a common source of errors.
An alternative is composition:
\begin{cfa}
struct myCoroutine {
	... // declaration/communication variables
	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.

\CFA custom types make any special properties explicit to the language and its tool chain, \eg the language code-generator knows where to inject code
% and when it is unsafe to perform certain optimizations,
and IDEs using simple parsing can find and manipulate types with special properties.
The downside of this approach is that it makes custom types a special case in the language.
Users wanting to extend custom types or build their own can only do so in ways offered by the language.
Furthermore, implementing custom types without language support may display the power of a programming language.
\CFA blends the two approaches, providing custom type for idiomatic \CFA code, while extending and building new custom types is still possible, similar to Java concurrency with builtin and library.

Part of the mechanism to generalize custom types is the \CFA trait~\cite[\S~2.3]{Moss18}, \eg the definition for custom-type @coroutine@ is anything satisfying the trait @is_coroutine@, and this trait both enforces and restricts the coroutine-interface functions.
\begin{cfa}
trait is_coroutine( `dtype` T ) {
	void main( T & );
	coroutine_desc * get_coroutine( T & );
};
forall( `dtype` T | is_coroutine(T) ) void $suspend$( T & ), resume( T & );
\end{cfa}
Note, copying generators/coroutines/threads is not meaningful.
For example, both the resumer and suspender descriptors can have bi-directional pointers;
copying these coroutines does not update the internal pointers so behaviour of both copies would be difficult to understand.
Furthermore, two coroutines cannot logically execute on the same stack.
A deep coroutine copy, which copies the stack, is also meaningless in an unmanaged language (no garbage collection), like C, because the stack may contain pointers to object within it that require updating for the copy.
The \CFA @dtype@ property provides no \emph{implicit} copying operations and the @is_coroutine@ trait provides no \emph{explicit} copying operations, so all coroutines must be passed by reference (pointer).
The function definitions ensures there is a statically-typed @main@ function that is the starting point (first stack frame) of a coroutine, and a mechanism to get (read) the coroutine descriptor from its handle.
The @main@ function has no return value or additional parameters because the coroutine type allows an arbitrary number of interface functions 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@ function, and possibly redefining \textsf{suspend} and @resume@.

The \CFA custom-type @coroutine@ implicitly implements the getter and forward declarations for 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 custom types and fundamental @trait@ description of these types allows a concise specification for programmers and tools, while more advanced programmers can have tighter control over memory layout and initialization.

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 type global/communication variables across interface functions.
The coroutine descriptor contains all implicit declarations needed by the runtime, \eg @suspend@/@resume@, and can be part of the coroutine handle or separate.
The coroutine stack can appear in a number of locations and be fixed or variable sized.
Hence, the coroutine's stack could be a VLS\footnote{
We are examining variable-sized structures (VLS), where fields can be variable-sized structures or arrays.
Once allocated, a VLS is fixed sized.}
on the allocating stack, provided the allocating stack is large enough.
For a VLS stack allocation/deallocation is an inexpensive adjustment of the stack pointer, modulo any stack constructor costs (\eg initial frame setup).
For heap stack allocation, allocation/deallocation is an expensive heap allocation (where the heap can be a shared resource), modulo any stack constructor costs.
With 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 fixed-sized heap allocated stacks.
In \CFA debug-mode, the fixed-sized stack is terminated with a write-only page, which catches most stack overflows.
Experience teaching concurrency with \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue for students.
Split-stack allocation is under development but requires recompilation of legacy code, which may be impossible.

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


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

Concurrency is nondeterministic scheduling of independent sequential execution-paths (threads), where each thread has its own stack.
A single thread with multiple call stacks, \newterm{coroutining}~\cite{Conway63,Marlin80}, does \emph{not} imply concurrency~\cite[\S~2]{Buhr05a}.
In coroutining, coroutines self-schedule the thread across stacks so execution is deterministic.
(It is \emph{impossible} to generate a concurrency error when coroutining.)
However, coroutines are a stepping stone towards concurrency.

The transition to concurrency, even for a single thread with multiple stacks, occurs when coroutines context switch to a \newterm{scheduling coroutine}, introducing non-determinism from the coroutine perspective~\cite[\S~3,]{Buhr05a}.
Therefore, a minimal concurrency system requires coroutines \emph{in conjunction with a nondeterministic scheduler}.
The resulting execution system now follows a cooperative threading-model~\cite{Adya02,libdill}, called \newterm{non-preemptive scheduling}.
Adding \newterm{preemption} introduces non-cooperative scheduling, where context switching occurs randomly between any two instructions often based on a timer interrupt, called \newterm{preemptive scheduling}.
While a scheduler introduces uncertain execution among explicit context switches, preemption introduces uncertainty by introducing implicit context switches.
Uncertainty gives the illusion of parallelism on a single processor and provides a mechanism to access and increase performance on multiple processors.
The reason is that the scheduler/runtime have complete knowledge about resources and how to best utilized them.
However, the introduction of unrestricted nondeterminism results in the need for \newterm{mutual exclusion} and \newterm{synchronization}, which restrict nondeterminism for correctness;
otherwise, it is impossible to write meaningful concurrent programs.
Optimal concurrent performance is often obtained by having as much nondeterminism as mutual exclusion and synchronization correctness allow.

A scheduler can either be a stackless or stackful.
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.
The \CFA runtime uses a stackful scheduler for uniformity and security.


\subsection{Thread}
\label{s:threads}

Threading needs the ability to start a thread and wait for its completion.
A common API for this ability is @fork@ and @join@.
\begin{cquote}
\begin{tabular}{@{}lll@{}}
\multicolumn{1}{c}{\textbf{Java}} & \multicolumn{1}{c}{\textbf{\Celeven}} & \multicolumn{1}{c}{\textbf{pthreads}} \\
\begin{cfa}
class MyTask extends Thread {...}
mytask t = new MyTask(...);
`t.start();` // start
// concurrency
`t.join();` // wait
\end{cfa}
&
\begin{cfa}
class MyTask { ... } // functor
MyTask mytask;
`thread t( mytask, ... );` // start
// concurrency
`t.join();` // wait
\end{cfa}
&
\begin{cfa}
void * rtn( void * arg ) {...}
pthread_t t;  int i = 3;
`pthread_create( &t, rtn, (void *)i );` // start
// concurrency
`pthread_join( t, NULL );` // wait
\end{cfa}
\end{tabular}
\end{cquote}
\CFA has a simpler approach using a custom @thread@ type and leveraging declaration semantics (allocation/deallocation), where threads implicitly @fork@ after construction and @join@ before destruction.
\begin{cfa}
thread MyTask {};
void main( MyTask & this ) { ... }
int main() {
	MyTask team`[10]`; $\C[2.5in]{// allocate stack-based threads, implicit start after construction}$
	// concurrency
} $\C{// deallocate stack-based threads, implicit joins before destruction}$
\end{cfa}
This semantic ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
For block allocation to arbitrary depth, including recursion, threads are created/destroyed in a lattice structure (tree with top and bottom).
Arbitrary topologies are possible using dynamic allocation, allowing threads to outlive their declaration scope, identical to normal dynamic allocation.
\begin{cfa}
MyTask * factory( int N ) { ... return `anew( N )`; } $\C{// allocate heap-based threads, implicit start after construction}$
int main() {
	MyTask * team = factory( 10 );
	// concurrency
	`delete( team );` $\C{// deallocate heap-based threads, implicit joins before destruction}\CRT$
}
\end{cfa}

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 ( c; cols ) { 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 ( r; rows; ) { $\C{// start threads to sum rows}$
		adders[r] = `new( matrix[r], cols, &subtotals[r] );`
	}
	for ( r; rows ) { $\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}


\subsection{Thread Implementation}

Threads in \CFA are user level run by runtime kernel threads (see Section~\ref{s:CFARuntimeStructure}), where user threads provide concurrency and kernel threads provide parallelism.
Like coroutines, and for the same design reasons, \CFA provides a custom @thread@ type and a @trait@ to enforce and restrict the task-interface functions.
\begin{cquote}
\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
\begin{cfa}
thread myThread {
	... // declaration/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}
Like coroutines, the @dtype@ property prevents \emph{implicit} copy operations and the @is_thread@ trait provides no \emph{explicit} copy operations, so threads must be passed by reference (pointer).
Similarly, the function definitions ensures there is a statically-typed @main@ function that is the thread starting point (first stack frame), a mechanism to get (read) the thread descriptor from its handle, and a special destructor to prevent deallocation while the thread is executing.
(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitor}.)
The difference between the coroutine and thread is that a coroutine borrows a thread from its caller, so the first thread resuming a coroutine creates the coroutine's stack and starts running the coroutine main on the stack;
whereas, a thread is scheduling for execution in @main@ immediately after its constructor is run.
No return value or additional parameters are necessary for this function because the @thread@ type allows an arbitrary number of interface functions with corresponding arbitrary typed input/output values.


\section{Mutual Exclusion / Synchronization}

Unrestricted nondeterminism is meaningless as there is no way to know when the result is completed without synchronization.
To produce meaningful execution requires clawing back some determinism using mutual exclusion and synchronization, where mutual exclusion provides access control for threads using shared data, and synchronization is a timing relationship among threads~\cite[\S~4]{Buhr05a}.
Some concurrent systems eliminate mutable shared-state by switching to stateless communication like message passing~\cite{Thoth,Harmony,V-Kernel,MPI} (Erlang, MPI), channels~\cite{CSP} (CSP,Go), actors~\cite{Akka} (Akka, Scala), or functional techniques (Haskell).
However, these approaches introduce a new communication mechanism for concurrency different from the standard communication using function call/return.
Hence, a programmer must learn and manipulate two sets of design/programming 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 a \newterm{critical section}~\cite{Dijkstra65}, which is enforced by \newterm{simple mutual-exclusion}.
The generalization is called a \newterm{group critical-section}~\cite{Joung00}, where multiple tasks with the same session use the resource simultaneously and different sessions are segregated, which is enforced by \newterm{complex mutual-exclusion} providing the correct kind and number of threads using a group critical-section.
The readers/writer problem~\cite{Courtois71} is an instance of a group critical-section, where readers share a session but writers have a unique session.

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 receive-specific versus receive-any thread in message passing or offering specialized solutions, \eg barrier lock.
Often synchronization is used to order access to a critical section, \eg ensuring a waiting writer thread enters the critical section before a calling reader thread.
If the calling reader is scheduled before the waiting writer, the reader has \newterm{barged}.
Barging can result in staleness/freshness problems, where a reader barges ahead of a writer and reads temporally stale data, or a writer barges ahead of another writer overwriting data with a fresh value preventing the previous value from ever being read (lost computation).
Preventing or detecting barging is an involved challenge with low-level locks, which is made easier through higher-level constructs.
This challenge is often split into two different approaches: barging avoidance and prevention.
Algorithms that unconditionally releasing a lock for competing threads to acquire use barging avoidance during synchronization to force a barging thread to wait;
algorithms that conditionally hold locks during synchronization, \eg baton-passing~\cite{Andrews89}, prevent barging completely.


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

A \textbf{monitor} is a set of functions that ensure mutual exclusion when accessing shared state.
More precisely, a monitor is a programming technique that implicitly binds mutual exclusion to static function 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).
Restricting acquire/release points eases programming, comprehension, and maintenance, at a slight cost in flexibility and efficiency.
\CFA uses a custom @monitor@ type and leverages declaration semantics (deallocation) to protect active or waiting threads in a monitor.

The following is a \CFA monitor implementation of an atomic counter.
\begin{cfa}[morekeywords=nomutex]
`monitor` Aint { int cnt; }; $\C[4.25in]{// atomic integer counter}$
int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$
int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions with int}\CRT$
int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; }
\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 prefix increment operation, @++?@, is normally @mutex@, indicating mutual exclusion is necessary during function execution, to protect the incrementing from race conditions, unless there is an atomic increment instruction for the implementation type.
The assignment operators provide bi-directional conversion between an atomic and normal integer without accessing field @cnt@;
these operations only need @mutex@, if reading/writing the implementation type is not atomic.
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}
int i = 0, j = 0, k = 5;
Aint x = { 0 }, y = { 0 }, z = { 5 }; $\C{// no mutex required}$
++x; ++y; ++z; $\C{// safe increment by multiple threads}$
x = 2; y = i; z = k; $\C{// conversions}$
i = x; j = y; k = z;
\end{cfa}

\CFA monitors have \newterm{multi-acquire} semantics so the thread in the monitor may acquire it multiple times without deadlock, allowing recursion and calling other interface functions.
\begin{cfa}
monitor M { ... } m;
void foo( M & mutex m ) { ... } $\C{// acquire mutual exclusion}$
void bar( M & mutex m ) { $\C{// acquire mutual exclusion}$
	... `bar( m );` ... `foo( m );` ... $\C{// reacquire mutual exclusion}$
}
\end{cfa}
\CFA monitors also ensure the monitor lock is released regardless of how an acquiring function ends (normal or exceptional), and returning a shared variable is safe via copying before the lock is released.
Similar safety is offered by \emph{explicit} mechanisms like \CC RAII;
monitor \emph{implicit} safety ensures no programmer usage errors.
Furthermore, RAII mechansims cannot handle complex synchronization within a monitor, where the monitor lock may not be released on function exit because it is passed to an unblocking thread;
RAII is purely a mutual-exclusion mechanism (see Section~\ref{s:Scheduling}).


\subsection{Monitor Implementation}

For the same design reasons, \CFA provides a custom @monitor@ type and a @trait@ to enforce and restrict the monitor-interface functions.
\begin{cquote}
\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
\begin{cfa}
monitor M {
	... // shared data
};

\end{cfa}
&
\begin{cfa}
trait is_monitor( `dtype` T ) {
	monitor_desc * get_monitor( T & );
	void ^?{}( T & mutex );
};
\end{cfa}
\end{tabular}
\end{cquote}
The @dtype@ property prevents \emph{implicit} copy operations and the @is_monitor@ trait provides no \emph{explicit} copy operations, so monitors must be passed by reference (pointer).
% 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.
Similarly, the function definitions ensures there is a mechanism to get (read) the monitor descriptor from its handle, and a special destructor to prevent deallocation if a thread using the shared data.
The custom monitor type also inserts any locks needed to implement the mutual exclusion semantics.


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

While the monitor lock provides mutual exclusion for shared data, there are implementation options for when and where the locking/unlocking occurs.
(Much of this discussion also applies to basic locks.)
For example, a monitor may be passed through multiple helper functions before it is necessary to acquire the monitor's mutual exclusion.

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, types can coincidentally match the monitor trait but not be a monitor, similar to inheritance where a shape and playing card can both be drawable.
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@.
The following has monitor parameter types that are composed of multiple objects.
\begin{cfa}
monitor M { ... }
int f1( M & mutex m ); $\C{// single parameter object}$
int f2( M * mutex m ); $\C{// single or multiple parameter object}$
int f3( M * mutex m[$\,$] ); $\C{// multiple parameter object}$
int f4( stack( M * ) & mutex m ); $\C{// multiple parameters object}$
\end{cfa}
Function @f1@ has a single parameter object, while @f2@'s indirection could be a single or multi-element array, where static array size is often unknown in C.
Function @f3@ has a multiple object matrix, and @f4@ a multiple object data structure.
While shown shortly, multiple object acquisition is possible, but the number of objects must be statically known.
Therefore, \CFA only acquires one monitor per parameter with at most one level of indirection, excluding pointers as it is impossible to statically determine the size.

For object-oriented monitors, \eg Java, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
\CFA has no receiver, and hence, the explicit @mutex@ qualifier is used to specify which objects acquire mutual exclusion.
A positive consequence of this design decision is the ability to support multi-monitor functions,\footnote{
While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.}
called \newterm{bulk acquire}.
\CFA guarantees acquisition order is consistent across calls to @mutex@ functions using the same monitors as arguments, so acquiring multiple monitors is safe from deadlock.
Figure~\ref{f:BankTransfer} shows a trivial solution to the bank transfer problem~\cite{BankTransfer}, where two resources must be locked simultaneously, using \CFA monitors with implicit locking and \CC with explicit locking.
A \CFA programmer only has to manage when to acquire mutual exclusion;
a \CC programmer must select the correct lock and acquisition mechanism from a panoply of locking options.
Making good choices for common cases in \CFA simplifies the programming experience and enhances safety.

\begin{figure}
\centering
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
monitor BankAccount {

	int balance;
} b1 = { 0 }, b2 = { 0 };
void deposit( BankAccount & `mutex` b,
			int deposit ) with(b) {
	balance += deposit;
}
void transfer( BankAccount & `mutex` my,
	BankAccount & `mutex` your, int me2you ) {

	deposit( my, -me2you ); // debit
	deposit( your, me2you ); // credit
}
`thread` Person { BankAccount & b1, & b2; };
void main( Person & person ) with(person) {
	for ( 10_000_000 ) {
		if ( random() % 3 ) deposit( b1, 3 );
		if ( random() % 3 ) transfer( b1, b2, 7 );
	}
}    
int main() {
	`Person p1 = { b1, b2 }, p2 = { b2, b1 };`

} // wait for threads to complete
\end{cfa}
\end{lrbox}

\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
struct BankAccount {
	`recursive_mutex m;`
	int balance = 0;
} b1, b2;
void deposit( BankAccount & b, int deposit ) {
	`scoped_lock lock( b.m );`
	b.balance += deposit;
}
void transfer( BankAccount & my,
			BankAccount & your, int me2you ) {
	`scoped_lock lock( my.m, your.m );`
	deposit( my, -me2you ); // debit
	deposit( your, me2you ); // credit
}

void person( BankAccount & b1, BankAccount & b2 ) {
	for ( int i = 0; i < 10$'$000$'$000; i += 1 ) {
		if ( random() % 3 ) deposit( b1, 3 );
		if ( random() % 3 ) transfer( b1, b2, 7 );
	}
}    
int main() {
	`thread p1(person, ref(b1), ref(b2)), p2(person, ref(b2), ref(b1));`
	`p1.join(); p2.join();`
}
\end{cfa}
\end{lrbox}

\subfloat[\CFA]{\label{f:CFABank}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[\CC]{\label{f:C++Bank}\usebox\myboxB}
\hspace{3pt}
\caption{Bank transfer problem}
\label{f:BankTransfer}
\end{figure}

Users can still force the acquiring order by using @mutex@/\lstinline[morekeywords=nomutex]@nomutex@.
\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 bulk-acquire semantics allow @bar@ or @baz@ to acquire a monitor lock and reacquire it in @foo@.
The calls to @bar@ and @baz@ acquired the monitors in opposite order, possibly resulting in deadlock.
However, this case is the simplest instance of the \emph{nested-monitor problem}~\cite{Lister77}, where monitors are acquired in sequence versus bulk.
Detecting the nested-monitor problem requires dynamic tracking of monitor calls, and dealing with it requires rollback semantics~\cite{Dice10}.
\CFA does not deal with this fundamental problem.

Finally, like Java, \CFA offers an alternative @mutex@ statement to reduce refactoring and naming.
\begin{cquote}
\renewcommand{\arraystretch}{0.0}
\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
\multicolumn{1}{c}{\textbf{\lstinline@mutex@ call}} & \multicolumn{1}{c}{\lstinline@mutex@ \textbf{statement}} \\
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
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}[aboveskip=0pt,belowskip=0pt]

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

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


\subsection{Scheduling}
\label{s:Scheduling}

% There are many aspects of scheduling in a concurrency system, all related to resource utilization by waiting threads, \ie which thread gets the resource next.
% Different forms of scheduling include access to processors by threads (see Section~\ref{s:RuntimeStructureCluster}), another is access to a shared resource by a lock or monitor.
This section discusses monitor scheduling for waiting threads eligible for entry, \ie which thread gets the shared resource next. (See Section~\ref{s:RuntimeStructureCluster} for scheduling threads on virtual processors.)
While monitor mutual-exclusion provides safe access to shared data, the monitor data may indicate that a thread accessing it cannot proceed, \eg a bounded buffer 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.
\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.
Finally, \CFA monitors do not allow calling threads to barge ahead of signalled threads, which simplifies synchronization among threads in the monitor and increases correctness.
If barging is allowed, synchronization between a signaller and signallee is difficult, often requiring additional flags and multiple unblock/block cycles.
In fact, signals-as-hints is completely opposite from that proposed by Hoare in the seminal paper on monitors~\cite[p.~550]{Hoare74}.
% \begin{cquote}
% 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{cquote}
Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implicit form of self barging.
Hence, a \CFA @wait@ statement is not enclosed in a @while@ loop retesting a blocking predicate, which can cause thread starvation due to barging.

Figure~\ref{f:MonitorScheduling} shows general internal/external scheduling (for the bounded-buffer example in Figure~\ref{f:InternalExternalScheduling}).
External calling threads block on the calling queue, if the monitor is occupied, otherwise they enter in FIFO order.
Internal threads block on condition queues via @wait@ and reenter from the condition in FIFO order.
Alternatively, internal threads block on urgent from the @signal_block@ or @waitfor@, and reenter implicitly when the monitor becomes empty, \ie, the thread in the monitor exits or waits.

There are three signalling mechanisms to unblock waiting threads to enter the monitor.
Note, signalling cannot have the signaller and signalled thread in the monitor simultaneously because of the mutual exclusion, so either the signaller or signallee can proceed.
For internal scheduling, threads are unblocked from condition queues using @signal@, where the signallee is moved to urgent and the signaller continues (solid line).
Multiple signals move multiple signallees to urgent, until the condition is empty.
When the signaller exits or waits, a thread blocked on urgent is processed before calling threads to prevent barging.
(Java conceptually moves the signalled thread to the calling queue, and hence, allows barging.)
The alternative unblock is in the opposite order using @signal_block@, where the signaller is moved to urgent and the signallee continues (dashed line), and is implicitly unblocked from urgent when the signallee exits or waits.

For external scheduling, the condition queues are not used;
instead threads are unblocked directly from the calling queue using @waitfor@ based on function names requesting mutual exclusion.
(The linear search through the calling queue to locate a particular call can be reduced to $O(1)$.)
The @waitfor@ has the same semantics as @signal_block@, where the signalled thread executes before the signallee, which waits on urgent.
Executing multiple @waitfor@s from different signalled functions causes the calling threads to move to urgent.
External scheduling requires urgent to be a stack, because the signaller excepts to execute immediately after the specified monitor call has exited or waited.
Internal scheduling behaves the same for an urgent stack or queue, except for multiple signalling, where the threads unblock from urgent in reverse order from signalling.
If the restart order is important, multiple signalling by a signal thread can be transformed into daisy-chain signalling among threads, where each thread signals the next thread.
We tried both a stack for @waitfor@ and queue for signalling, but that resulted in complex semantics about which thread enters next.
Hence, \CFA uses a single urgent stack to correctly handle @waitfor@ and adequately support both forms of signalling.

\begin{figure}
\centering
% \subfloat[Scheduling Statements] {
% \label{fig:SchedulingStatements}
% {\resizebox{0.45\textwidth}{!}{\input{CondSigWait.pstex_t}}}
\input{CondSigWait.pstex_t}
% }% subfloat
% \quad
% \subfloat[Bulk acquire monitor] {
% \label{fig:BulkMonitor}
% {\resizebox{0.45\textwidth}{!}{\input{ext_monitor.pstex_t}}}
% }% subfloat
\caption{Monitor Scheduling}
\label{f:MonitorScheduling}
\end{figure}

Figure~\ref{f:BBInt} shows a \CFA generic bounded-buffer with internal scheduling, where producers/consumers enter the monitor, detect the buffer is full/empty, and block on an appropriate condition variable, @full@/@empty@.
The @wait@ function atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the function's parameter list.
The appropriate condition variable 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 variable does nothing.
It is common to declare condition variables as monitor fields to prevent shared access, hence no locking is required for access as the conditions are protected by the monitor lock.
In \CFA, a condition variable can be created/stored independently.
% To still prevent expensive locking on access, a condition variable is tied to a \emph{group} of monitors on first use, called \newterm{branding}, resulting in a low-cost boolean test to detect sharing from other monitors.

% 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 urgent 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.

\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}

\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
monitor ReadersWriter {
	int rcnt, wcnt; // readers/writer using resource
};
void ?{}( ReadersWriter & rw ) with(rw) {
	rcnt = wcnt = 0;
}
void EndRead( ReadersWriter & mutex rw ) with(rw) {
	rcnt -= 1;
}
void EndWrite( ReadersWriter & mutex rw ) with(rw) {
	wcnt = 0;
}
void StartRead( ReadersWriter & mutex rw ) with(rw) {
	if ( wcnt > 0 ) `waitfor( EndWrite, rw );`
	rcnt += 1;
}
void StartWrite( ReadersWriter & mutex rw ) with(rw) {
	if ( wcnt > 0 ) `waitfor( EndWrite, rw );`
	else while ( rcnt > 0 ) `waitfor( EndRead, rw );`
	wcnt = 1;
}

\end{cfa}
\end{lrbox}

\subfloat[Generic bounded buffer, internal scheduling]{\label{f:BBInt}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[Readers / writer lock, external scheduling]{\label{f:RWExt}\usebox\myboxB}

\caption{Internal / external scheduling}
\label{f:InternalExternalScheduling}
\end{figure}

Figure~\ref{f:BBInt} can be transformed into external scheduling by removing the condition variables and signals/waits, and adding the following lines at the locations of the current @wait@s in @insert@/@remove@, respectively.
\begin{cfa}[aboveskip=2pt,belowskip=1pt]
if ( count == 10 ) `waitfor( remove, buffer )`;       |      if ( count == 0 ) `waitfor( insert, buffer )`;
\end{cfa}
Here, the producers/consumers detects a full/\-empty buffer and prevents 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 function 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 calling excluded functions block outside of (external to) the monitor on the calling queue, versus blocking on condition queues inside of (internal to) the monitor.
Figure~\ref{f:RWExt} shows a readers/writer lock written using external scheduling, where a waiting reader detects a writer using the resource and restricts further calls until the writer exits by calling @EndWrite@.
The writer does a similar action for each reader or writer using the resource.
Note, no new calls to @StarRead@/@StartWrite@ may occur when waiting for the call to @EndRead@/@EndWrite@.
External scheduling allows waiting for events from other threads while restricting unrelated events, that would otherwise have to wait on conditions in the monitor.
The mechnaism can be done in terms of control flow, \eg Ada @accept@ or \uC @_Accept@, or in terms of data, \eg Go @select@ on channels.
While both mechanisms have strengths and weaknesses, this project uses the control-flow mechanism to be consistent with other language features.
% Two challenges specific to \CFA for external scheduling are loose object-definitions (see Section~\ref{s:LooseObjectDefinitions}) and multiple-monitor functions (see Section~\ref{s:Multi-MonitorScheduling}).

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.
Furthermore, barging corrupts the dating service during an exchange because a barger may also match and change the phone numbers, invalidating the previous exchange phone number.
Putting loops around the @wait@s does not correct the problem;
the simple solution must be restructured to account for barging.

\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 );`
	}
	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}

In summation, 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 signal 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.

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 parameters, \ie @wait( e, m1, m2 )@.
To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
Wait cannot statically verifies the released monitors are the acquired mutex-parameters without disallowing separately compiled helper functions calling @wait@.
While \CC supports bulk locking, @wait@ only accepts a single lock for a condition variable, so bulk locking with condition variables is asymmetric.
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 a condition queue to allow the locks to be passed, and hence, prevent barging.

Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex parameters, \ie @waitfor( rtn, m1, m2 )@.
To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn, m1 )@.
@waitfor@ does statically verify the monitor types passed are the same as the acquired mutex-parameters of the given function or function pointer, hence the function (pointer) prototype must be accessible.
% When an overloaded function appears in an @waitfor@ statement, calls to any function 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 functions 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 @m1@ and @m2@ to enter @bar@ and @signal@ the condition.
While deadlock can occur with multiple/nesting acquisition, this is a consequence of locks, and by extension monitors, not being perfectly composable.



\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 functions, with an optional statement to be performed \emph{after} the mutex function 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 function, but the function must not block or context switch.
If there are multiple acceptable mutex calls, selection occurs top-to-bottom (prioritized) among the @waitfor@ clauses, whereas some programming languages with similar mechanisms accept nondeterministically 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 blocked until a call to one of these members is made.
If there is a @timeout@ clause, it provides an upper bound on waiting.
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 both @timeout@ and @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered.

\begin{figure}
\centering
\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{// any number of functions}$
	waitfor( $\emph{mutex-member-name}$ ) $\emph{statement}$
`or`	...
`when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
	`timeout` $\emph{statement}$ $\C{// optional terminating timeout clause}$
`when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
	`else`  $\emph{statement}$ $\C{// optional terminating clause}$
\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 only accepts @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, \eg assume the bounded buffer is restructred from a monitor to a thread with the following @main@.
\begin{cfa}
void main( Buffer(T) & buffer ) with(buffer) {
	for () {
		`waitfor( ^?{}, buffer )` break;
		or when ( count != 20 ) waitfor( insert, buffer ) { ... }
		or when ( count != 0 ) waitfor( remove, buffer ) { ... }
	}
	// clean up
}
\end{cfa}
When the program main deallocates the buffer, it first calls the buffer's destructor, which is accepted, the destructor runs, and the buffer is deallocated.
However, the buffer thread cannot continue after the destructor call because the object is gone;
hence, clean up in @main@ cannot occur, which means destructors for local objects are not run.
To make this useful capability work, the semantics for accepting the destructor is the same as @signal@, \ie the destructor call is placed on urgent and the acceptor continues execution, which ends the loop, cleans up, and the thread terminates.
Then, the destructor caller unblocks from urgent to deallocate the object.
Accepting the destructor is the idiomatic way in \CFA to terminate a thread performing direct communication.


\subsection{Bulk Barging Prevention}

Figure~\ref{f:BulkBargingPrevention} 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 threads W1 and W2 need some subset of monitors @m1@ and @m2@.
\begin{cquote}
condition c: (order 1) W2(@m2@), W1(@m1@,@m2@)\ \ \ or\ \ \ (order 2) W1(@m1@,@m2@), W2(@m2@) \\
S: acq. @m1@ $\rightarrow$ acq. @m1,m2@ $\rightarrow$ @signal(c)@ $\rightarrow$ rel. @m2@ $\rightarrow$ pass @m2@ unblock W2 (order 2) $\rightarrow$ rel. @m1@ $\rightarrow$ pass @m1,m2@ unblock W1 \\
\hspace*{2.75in}$\rightarrow$ rel. @m1@ $\rightarrow$ pass @m1,m2@ unblock W1 (order 1)
\end{cquote}

\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 still 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 )`; // release m1, m2
		// m1, m2 reacquired
	} // $\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 )`; // release m2
	// m2 reacquired
} // $\LstCommentStyle{\color{red}release m2}$




\end{cfa}
\end{lrbox}

\begin{cquote}
\subfloat[Signalling Thread (S)]{\label{f:SignallingThread}\usebox\myboxA}
\hspace{3\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{Bulk Barging Prevention}
\label{f:BulkBargingPrevention}
\end{figure}

One scheduling solution is for the signaller S 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, this solution is inefficient if W2 waited first and can be immediate passed @m2@ when released, while S retains @m1@ until completion of the outer mutex statement.
If W1 waited first, the signaller must retain @m1@ amd @m2@ until completion of the outer mutex statement and then pass both to W1.
% Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
To support this efficient semantics (and prevent barging), the implementation maintains a list of monitors acquired for each blocked thread.
When a signaller exits or waits in a monitor function/statement, the front waiter on urgent is unblocked if all its monitors are released.
Implementing a fast subset check for the necessary released monitors is important.
% 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.
A new class can add members via static inheritance but the subclass still has an exhaustive list of operations.
(Dynamic member adding, \eg JavaScript~\cite{JavaScript}, is not considered.)
In the object-oriented scenario, the type and all its operators are always present at compilation (even separate compilation), so it is possible to number the operations in a bit mask and use an $O(1)$ compare with a similar bit mask created for the operations specified in a @waitfor@.

However, in \CFA, monitor functions can be statically added/removed in translation units, making a fast subset check difficult.
\begin{cfa}
	monitor M { ... }; // common type, included in .h file
translation unit 1
	void `f`( M & mutex m );
	void g( M & mutex m ) { waitfor( `f`, m ); }
translation unit 2
	void `f`( M & mutex m ); $\C{// replacing f and g for type M in this translation unit}$
	void `g`( M & mutex m );
	void h( M & mutex m ) { waitfor( `f`, m ) or waitfor( `g`, m ); } $\C{// extending type M in this translation unit}$
\end{cfa}
The @waitfor@ statements in each translation unit cannot form a unique bit-mask because the monitor type does not carry that information.
Hence, function pointers are used to identify the functions listed in the @waitfor@ statement, stored in a variable-sized array.
Then, the same implementation approach used for the urgent stack is used for the calling queue.
Each caller has a list of monitors acquired, and the @waitfor@ statement performs a (usually short) linear search matching functions in the @waitfor@ list with called functions, and then verifying the associated mutex locks can be transfers.
(A possible way to construct a dense mapping is at link or load-time.)


\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 need to be established.
\begin{cfa}
monitor M { ... };
void f( M & mutex m1 );
void g( M & mutex m1, M & mutex m2 ) { `waitfor( f );` } $\C{// pass m1 or m2 to f?}$
\end{cfa}
The solution is for the programmer to disambiguate:
\begin{cfa}
waitfor( f, `m2` ); $\C{// wait for call to f with argument m2}$
\end{cfa}
Both locks are acquired by function @g@, so when function @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{// 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 function.
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}
\centering
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
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}
\end{lrbox}

\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
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{lrbox}
\subfloat[Internal scheduling]{\label{f:InternalScheduling}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[External scheduling]{\label{f:ExternalScheduling}\usebox\myboxB}
\caption{Unmatched \protect\lstinline@mutex@ sets}
\label{f:UnmatchedMutexSets}
\end{figure}


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

Threads in \CFA can also be monitors to allow \emph{direct communication} among threads, \ie threads can have mutex functions that are called by other threads.
Hence, all monitor features are available when using threads.
Figure~\ref{f:DirectCommunication} shows a comparison of direct call communication in \CFA with direct channel communication in Go.
(Ada provides a similar mechanism to the \CFA direct communication.)
The program main in both programs communicates directly with the other thread versus indirect communication where two threads interact through a passive monitor.
Both direct and indirection thread communication are valuable tools in structuring concurrent programs.

\begin{figure}
\centering
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]

struct Msg { int i, j; };
thread GoRtn { int i;  float f;  Msg m; };
void mem1( GoRtn & mutex gortn, int i ) { gortn.i = i; }
void mem2( GoRtn & mutex gortn, float f ) { gortn.f = f; }
void mem3( GoRtn & mutex gortn, Msg m ) { gortn.m = m; }
void ^?{}( GoRtn & mutex ) {}

void main( GoRtn & gortn ) with( gortn ) {  // thread starts

	for () {

		`waitfor( mem1, gortn )` sout | i;  // wait for calls
		or `waitfor( mem2, gortn )` sout | f;
		or `waitfor( mem3, gortn )` sout | m.i | m.j;
		or `waitfor( ^?{}, gortn )` break;

	}

}
int main() {
	GoRtn gortn; $\C[2.0in]{// start thread}$
	`mem1( gortn, 0 );` $\C{// different calls}\CRT$
	`mem2( gortn, 2.5 );`
	`mem3( gortn, (Msg){1, 2} );`


} // wait for completion
\end{cfa}
\end{lrbox}

\begin{lrbox}{\myboxB}
\begin{Go}[aboveskip=0pt,belowskip=0pt]
func main() {
	type Msg struct{ i, j int }

	ch1 := make( chan int )
	ch2 := make( chan float32 )
	ch3 := make( chan Msg )
	hand := make( chan string )
	shake := make( chan string )
	gortn := func() { $\C[1.5in]{// thread starts}$
		var i int;  var f float32;  var m Msg
		L: for {
			select { $\C{// wait for messages}$
			  case `i = <- ch1`: fmt.Println( i )
			  case `f = <- ch2`: fmt.Println( f )
			  case `m = <- ch3`: fmt.Println( m )
			  case `<- hand`: break L $\C{// sentinel}$
			}
		}
		`shake <- "SHAKE"` $\C{// completion}$
	}

	go gortn() $\C{// start thread}$
	`ch1 <- 0` $\C{// different messages}$
	`ch2 <- 2.5`
	`ch3 <- Msg{1, 2}`
	`hand <- "HAND"` $\C{// sentinel value}$
	`<- shake` $\C{// wait for completion}\CRT$
}
\end{Go}
\end{lrbox}

\subfloat[\CFA]{\label{f:CFAwaitfor}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[Go]{\label{f:Gochannel}\usebox\myboxB}
\caption{Direct communication}
\label{f:DirectCommunication}
\end{figure}

\begin{comment}
The following shows an example of two threads directly calling each other and accepting calls from each other in a cycle.
\begin{cfa}
\end{cfa}
\vspace{-0.8\baselineskip}
\begin{cquote}
\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
\begin{cfa}
thread Ping {} pi;
void ping( Ping & mutex ) {}
void main( Ping & pi ) {
	for ( 10 ) {
		`waitfor( ping, pi );`
		`pong( po );`
	}
}
int main() {}
\end{cfa}
&
\begin{cfa}
thread Pong {} po;
void pong( Pong & mutex ) {}
void main( Pong & po ) {
	for ( 10 ) {
		`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.
\end{comment}


\subsection{Execution Properties}

Table~\ref{t:ObjectPropertyComposition} shows how the \CFA high-level constructs cover 3 fundamental execution properties: thread, stateful function, and mutual exclusion.
Case 1 is a basic object, with none of the new execution properties.
Case 2 allows @mutex@ calls to Case 1 to protect shared data.
Case 3 allows stateful functions to suspend/resume but restricts operations because the state is stackless.
Case 4 allows @mutex@ calls to Case 3 to protect shared data.
Cases 5 and 6 are the same as 3 and 4 without restriction because the state is stackful.
Cases 7 and 8 are rejected because a thread cannot execute without a stackful state in a preemptive environment when context switching from the signal handler.
Cases 9 and 10 have a stackful thread without and with @mutex@ calls.
For situations where threads do not require direct communication, case 9 provides faster creation/destruction by eliminating @mutex@ setup.

\begin{table}
\caption{Object property composition}
\centering
\label{t:ObjectPropertyComposition}
\renewcommand{\arraystretch}{1.25}
%\setlength{\tabcolsep}{5pt}
\begin{tabular}{c|c|l|l}
\multicolumn{2}{c|}{object properties} & \multicolumn{2}{c}{mutual exclusion} \\
\hline
thread	& stateful				& \multicolumn{1}{c|}{No} & \multicolumn{1}{c}{Yes} \\
\hline
\hline
No		& No					& \textbf{1}\ \ \ aggregate type		& \textbf{2}\ \ \ @monitor@ aggregate type \\
\hline
No		& Yes (stackless)		& \textbf{3}\ \ \ @generator@			& \textbf{4}\ \ \ @monitor@ @generator@ \\
\hline
No		& Yes (stackful)		& \textbf{5}\ \ \ @coroutine@			& \textbf{6}\ \ \ @monitor@ @coroutine@ \\
\hline
Yes		& No / Yes (stackless)	& \textbf{7}\ \ \ {\color{red}rejected}	& \textbf{8}\ \ \ {\color{red}rejected} \\
\hline
Yes		& Yes (stackful)		& \textbf{9}\ \ \ @thread@				& \textbf{10}\ \ @monitor@ @thread@ \\
\end{tabular}
\end{table}


\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.
Some of these low-level mechanism are used in the \CFA runtime, but we strongly advocate using high-level mechanisms whenever possible.


% \section{Parallelism}
% \label{s: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}.
% Therefore, 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}
% 
% 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, gives 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 increases the potential for concurrency errors: race, livelock, starvation, and deadlock.
% \CFA adopts user-threads to provide more flexibility and a low-cost mechanism to build any other concurrency approach, \eg thread pools and actors~\cite{Actors}.
% 
% A variant of user thread is \newterm{fibres}, 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 fairness and to reduce tail-latency.
% For concurrency that relies on spinning, if all cores spin the system is livelocked, whereas preemption breaks the livelock.


\begin{comment}
\subsection{Thread Pools}

In contrast to direct threading is indirect \newterm{thread pools}, \eg Java @executor@, 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.

\begin{figure}
\centering
\begin{tabular}{@{}l|l@{}}
\begin{cfa}
struct Adder {
    int * row, cols;
};
int operator()() {
	subtotal = 0;
	for ( int c = 0; c < cols; c += 1 )
		subtotal += row[c];
	return subtotal;
}
void ?{}( Adder * adder, int row[$\,$], int cols, int & subtotal ) {
	adder.[rows, cols, subtotal] = [rows, cols, subtotal];
}




\end{cfa}
&
\begin{cfa}
int main() {
	const int rows = 10, cols = 10;
	int matrix[rows][cols], subtotals[rows], total = 0;
	// read matrix
	Executor executor( 4 );	// kernel threads
	Adder * adders[rows];
	for ( r; rows ) { // send off work for executor
		adders[r] = new( matrix[r], cols, &subtotal[r] );
		executor.send( *adders[r] );
	}
	for ( r; rows ) {	// wait for results
		delete( adders[r] );
		total += subtotals[r];
	}
	sout | total;
}
\end{cfa}
\end{tabular}
\caption{Executor}
\end{figure}
\end{comment}


\section{\protect\CFA Runtime Structure}
\label{s:CFARuntimeStructure}

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 (user) threads from its own ready queue (like an OS executing kernel threads).
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 design allows changing the scheduler, \eg multi-queue multi-server with work-stealing/sharing across the virtual processors.
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 scheduling requirements (real-time), NUMA architecture, heterogeneous hardware, or issues with the underlying operating system, multiple clusters are sometimes necessary.


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

A virtual processor is implemented by a kernel thread (\eg UNIX process), which are 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 because it requires future knowledge, \ie what will the applicaton workload do next.
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 fibres.


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

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 function 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 function.
Experimental results (not presented) for a stackless or stackful scheduler (1 versus 2 context switches) (see Section~\ref{s:Concurrency}) show the performance 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.
\end{comment}


\subsection{Preemption}

Nondeterministic preemption provides fairness from long running threads, and forces concurrent programmers to write more robust programs, rather than relying on code between cooperative scheduling to be atomic.
This atomic reliance can fail on multi-core machines, because execution across cores is nondeterministic.
A different reason for not supporting preemption is that it significantly complicates the runtime system, \eg Microsoft runtime does not support interrupts and on Linux systems, interrupts are complex (see below).
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.
Because preemption frequency is usually long (1 millisecond) performance cost is negligible.

Linux switched a decade ago from specific to arbitrary process signal-delivery for applications with multiple kernel threads.
\begin{cquote}
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{cquote}
Hence, the timer-expiry signal, which is generated \emph{externally} by the Linux kernel to an application, is delivered to any of its Linux subprocesses (kernel threads).
To ensure each virtual processor receives a preemption signal, 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.


\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 significantly decrease space and increase performance.


\section{Performance}
\label{results}

To verify the implementation of the \CFA runtime, a series of microbenchmarks are performed comparing \CFA with pthreads, Java OpenJDK-9, Go 1.12.6 and \uC 7.0.0.
For comparison, the package must be multi-processor (M:N), which excludes libdill/libmil~\cite{libdill} (M:1)), and use a shared-memory programming model, \eg not message passing.
The benchmark computer is an AMD Opteron\texttrademark\ 6380 NUMA 64-core, 8 socket, 2.5 GHz processor, running Ubuntu 16.04.6 LTS, and \CFA/\uC are compiled with gcc 6.5.

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.
Each benchmark experiment is run 31 times.
All omitted tests for other languages are functionally identical to the \CFA tests and available online~\cite{CforallBenchMarks}.


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

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

\columnbreak

\vspace*{-16pt}
\captionof{table}{Object creation comparison (nanoseconds)}
\label{tab:creation}

\begin{tabular}[t]{@{}r*{3}{D{.}{.}{5.2}}@{}}
\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
\CFA Coroutine Lazy		& 14.3		& 14.3		& 0.32		\\
\CFA Coroutine Eager	& 2203.7	& 2205.6	& 26.03		\\
\CFA Thread				& 1257.8	& 1291.2	& 86.19		\\
\uC Coroutine			& 92.2		& 91.4		& 1.58		\\
\uC Thread				& 499.5		& 500.1		& 5.67		\\
Goroutine				& 4397.0	& 4362.8	& 390.77	\\
Java Thread				& 107405.0	& 107794.8	& 1601.33	\\
% Qthreads				& 159.9		& 159.6		& 0.73		\\
Pthreads				& 32920.9	& 32882.7	& 213.55
\end{tabular}
\end{multicols}


\paragraph{Internal Scheduling}

Internal scheduling is measured using a cycle of two threads signalling and waiting.
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{multicols}{2}
\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
\begin{cfa}
volatile int go = 0;
@monitor@ M { @condition c;@ } m;
void __attribute__((noinline))
do_call( M & @mutex@ a1 ) { @signal( c );@ }
thread T {};
void main( T & this ) {
	while ( go == 0 ) { yield(); }
	while ( go == 1 ) { do_call( m ); }
}
int  __attribute__((noinline))
do_wait( M & mutex m ) with(m) {
	go = 1;	// continue other thread
	BENCH( for ( N ) { @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}

\columnbreak

\vspace*{-16pt}
\captionof{table}{Internal-scheduling comparison (nanoseconds)}
\label{tab:int-sched}
\bigskip

\begin{tabular}{@{}r*{3}{D{.}{.}{5.2}}@{}}
\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
\CFA @signal@, 1 @monitor@	& 367.0		& 371.5		& 17.34		\\
\CFA @signal@, 2 @monitor@	& 477.2		& 478.6		& 8.31		\\
\CFA @signal@, 4 @monitor@	& 725.8		& 734.0		& 17.98		\\
\uC @signal@				& 322.8		& 323.0 	& 3.64		\\
Java @notify@				& 16520.0	& 20096.7	& 9378.53	\\
Pthreads Cond. Variable		& 4931.3	& 5057.0 	& 326.80
\end{tabular}
\end{multicols}


\paragraph{External Scheduling}

External scheduling is measured using a cycle of two threads calling and accepting the call using the @waitfor@ statement.
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{multicols}{2}
\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
\vspace*{-16pt}
\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(); }
	while ( go == 1 ) { do_call( m ); }
}
int __attribute__((noinline))
do_wait( M & @mutex@ m ) {
	go = 1;	// continue other thread
	BENCH( for ( N ) { @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}

\columnbreak

\vspace*{-16pt}
\captionof{table}{External-scheduling comparison (nanoseconds)}
\label{tab:ext-sched}
\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
\CFA @waitfor@, 1 @monitor@	& 366.7		& 369.5	& 7.52	\\
\CFA @waitfor@, 2 @monitor@	& 453.6		& 455.8	& 12.38	\\
\CFA @waitfor@, 4 @monitor@	& 671.6		& 672.4	& 14.16	\\
\uC @_Accept@				& 336.0		& 335.8		& 3.22
\end{tabular}
\end{multicols}


\paragraph{Context-Switching}

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

\begin{multicols}{2}
\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
@coroutine@ C {} c;
void main( C & ) { for ( ;; ) { @suspend;@ } }
int main() { // coroutine test
	BENCH( for ( N ) { @resume( c );@ } )
	sout | result`ns;
}
int main() { // task test
	BENCH( for ( N ) { @yield();@ } )
	sout | result`ns;
}
\end{cfa}
\captionof{figure}{\CFA context-switch benchmark}
\label{f:ctx-switch}

\columnbreak

\vspace*{-16pt}
\captionof{table}{Context switch comparison (nanoseconds)}
\label{tab:ctx-switch}
\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
C function		& 1.8		& 1.8	& 0		\\
\CFA generator	& 2.7		& 2.4	& 0.27	\\
\CFA Coroutine	& 37.8		& 37.7	& 0.22	\\
\CFA Thread		& 93.6		& 93.8	& 1.46	\\
\uC Coroutine	& 52.7		& 52.8	& 0.28	\\
\uC Thread		& 93.4		& 93.7	& 1.04	\\
Goroutine		& 140.0		& 139.7	& 2.93	\\
Java Thread		& 374.0		& 375.8	& 10.38	\\
% Qthreads Thread	& 159.5		& 159.3	& 0.71	\\
Pthreads Thread	& 334.4		& 335.0	& 1.95	\\
\end{tabular}
\end{multicols}


\paragraph{Mutual-Exclusion}

Uncontented mutual exclusion, which occurs frequently, is measured by entering/leaving a critical section.
For monitors, entering and leaving a monitor function is measured.
To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a @pthread_mutex@ lock is also measured.
Figure~\ref{f:mutex} shows the code for \CFA with all results in Table~\ref{tab:mutex}.
Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.

\begin{multicols}{2}
\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( N ) do_call( m1/*, m2, m3, m4*/ );
	)
	sout | result`ns;
}
\end{cfa}
\captionof{figure}{\CFA acquire/release mutex benchmark}
\label{f:mutex}

\columnbreak

\vspace*{-16pt}
\captionof{table}{Mutex comparison (nanoseconds)}
\label{tab:mutex}
\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
test and test-and-test lock		& 19.1	& 19.0	& 0.36	\\
\CFA @mutex@ function, 1 arg.	& 46.6	& 46.8	& 0.86	\\
\CFA @mutex@ function, 2 arg.	& 84.1	& 85.3	& 1.86	\\
\CFA @mutex@ function, 4 arg.	& 158.6	& 160.7	& 3.07	\\
\uC @monitor@ member rtn.		& 54.0	& 53.7	& 0.83	\\
Java synchronized method		& 27.0	& 27.1	& 0.25	\\
Pthreads Mutex Lock				& 33.6	& 32.7	& 1.12
\end{tabular}
\end{multicols}


\section{Conclusion}

Advanced control-flow will always be difficult, especially when there is temporal ordering and nondeterminism.
However, many systems exacerbate the difficulty through their presentation mechanisms.
This paper shows it is possible to present a hierarchy of control-flow features, generator, coroutine, thread, and monitor, providing an integrated set of high-level, efficient, and maintainable control-flow features.
Eliminated from \CFA are spurious wakeup and barging, which are nonintuitive and lead to errors, and having to work with a bewildering set of low-level locks and acquisition techniques.
\CFA high-level race-free monitors and tasks provide the core mechanisms for mutual exclusion and synchronization, without having to resort to magic qualifiers like @volatile@/@atomic@.
Extending these mechanisms to handle high-level deadlock-free bulk acquire across both mutual exclusion and synchronization is a unique contribution.
The \CFA runtime 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.
These concepts and the \CFA runtime-system are written in the \CFA language, extensively leveraging the \CFA type-system, which demonstrates 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 complex control-flow in applications, with the ability to obtain maximum available performance by selecting mechanisms at the appropriate level of need.


\section{Future Work}

While control flow in \CFA has a strong start, development is still underway to complete a number of 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 tuning 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~\cite{Buhr00b}.

\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 for applications that can be constructed without shared data and direct blocking.
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, Andrew Beach and Michael Brooks 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: %
