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

\articletype{RESEARCH ARTICLE}%

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

\raggedbottom

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

% Latex packages used in the document.

\usepackage{epic,eepic}
\usepackage{xspace}
\usepackage{comment}
\usepackage{upquote}						% switch curled `'" to straight
\usepackage{listings}						% format program code
\usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig}
\renewcommand{\thesubfigure}{(\Alph{subfigure})}
\captionsetup{justification=raggedright,singlelinecheck=false}
\usepackage{dcolumn}						% align decimal points in tables
\usepackage{capt-of}

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

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

\renewcommand{\topfraction}{0.8}			% float must be greater than X of the page before it is forced onto its own page
\renewcommand{\bottomfraction}{0.8}			% float must be greater than X of the page before it is forced onto its own page
\renewcommand{\floatpagefraction}{0.8}		% float must be greater than X of the page before it is forced onto its own page
\renewcommand{\textfraction}{0.0}			% the entire page maybe devoted to floats with no text on the page at all

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

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

% Names used in the document.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

\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 modern, polymorphic, non-object-oriented, backwards-compatible extension of the C programming language.
This paper discusses some advanced control-flow and concurrency/parallelism features in \CFA, along with the supporting runtime.
These features are created from scratch because they do not exist in ISO C, or are low-level and/or unimplemented, so C programmers continue to rely on library features, like C pthreads.
\CFA introduces language-level control-flow mechanisms, like coroutines, user-level threading, and monitors for mutual exclusion and synchronization.
A unique contribution of this work is allowing multiple monitors to be safely acquired \emph{simultaneously} (deadlock free), while integrating this capability with monitor synchronization mechanisms.
These features also 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{coroutines, concurrency, parallelism, threads, monitors, runtime, C, \CFA (Cforall)}


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

\maketitle


\section{Introduction}

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

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

A further effort over the past decade is the development of language memory-models to deal with the conflict between certain language features and compiler/hardware optimizations.
This issue can be rephrased as: some language features are pervasive (language and runtime) and cannot be safely added via a library to prevent invalidation by sequential optimizations~\cite{Buhr95a,Boehm05}.
The consequence is that a language must be cognizant of these features and provide sufficient tools to program around any safety issues.
For example, C created the @volatile@ qualifier to provide correct execution for @setjmp@/@logjmp@ (concurrency came later).
The common solution is to provide a handful of complex qualifiers and functions (e.g., @volatile@ and atomics) allowing programmers to write consistent/race-free programs, often in the sequentially-consistent memory-model~\cite{Boehm12}.

While having a sufficient memory-model allows sound libraries to be constructed, writing these libraries can quickly become awkward and error prone, and using these low-level libraries has the same issues.
Essentially, using low-level explicit locks is the concurrent equivalent of assembler programming.
Just as most assembler programming is replaced with high-level programming, explicit locks can be replaced with high-level concurrency in a programming language.
Then the goal is for the compiler to check for correct usage and follow any complex coding conventions implicitly.
The drawback is that language constructs may preclude certain specialized techniques, therefore introducing inefficiency or inhibiting concurrency.
For most concurrent programs, these drawbacks are insignificant in comparison to the speed of composition, and subsequent reliability and maintainability of the high-level concurrent program.
(The same is true for high-level programming versus assembler programming.)
Only very rarely should it be necessary to drop down to races and/or explicit locks to apply a specialized technique to achieve maximum speed or concurrency.
As stated, this observation applies to non-concurrent forms of complex control-flow, like exception handling and coroutines.

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

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

We present comparative examples so the reader can judge if the \CFA control-flow extensions are equivalent or better than those in or proposed for \Celeven, \CC and other concurrent, imperative programming languages, and perform experiments to show the \CFA runtime is competitive with other similar mechanisms.
The detailed contributions of this work are:
\begin{itemize}
\item
allowing multiple monitors to be safely acquired \emph{simultaneously} (deadlock free), while seamlessly integrating this capability with all monitor synchronization mechanisms.
\item
all control-flow features respect the expectations of C programmers, with statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features.
\item
experimental results show comparable performance of the new features with similar mechanisms in other concurrent programming-languages.
\end{itemize}

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

The following terminology is used.
A \newterm{thread} is a fundamental unit of execution that runs a sequence of code and requires a stack to maintain state.
Multiple simultaneous threads give rise to \newterm{concurrency}, which requires locking to ensure access to shared data and safe communication.
\newterm{Locking}, and by extension \newterm{locks}, are defined as a mechanism to prevent progress of threads to provide safety.
\newterm{Parallelism} is running multiple threads simultaneously.
Parallelism implies \emph{actual} simultaneous execution, where concurrency only requires \emph{apparent} simultaneous execution.
As such, parallelism only affects performance, which is observed through differences in space and/or time at runtime.
Hence, there are two problems to be solved: concurrency and parallelism.
While these two concepts are often combined, they are distinct, requiring different tools~\cite[\S~2]{Buhr05a}.
Concurrency tools handle mutual exclusion and synchronization, while parallelism tools handle performance, cost, and resource utilization.

The proposed concurrency API is implemented in a dialect of C, called \CFA (pronounced C-for-all).
The paper discusses how the language features are added to the \CFA translator with respect to parsing, semantics, and type checking, and the corresponding high-performance runtime-library to implement the concurrent features.
\end{comment}


\begin{comment}
\section{\CFA Overview}

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

\CFA is a non-object-oriented extension of ISO-C, and hence, supports all C paradigms.
Like C, the building blocks of \CFA are structures and routines.
Virtually all of the code generated by the \CFA translator respects C memory layouts and calling conventions.
While \CFA is not object oriented, lacking the concept of a receiver (\eg @this@) and nominal inheritance-relationships, C has a notion of objects: ``region of data storage in the execution environment, the contents of which can represent values''~\cite[3.15]{C11}.
While some object-oriented features appear in \CFA, they are independent capabilities, allowing \CFA to adopt them while maintaining a procedural paradigm.


\subsection{References}

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

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


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

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

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


\subsection{Overloading}

\CFA maximizes the ability to reuse names via overloading to aggressively address the naming problem.
Both variables and routines may be overloaded, where selection is based on number and types of returns and arguments (as in Ada~\cite{Ada}).
\newpage
\vspace*{-2\baselineskip}%???
\begin{cquote}
\begin{cfa}
// selection based on type
\end{cfa}
\lstDeleteShortInline@%
\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
const short int `MIN` = -32768;
const int `MIN` = -2147483648;
const long int `MIN` = -9223372036854775808L;
\end{cfa}
&
\begin{cfa}
short int si = `MIN`;
int i = `MIN`;
long int li = `MIN`;
\end{cfa}
\end{tabular}
\begin{cfa}
// selection based on type and number of parameters
\end{cfa}
\begin{tabular}{@{}l@{\hspace{2.7\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
void `f`( void );
void `f`( char );
void `f`( int, double );
\end{cfa}
&
\begin{cfa}
`f`();
`f`( 'a' );
`f`( 3, 5.2 );
\end{cfa}
\end{tabular}
\begin{cfa}
// selection based on type and number of returns
\end{cfa}
\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
char `f`( int );
double `f`( int );
[char, double] `f`( int );
\end{cfa}
&
\begin{cfa}
char c = `f`( 3 );
double d = `f`( 3 );
[d, c] = `f`( 3 );
\end{cfa}
\end{tabular}
\lstMakeShortInline@%
\end{cquote}
Overloading is important for \CFA concurrency since the runtime system relies on creating different types to represent concurrency objects.
Therefore, overloading eliminates long prefixes and other naming conventions to prevent name clashes.
As seen in Section~\ref{s:Concurrency}, routine @main@ is heavily overloaded.
As another example, variable overloading is useful in the parallel semantics of the @with@ statement for fields with the same name:
\begin{cfa}
struct S { int `i`; int j; double m; } s;
struct T { int `i`; int k; int m; } t;
with ( s, t ) {
	j + k;									$\C{// unambiguous, s.j + t.k}$
	m = 5.0;								$\C{// unambiguous, s.m = 5.0}$
	m = 1;									$\C{// unambiguous, t.m = 1}$
	int a = m;								$\C{// unambiguous, a = t.m }$
	double b = m;							$\C{// unambiguous, b = s.m}$
	int c = `s.i` + `t.i`;					$\C{// unambiguous, qualification}$
	(double)m;								$\C{// unambiguous, cast s.m}$
}
\end{cfa}
For parallel semantics, both @s.i@ and @t.i@ are visible with the same type, so only @i@ is ambiguous without qualification.


\subsection{Operators}

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


\subsection{Constructors / Destructors}

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


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

The signature feature of \CFA is parametric-polymorphic routines~\cite{Cforall} with routines generalized using a @forall@ clause (giving the language its name), which allow separately compiled routines to support generic usage over multiple types.
For example, the following sum routine works for any type that supports construction from 0 and addition:
\begin{cfa}
forall( otype T | { void `?{}`( T *, zero_t ); T `?+?`( T, T ); } ) // constraint type, 0 and +
T sum( T a[$\,$], size_t size ) {
	`T` total = { `0` };					$\C{// initialize by 0 constructor}$
	for ( size_t i = 0; i < size; i += 1 )
		total = total `+` a[i];				$\C{// select appropriate +}$
	return total;
}
S sa[5];
int i = sum( sa, 5 );						$\C{// use S's 0 construction and +}$
\end{cfa}
Type variables can be @otype@ or @dtype@.
@otype@ refers to a \emph{complete type}, \ie, a type with size, alignment, default constructor, copy constructor, destructor, and assignment operator.
@dtype@ refers to an \emph{incomplete type}, \eg, void or a forward-declared type.
The builtin types @zero_t@ and @one_t@ overload constant 0 and 1 for a new types, where both 0 and 1 have special meaning in C.

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

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


\section{Coroutines: Stepping Stone}
\label{coroutine}

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

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

\begin{figure}
\centering
\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`int 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}

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

	int ret = f->fn2;
	int fn = f->fn1 + f->fn2;
	f->fn2 = f->fn1; f->fn1 = fn;

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

\subfloat[3 states: global variables]{\label{f:GlobalVariables}\usebox\myboxA}
\qquad
\subfloat[1 state: encapsulated variables]{\label{f:ExternalState}\usebox\myboxB}
\caption{C fibonacci fsm}
\label{f:C-fibonacci}

\bigskip

\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`coroutine` Fib { int fn; };
void main( Fib & fib ) with( fib ) {
	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}

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

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

\begin{figure}
\centering
\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`coroutine` Fmt {
	char ch;   // communication variables
	int g, b;   // needed in destructor
};
void main( Fmt & fmt ) with( fmt ) {
	for () {
		for ( g = 0; g < 5; g += 1 ) { // groups
			for ( b = 0; b < 4; b += 1 ) { // blocks
				`suspend();`
				sout | ch; } // print character
			sout | "  "; } // block separator
		sout | nl; }  // group separator
}
void ?{}( Fmt & fmt ) { `resume( fmt );` } // prime
void ^?{}( Fmt & fmt ) with( fmt ) { // destructor
	if ( g != 0 || b != 0 )	// special case
		sout | nl; }
void send( Fmt & fmt, char c ) { fmt.ch = c; `resume( fmt )`; }
int main() {
	Fmt fmt;
 	sout | nlOff;	// turn off auto newline
	for ( 41 )
		send( fmt, 'a' );
}
\end{cfa}
\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
for i in range( 41 ):
	`fmt.send( 'a' );`	# send to yield

\end{python}
\end{lrbox}
\subfloat[\CFA]{\label{f:CFAFmt}\usebox\myboxA}
\qquad
\subfloat[Python]{\label{f:CFmt}\usebox\myboxB}
\caption{Output formatting text}
\label{f:fmt-line}
\end{figure}

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

\begin{figure}
\centering
\lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $
\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
`coroutine` Prod {
	Cons & c;
	int N, money, receipt;
};
void main( Prod & prod ) with( prod ) {
	// 1st resume starts here
	for ( 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; // reassignable reference
	prod.[N, receipt] = [N, 0];
	`resume( prod );`
}
int main() {
	Prod prod;
	Cons cons = { prod };
	start( prod, 5, cons );
}
\end{cfa}
&
\begin{cfa}
`coroutine` Cons {
	Prod & p;
	int p1, p2, status;
	bool done;
};
void ?{}( Cons & cons, Prod & p ) {
	&cons.p = &p; // reassignable reference
	cons.[status, done ] = [0, false];
}
void ^?{}( Cons & cons ) {}
void main( Cons & cons ) with( cons ) {
	// 1st resume starts here
	int money = 1, receipt;
	for ( ; ! done; ) {
		sout | p1 | " " | p2 | 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 a producer/consumer symmetric-coroutine performing bi-directional communication.
Since the solution involves a full-coroutining cycle, the program main creates one coroutine in isolation, passes this coroutine to its partner, and closes the cycle at the call to @start@.
The @start@ routine communicates both the number of elements to be produced and the consumer into the producer's coroutine-structure.
Then the @resume@ to @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
@prod@'s coroutine main starts, creates local variables that are retained between coroutine activations, and executes $N$ iterations, each generating two random values, calling the consumer to deliver the values, and printing the status returned from the consumer.

The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
For the first resume, @cons@'s stack is initialized, creating local variables retained between subsequent activations of the coroutine.
The consumer iterates until the @done@ flag is set, prints 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.

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

One \emph{killer} application for a coroutine is device drivers, which at one time caused 70\%-85\% of failures in Windows/Linux~\cite{Swift05}.
Many device drivers are a finite state-machine parsing a protocol, e.g.:
\begin{tabbing}
\ldots STX \= \ldots message \ldots \= ESC \= ETX \= \ldots message \ldots  \= ETX \= 2-byte crc \= \ldots	\kill
\ldots STX \> \ldots message \ldots \> ESC \> ETX \> \ldots message \ldots  \> ETX \> 2-byte crc \> \ldots
\end{tabbing}
where a network message begins with the control character STX and ends with an ETX, followed by a 2-byte cyclic-redundancy check.
Control characters may appear in a message if preceded by an ESC.
Because FSMs can be complex and occur frequently in important domains, direct support of the coroutine is crucial in a systems programminglanguage.

\begin{figure}
\begin{cfa}
enum Status { CONT, MSG, ESTX, ELNTH, ECRC };
`coroutine` Driver {
	Status status;
	char * msg, byte;
};
void ?{}( Driver & d, char * m ) { d.msg = m; }		$\C[3.0in]{// constructor}$
Status next( Driver & d, char b ) with( d ) {		$\C{// 'with' opens scope}$
	byte = b; `resume( d );` return status;
}
void main( Driver & d ) with( d ) {
	enum { STX = '\002', ESC = '\033', ETX = '\003', MaxMsg = 64 };
	unsigned short int crc;							$\C{// error checking}$
  msg: for () {										$\C{// parse message}$
		status = CONT;
		unsigned int lnth = 0, sum = 0;
		while ( byte != STX ) `suspend();`
	  emsg: for () {
			`suspend();`							$\C{// process byte}$
			choose ( byte ) {						$\C{// switch with default break}$
			  case STX:
				status = ESTX; `suspend();` continue msg;
			  case ETX:
				break emsg;
			  case ESC:
				suspend();
			} // choose
			if ( lnth >= MaxMsg ) {					$\C{// buffer full ?}$
				status = ELNTH; `suspend();` continue msg; }
			msg[lnth++] = byte;
			sum += byte;
		} // for
		msg[lnth] = '\0';							$\C{// terminate string}\CRT$
		`suspend();`
		crc = (unsigned char)byte << 8;	// prevent sign extension for signed char
		`suspend();`
		status = (crc | (unsigned char)byte) == sum ? MSG : ECRC;
		`suspend();`
	} // for
}
\end{cfa}
\caption{Device driver for simple communication protocol}
\end{figure}


\subsection{Coroutine Implementation}

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

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

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

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

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

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

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

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



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


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

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

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

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

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

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


\subsection{Thread Interface}
\label{threads}

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


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

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

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

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

thread RtnRunner {
	voidRtn func;
	int arg;
};

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

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

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

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

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

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

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


\section{Mutual Exclusion / Synchronization}

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

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

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


\subsection{Mutual Exclusion}

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

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


\subsection{Synchronization}

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


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

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

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


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

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

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

For maximum usability, monitors have \newterm{multi-acquire} semantics allowing a thread to acquire it multiple times without deadlock.
\begin{cfa}
monitor M { ... } m;
void foo( M & mutex m ) { ... }				$\C{// acquire mutual exclusion}$
void bar( M & mutex m ) {					$\C{// acquire mutual exclusion}$
	... `foo( m );` ...						$\C{// reacquire mutual exclusion}$
}
`bar( m );`									$\C{// nested monitor call}$
\end{cfa}

The benefit of mandatory monitor qualifiers is self-documentation, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameters is redundant.
Instead, the semantics have one qualifier as the default, and the other required.
For example, make the safe @mutex@ qualifier the default because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
Alternatively, make the unsafe \lstinline[morekeywords=nomutex]@nomutex@ qualifier the default because it is the \emph{normal} parameter semantics while @mutex@ parameters are rare.
Providing a default qualifier implies knowing whether a parameter is a monitor.
Since \CFA relies heavily on traits as an abstraction mechanism, the distinction between a type that is a monitor and a type that looks like a monitor can become blurred.
For this reason, \CFA requires programmers to identify the kind of parameter with the @mutex@ keyword and uses no keyword to mean \lstinline[morekeywords=nomutex]@nomutex@.

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

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

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

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

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


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

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

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

\end{cfa}
\\
\multicolumn{1}{c}{\textbf{routine call}} & \multicolumn{1}{c}{\lstinline@mutex@ \textbf{statement}}
\end{tabular}
\end{cquote}


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

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

Figure~\ref{f:BBInt} shows a \CFA generic bounded-buffer with internal scheduling, where producers/consumers enter the monitor, see the buffer is full/empty, and block on an appropriate condition lock, @full@/@empty@.
The @wait@ routine atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the routine's parameter list.
The appropriate condition lock is signalled to unblock an opposite kind of thread after an element is inserted/removed from the buffer.
Signalling is unconditional, because signalling an empty condition lock does nothing.

Signalling semantics cannot have the signaller and signalled thread in the monitor simultaneously, which means:
\begin{enumerate}
\item
The signalling thread returns immediately, and the signalled thread continues.
\item
The signalling thread continues and the signalled thread is marked for urgent unblocking at the next scheduling point (exit/wait).
\item
The signalling thread blocks but is marked for urgrent unblocking at the next scheduling point and the signalled thread continues.
\end{enumerate}
The first approach is too restrictive, as it precludes solving a reasonable class of problems, \eg dating service (see Figure~\ref{f:DatingService}).
\CFA supports the next two semantics as both are useful.
Finally, while it is common to store a @condition@ as a field of the monitor, in \CFA, a @condition@ variable can be created/stored independently.
Furthermore, a condition variable is tied to a \emph{group} of monitors on first use, called \newterm{branding}, which means that using internal scheduling with distinct sets of monitors requires one condition variable per set of monitors.

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

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

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

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

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

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

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

Figure~\ref{f:BBExt} shows a \CFA generic bounded-buffer with external scheduling, where producers/consumers detecting a full/empty buffer block and prevent more producers/consumers from entering the monitor until there is a free/empty slot in the buffer.
External scheduling is controlled by the @waitfor@ statement, which atomically blocks the calling thread, releases the monitor lock, and restricts the routine calls that can next acquire mutual exclusion.
If the buffer is full, only calls to @remove@ can acquire the buffer, and if the buffer is empty, only calls to @insert@ can acquire the buffer.
Threads making calls to routines that are currently excluded, block outside of (external to) the monitor on a calling queue, versus blocking on condition queues inside of (internal to) the monitor.
External scheduling allows users to wait for events from other threads without concern of unrelated events occurring.
The mechnaism can be done in terms of control flow, \eg Ada @accept@ or \uC @_Accept@, or in terms of data, \eg Go channels.
While both mechanisms have strengths and weaknesses, this project uses a control-flow mechanism to stay consistent with other language semantics.
Two challenges specific to \CFA for external scheduling are loose object-definitions (see Section~\ref{s:LooseObjectDefinitions}) and multiple-monitor routines (see Section~\ref{s:Multi-MonitorScheduling}).

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

Figure~\ref{f:DatingService} shows a dating service demonstrating non-blocking and blocking signalling.
The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers.
A thread blocks until an appropriate partner arrives.
The complexity is exchanging phone numbers in the monitor because of the mutual-exclusion property.
For signal scheduling, the @exchange@ condition is necessary to block the thread finding the match, while the matcher unblocks to take the opposite number, post its phone number, and unblock the partner.
For signal-block scheduling, the implicit urgent-queue replaces the explict @exchange@-condition and @signal_block@ puts the finding thread on the urgent condition and unblocks the matcher.

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

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

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

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

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

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

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

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

Both internal and external scheduling extend to multiple monitors in a natural way.
\begin{cquote}
\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
\begin{cfa}
monitor M { `condition e`; ... };
void foo( M & mutex m1, M & mutex m2 ) {
	... wait( `e` ); ...   // wait( e, m1, m2 )
	... wait( `e, m1` ); ...
	... wait( `e, m2` ); ...
}
\end{cfa}
&
\begin{cfa}
void rtn$\(_1\)$( M & mutex m1, M & mutex m2 );
void rtn$\(_2\)$( M & mutex m1 );
void bar( M & mutex m1, M & mutex m2 ) {
	... waitfor( `rtn` ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\), m1, m2 )}$
	... waitfor( `rtn, m1` ); ... // $\LstCommentStyle{waitfor( rtn\(_2\), m1 )}$
}
\end{cfa}
\end{tabular}
\end{cquote}
For @wait( e )@, the default semantics is to atomically block the signaller and release all acquired mutex types in the parameter list, \ie @wait( e, m1, m2 )@.
To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
Wait statically verifies the released monitors are the acquired mutex-parameters so unconditional release is safe.
Finally, a signaller,
\begin{cfa}
void baz( M & mutex m1, M & mutex m2 ) {
	... signal( e ); ...
}
\end{cfa}
must have acquired at least the same locks as the waiting thread signalled from the condition queue.

Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex types in the parameter list, \ie @waitfor( rtn, m1, m2 )@.
To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn, m1 )@.
@waitfor@ statically verifies the released monitors are the same as the acquired mutex-parameters of the given routine or routine pointer.
To statically verify the released monitors match with the accepted routine's mutex parameters, the routine (pointer) prototype must be accessible.
% When an overloaded routine appears in an @waitfor@ statement, calls to any routine with that name are accepted.
% The rationale is that members with the same name should perform a similar function, and therefore, all should be eligible to accept a call.
Overloaded routines can be disambiguated using a cast:
\begin{cfa}
void rtn( M & mutex m );
`int` rtn( M & mutex m );
waitfor( (`int` (*)( M & mutex ))rtn, m );
\end{cfa}

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

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


\subsection{Barging Prevention}

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

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

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


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

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


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




\end{cfa}
\end{lrbox}

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

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

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


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

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

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

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

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


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

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

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

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

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

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


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

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

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

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

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


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

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


\subsection{Low-level Locks}

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


\section{Parallelism}

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


\subsection{User Threads with Preemption}

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


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

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


\subsection{Thread Pools}

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


\section{\protect\CFA Runtime Structure}

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

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


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

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

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


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

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


\subsection{Debug Kernel}

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


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

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

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

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

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

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

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

However, on current UNIX systems:
\begin{quote}
A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
SIGNAL(7) - Linux Programmer's Manual
\end{quote}
Hence, the timer-expiry signal, which is generated \emph{externally} by the UNIX kernel to the UNIX process, is delivered to any of its UNIX subprocesses (kernel threads).
To ensure each virtual processor receives its own preemption signals, a discrete-event simulation is run on a special virtual processor, and only it sets and receives timer events.
Virtual processors register an expiration time with the discrete-event simulator, which is inserted in sorted order.
The simulation sets the count-down timer to the value at the head of the event list, and when the timer expires, all events less than or equal to the current time are processed.
Processing a preemption event sends an \emph{internal} @SIGUSR1@ signal to the registered virtual processor, which is always delivered to that processor.


\section{Performance}
\label{results}

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

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

\begin{tabular}{|l|r||l|r|}
\hline
Architecture		& x86\_64 				& NUMA node(s) 	& 8 \\
\hline
CPU op-mode(s)		& 32-bit, 64-bit 		& Model name 	& AMD Opteron\texttrademark\ Processor 6380 \\
\hline
Byte Order			& Little Endian 		& CPU Freq 		& 2.5 GHz \\
\hline
CPU(s)				& 64 					& L1d cache 	& 16 KiB \\
\hline
Thread(s) per core	& 2 					& L1i cache 	& 64 KiB \\
\hline
Core(s) per socket	& 8 					& L2 cache 		& 2048 KiB \\
\hline
Socket(s)			& 4 					& L3 cache 		& 6144 KiB \\
\hline
\hline
Operating system	& Ubuntu 16.04.3 LTS	& Kernel		& Linux 4.4-97-generic \\
\hline
gcc					& 6.3	 				& \CFA			& 1.0.0 \\
\hline
Java				& OpenJDK-9 			& Go			& 1.9.2 \\
\hline
\end{tabular}
\end{table}

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


\paragraph{Context-Switching}

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

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

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

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


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

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

\centering

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

\bigskip
\bigskip

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

\centering

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

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


\paragraph{Mutual-Exclusion}

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


\paragraph{Internal Scheduling}

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

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

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

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


\paragraph{External Scheduling}

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

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

\centering

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

\bigskip
\medskip

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

\centering

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

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


\paragraph{Object Creation}

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


\section{Conclusion}

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


\section{Future Work}

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

\paragraph{Flexible Scheduling}
\label{futur:sched}

An important part of concurrency is scheduling.
Different scheduling algorithms can affect performance (both in terms of average and variation).
However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
One solution is to offer various tweaking options, allowing the scheduler to be adjusted to the requirements of the workload.
However, to be truly flexible, a pluggable scheduler is necessary.
Currently, the \CFA pluggable scheduler is too simple to handle complex scheduling, \eg quality of service and real-time, where the scheduler must interact with mutex objects to deal with issues like priority inversion.

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

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

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

While monitors offer flexible and powerful concurrency for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
Examples of such tools can include futures and promises~\cite{promises}, executors and actors.
These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
As well, new \CFA extensions should make it possible to create a uniform interface for virtually all mutual exclusion, including monitors and low-level locks.

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

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


\section{Acknowledgements}

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

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

\end{document}

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