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

\articletype{RESEARCH ARTICLE}%

% Referees
% Doug Lea, dl@cs.oswego.edu, SUNY Oswego
% Herb Sutter, hsutter@microsoft.com, Microsoft Corp
% Gor Nishanov, gorn@microsoft.com, Microsoft Corp
% James Noble, kjx@ecs.vuw.ac.nz, Victoria University of Wellington, School of Engineering and Computer Science

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

\raggedbottom

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

% Latex packages used in the document.

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

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

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

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

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

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

% Names used in the document.

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

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

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

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

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

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

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

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

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

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

% Denote newterms in particular font and index them without particular font and in lowercase, \eg \newterm{abc}.
% The option parameter provides an index term different from the new term, \eg \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{.}{\ETAL}%
		{\ETAL.\xspace}%
}}{}%
\@ifundefined{viz}{
\newcommand{\VIZ}{\abbrevFont{viz}}
\newcommand*{\viz}{%
	\@ifnextchar{.}{\VIZ}%
		{\VIZ.\xspace}%
}}{}%
\makeatother

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

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

% CFA programming language, based on ANSI C (with some gcc additions)
\lstdefinelanguage{CFA}[ANSI]{C}{
	morekeywords={
		_Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, __attribute, __attribute__,
		auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__, __const, __const__,
		coroutine, disable, dtype, enable, exception, __extension__, fallthrough, fallthru, finally,
		__float80, float80, __float128, float128, forall, ftype, generator, _Generic, _Imaginary, __imag, __imag__,
		inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
		otype, restrict, resume, __restrict, __restrict__, __signed, __signed__, _Static_assert, suspend, thread,
		_Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
		virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
	moredirectives={defined,include_next},
	% replace/adjust listing characters that look bad in sanserif
	literate={-}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
		{~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
		{<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
		{<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex{\textrm{\textgreater}}}2,
}

\lstset{
language=CFA,
columns=fullflexible,
basicstyle=\linespread{0.9}\sf,							% reduce line spacing and use sanserif font
stringstyle=\tt,										% use typewriter font
tabsize=5,												% N space tabbing
xleftmargin=\parindentlnth,								% indent code to paragraph indentation
%mathescape=true,										% LaTeX math escape in CFA code $...$
escapechar=\$,											% LaTeX escape in CFA code
keepspaces=true,										%
showstringspaces=false,									% do not show spaces with cup
showlines=true,											% show blank lines at end of code
aboveskip=4pt,											% spacing above/below code block
belowskip=3pt,
moredelim=**[is][\color{red}]{`}{`},
}% lstset

% uC++ programming language, based on ANSI C++
\lstdefinelanguage{uC++}[ANSI]{C++}{
	morekeywords={
		_Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _CatchResume, _Cormonitor, _Coroutine, _Disable,
		_Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
		_Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
}

% Go programming language: https://github.com/julienc91/listings-golang/blob/master/listings-golang.sty
\lstdefinelanguage{Golang}{
	morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
	morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
		bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
	morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
	morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
	morekeywords=[5]{Println,Printf,Error,},
	sensitive=true,
	morecomment=[l]{//},
	morecomment=[s]{/*}{*/},
	morestring=[b]',
	morestring=[b]",
	morestring=[s]{`}{`},
	% replace/adjust listing characters that look bad in sanserif
	literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
		{~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
		{<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
		{<-}{\makebox[2ex][c]{\textrm{\textless}\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}}2,
}

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

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

\newcommand{\commenttd}[1]{{\color{red}{Thierry : #1}}}

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

\newsavebox{\myboxA}
\newsavebox{\myboxB}
\newsavebox{\myboxC}
\newsavebox{\myboxD}

\title{\texorpdfstring{Advanced Control-flow and Concurrency in \protect\CFA}{Advanced Control-flow in Cforall}}

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

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

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

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

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

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


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

\maketitle


\section{Introduction}

\CFA~\cite{Moss18,Cforall} is a modern, polymorphic, non-object-oriented\footnote{
\CFA has object-oriented features, such as constructors, destructors, and simple trait/interface inheritance.
% Go interfaces, Rust traits, Swift Protocols, Haskell Type Classes and Java Interfaces.
% "Trait inheritance" works for me. "Interface inheritance" might also be a good choice, and distinguish clearly from implementation inheritance.
% You'll want to be a little bit careful with terms like "structural" and "nominal" inheritance as well. CFA has structural inheritance (I think Go as well) -- it's inferred based on the structure of the code.
% Java, Rust, and Haskell (not sure about Swift) have nominal inheritance, where there needs to be a specific statement that "this type inherits from this type".
However, functions \emph{cannot} be nested in structures and there is no mechanism to designate a function parameter as a receiver, \lstinline@this@, parameter.},
backwards-compatible extension of the C programming language.
In many ways, \CFA is to C as Scala~\cite{Scala} is to Java, providing a vehicle for new typing and control-flow capabilities on top of a highly popular programming language\footnote{
The TIOBE index~\cite{TIOBE} for May 2020 ranks the top five \emph{popular} programming languages as C 17\%, Java 16\%, Python 9\%, \CC 6\%, and \Csharp 4\% = 52\%, and over the past 30 years, C has always ranked either first or second in popularity.}
allowing immediate dissemination.
This paper discusses the design philosophy and implementation of \CFA's advanced control-flow and concurrent/parallel features, along with the supporting runtime written in \CFA.

% The call/return extensions retain state between callee and caller versus losing the callee's state on return;
% the concurrency extensions allow high-level management of threads.

The \CFA control-flow framework extends ISO \Celeven~\cite{C11} with new call/return and concurrent/parallel control-flow.
Call/return control-flow with argument and parameter passing appeared in the first programming languages.
Over the past 50 years, call/return has been augmented with features like static and dynamic call, exceptions (multi-level return) and generators/coroutines (see Section~\ref{s:StatefulFunction}).
While \CFA has mechanisms for dynamic call (algebraic effects~\cite{Zhang19}) and exceptions\footnote{
\CFA exception handling will be presented in a separate paper.
The key feature that dovetails with this paper is nonlocal 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++}}, this work only discusses retaining state between calls via generators and coroutines.
\newterm{Coroutining} was introduced by Conway~\cite{Conway63} (1963), discussed by Knuth~\cite[\S~1.4.2]{Knuth73V1}, implemented in Simula67~\cite{Simula67}, formalized by Marlin~\cite{Marlin80}, and is now popular and appears in old and new programming languages: CLU~\cite{CLU}, \Csharp~\cite{Csharp}, Ruby~\cite{Ruby}, Python~\cite{Python}, JavaScript~\cite{JavaScript}, Lua~\cite{Lua}, \CCtwenty~\cite{C++20Coroutine19}.
Coroutining is sequential execution requiring direct handoff among coroutines, \ie only the programmer is controlling execution order.
If coroutines transfer to an internal event-engine for scheduling the next coroutines (as in async-await), the program transitions into the realm of concurrency~\cite[\S~3]{Buhr05a}.
Coroutines are only a stepping stone towards concurrency where the commonality is that coroutines and threads retain state between calls.

\Celeven and \CCeleven define concurrency~\cite[\S~7.26]{C11}, but it is largely wrappers for a subset of the pthreads library~\cite{Pthreads}.\footnote{Pthreads concurrency is based on simple thread fork and join in a function and mutex or condition locks, which is low-level and error-prone}
Interestingly, almost a decade after the \Celeven standard, the most recent versions of gcc, clang, and msvc do not support the \Celeven include @threads.h@, indicating no interest in the C11 concurrency approach (possibly because of the recent effort to add concurrency to \CC).
While the \Celeven standard does not state a threading model, the historical association with pthreads suggests implementations would adopt kernel-level threading (1:1)~\cite{ThreadModel}, as for \CC.
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, many languages adopt the 1:1 kernel-threading model, like Java (Scala), Objective-C~\cite{obj-c-book}, \CCeleven~\cite{C11}, C\#~\cite{Csharp} and Rust~\cite{Rust}, with a variety of presentation mechanisms.
From 2000 onwards, several language implementations have championed the M:N user-threading model, like Go~\cite{Go}, Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, D~\cite{D}, and \uC~\cite{uC++,uC++book}, including putting green threads back into Java~\cite{Quasar}, and many user-threading libraries have appeared~\cite{Qthreads,MPC,Marcel}.
The main argument for user-level threading is that it is lighter weight than kernel threading because locking and context switching do not cross the kernel boundary, so there is less restriction on programming styles that encourages large numbers of threads performing medium-sized work to facilitate load balancing by the runtime~\cite{Verch12}.
As well, user-threading facilitates a simpler concurrency approach using thread objects that leverage sequential patterns versus events with call-backs~\cite{Adya02,vonBehren03}.
Finally, performant user-threading implementations, both in time and space, meet or exceed direct kernel-threading implementations, while achieving the programming advantages of high concurrency levels and safety.

A further effort over the past two decades is the development of language memory models to deal with the conflict between language features and compiler/hardware optimizations, \eg some language features are unsafe in the presence of aggressive sequential optimizations~\cite{Buhr95a,Boehm05}.
The consequence is that a language must provide sufficient tools to program around safety issues, as inline and library code is compiled as sequential without any explicit concurrent directive.
One solution is low-level qualifiers and functions, \eg @volatile@ and atomics, allowing \emph{programmers} to explicitly write safe, race-free~\cite{Boehm12} programs.
A safer solution is high-level language constructs so the \emph{compiler} knows the concurrency boundaries, \ie where mutual exclusion and synchronization are acquired and released, and provide implicit safety at and across these boundaries.
While the optimization problem is best known with respect to concurrency, it applies to other complex control-flow, like exceptions and coroutines.
As well, language solutions allow matching the language paradigm with the approach, \eg matching the functional paradigm with data-flow programming or the imperative paradigm with thread programming.

Finally, it is important for a language to provide safety over performance \emph{as the default}, allowing careful reduction of safety for performance when necessary.
Two concurrency violations of this philosophy are \emph{spurious} or \emph{random wakeup}~\cite[\S~9]{Buhr05a}, and \emph{barging}\footnote{
Barging is competitive succession instead of direct handoff, \ie after a lock is released both arriving and preexisting waiter threads compete to acquire the lock.
Hence, an arriving thread can temporally \emph{barge} ahead of threads already waiting for an event, which can repeat indefinitely leading to starvation of waiter threads.
} or signals-as-hints~\cite[\S~8]{Buhr05a}, where one is a consequence of the other, \ie once there is spurious wakeup, barging follows.
(Author experience teaching concurrency is that students are confused by these semantics.)
However, spurious wakeup is \emph{not} a foundational concurrency property~\cite[\S~9]{Buhr05a};
it is a performance design choice.
We argue removing spurious wakeup and signals-as-hints make concurrent programming simpler and safer as there is less local non-determinism to manage.
If barging acquisition is allowed, its specialized performance advantage should be available as an option not the default.

\CFA embraces language extensions for advanced control-flow, user-level threading, and safety as the default.
We present comparative examples to support our argument that the \CFA control-flow extensions are as expressive and safe as those in other concurrent imperative programming languages, and perform experiments to show the \CFA runtime is competitive with other similar mechanisms.
The main contributions of this work are:
\begin{itemize}[topsep=3pt,itemsep=0pt]
\item
a set of fundamental execution properties that dictate which language-level control-flow features need to be supported,

\item
integration of these language-level control-flow features, while respecting the style and expectations of C programmers,

\item
monitor synchronization without barging, and the ability to safely acquiring multiple monitors in a deadlock-free way, while seamlessly integrating these capabilities with all monitor synchronization mechanisms,

\item
providing statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features,

% \item
% library extensions for executors, futures, and actors built on the basic mechanisms.

\item
a runtime system without spurious wake-up and no performance loss,

\item
a dynamic partitioning mechanism to segregate groups of executing user and kernel threads performing specialized work, \eg web-server or compute engine, or requiring different scheduling, \eg NUMA or real-time.

% \item
% a non-blocking I/O library

\item
experimental results showing comparable performance of the \CFA features with similar mechanisms in other languages.
\end{itemize}

Section~\ref{s:FundamentalExecutionProperties} presents the compositional hierarchy of execution properties directing the design of control-flow features in \CFA.
Section~\ref{s:StatefulFunction} begins advanced control by introducing sequential functions that retain data and execution state between calls producing constructs @generator@ and @coroutine@.
Section~\ref{s:Concurrency} begins concurrency, or how to create (fork) and destroy (join) a thread producing the @thread@ construct.
Section~\ref{s:MutualExclusionSynchronization} discusses the two mechanisms to restricted nondeterminism when controlling shared access to resources, called mutual exclusion, and timing relationships among threads, called synchronization.
Section~\ref{s:Monitor} shows how both mutual exclusion and synchronization are safely embedded in the @monitor@ and @thread@ constructs.
Section~\ref{s:CFARuntimeStructure} describes the large-scale mechanism to structure threads and virtual processors (kernel threads).
Section~\ref{s:Performance} uses microbenchmarks to compare \CFA threading with pthreads, Java 11.0.6, Go 1.12.6, Rust 1.37.0, Python 3.7.6, Node.js v12.18.0, and \uC 7.0.0.


\section{Fundamental Execution Properties}
\label{s:FundamentalExecutionProperties}

The features in a programming language should be composed of a set of fundamental properties rather than an ad hoc collection chosen by the designers.
To this end, the control-flow features created for \CFA are based on the fundamental properties of any language with function-stack control-flow (see also \uC~\cite[pp.~140-142]{uC++}).
The fundamental properties are execution state, thread, and mutual-exclusion/synchronization.
These independent properties can be used to compose different language features, forming a compositional hierarchy, where the combination of all three is the most advanced feature, called a thread.
While it is possible for a language to only provide threads for composing programs~\cite{Hermes90}, this unnecessarily complicates and makes inefficient solutions to certain classes of problems.
As is shown, each of the non-rejected composed language features solves a particular set of problems, and hence, has a defensible position in a programming language.
If a compositional feature is missing, a programmer has too few fundamental properties resulting in a complex and/or inefficient solution.

In detail, the fundamental properties are:
\begin{description}[leftmargin=\parindent,topsep=3pt,parsep=0pt]
\item[\newterm{execution state}:]
is the state information needed by a control-flow feature to initialize and manage both compute data and execution location(s), and de-initialize.
For example, calling a function initializes a stack frame including contained objects with constructors, manages local data in blocks and return locations during calls, and de-initializes the frame by running any object destructors and management operations.
State is retained in fixed-sized aggregate structures (objects) and dynamic-sized stack(s), often allocated in the heap(s) managed by the runtime system.
The lifetime of state varies with the control-flow feature, where longer life-time and dynamic size provide greater power but also increase usage complexity and cost.
Control-flow transfers among execution states in multiple ways, such as function call, context switch, asynchronous await, etc.
Because the programming language determines what constitutes an execution state, implicitly manages this state, and defines movement mechanisms among states, execution state is an elementary property of the semantics of a programming language.
% An execution-state is related to the notion of a process continuation \cite{Hieb90}.

\item[\newterm{threading}:]
is execution of code that occurs independently of other execution, where an individual thread's execution is sequential.
Multiple threads provide \emph{concurrent execution};
concurrent execution becomes parallel when run on multiple processing units, \eg hyper-threading, cores, or sockets.
A programmer needs mechanisms to create, block and unblock, and join with a thread, even if these basic mechanisms are supplied indirectly through high-level features.

\item[\newterm{mutual-exclusion / synchronization (MES)}:]
is the concurrency mechanism to perform an action without interruption and establish timing relationships among multiple threads.
We contented these two properties are independent, \ie mutual exclusion cannot provide synchronization and vice versa without introducing additional threads~\cite[\S~4]{Buhr05a}.
Limiting MES functionality results in contrived solutions and inefficiency on multi-core von Neumann computers where shared memory is a foundational aspect of its design.
\end{description}
These properties are fundamental as they cannot be built from existing language features, \eg a basic programming language like C99~\cite{C99} cannot create new control-flow features, concurrency, or provide MES without (atomic) hardware mechanisms.


\subsection{Structuring Execution Properties}

Programming languages seldom present the fundamental execution properties directly to programmers.
Instead, the properties are packaged into higher-level constructs that encapsulate details and provide safety to these low-level mechanisms.
Interestingly, language designers often pick and choose among these execution properties proving a varying subset of constructs.

Table~\ref{t:ExecutionPropertyComposition} shows all combinations of the three fundamental execution properties available to language designers.
(When doing combination case-analysis, not all combinations are meaningful.)
The combinations of state, thread, and MES compose a hierarchy of control-flow features all of which have appeared in prior programming languages, where each of these languages have found the feature useful.
To understand the table, it is important to review the basic von Neumann execution requirement of at least one thread and execution state providing some form of call stack.
For table entries missing these minimal components, the property is borrowed from the invoker (caller).
Each entry in the table, numbered \textbf{1}--\textbf{12}, is discussed with respect to how the execution properties combine to generate a high-level language construct.

\begin{table}
\caption{Execution property composition}
\centering
\label{t:ExecutionPropertyComposition}
\renewcommand{\arraystretch}{1.25}
%\setlength{\tabcolsep}{5pt}
\vspace*{-5pt}
\begin{tabular}{c|c||l|l}
\multicolumn{2}{c||}{execution properties} & \multicolumn{2}{c}{mutual exclusion / synchronization} \\
\hline
stateful			& thread	& \multicolumn{1}{c|}{No} & \multicolumn{1}{c}{Yes} \\
\hline
\hline
No					& No		& \textbf{1}\ \ \ @struct@				& \textbf{2}\ \ \ @mutex@ @struct@		\\
\hline
Yes (stackless)		& No		& \textbf{3}\ \ \ @generator@			& \textbf{4}\ \ \ @mutex@ @generator@	\\
\hline
Yes (stackful)		& No		& \textbf{5}\ \ \ @coroutine@			& \textbf{6}\ \ \ @mutex@ @coroutine@	\\
\hline
No					& Yes		& \textbf{7}\ \ \ {\color{red}rejected}	& \textbf{8}\ \ \ {\color{red}rejected}	\\
\hline
Yes (stackless)		& Yes		& \textbf{9}\ \ \ {\color{red}rejected}	& \textbf{10}\ \ \ {\color{red}rejected} \\
\hline
Yes (stackful)		& Yes		& \textbf{11}\ \ \ @thread@				& \textbf{12}\ \ @mutex@ @thread@		\\
\end{tabular}
\vspace*{-8pt}
\end{table}

Case 1 is a structure where access functions borrow local state (stack frame/activation) and thread from the invoker and retain this state across \emph{callees}, \ie function local-variables are retained on the borrowed stack during calls.
Structures are a foundational mechanism for data organization, and access functions provide interface abstraction and code sharing in all programming languages.
Case 2 is case 1 with thread safety to a structure's state where access functions provide serialization (mutual exclusion) and scheduling among calling threads (synchronization).
A @mutex@ structure, often called a \newterm{monitor}, provides a high-level interface for race-free access of shared data in concurrent programming-languages.
Case 3 is case 1 where the structure can implicitly retain execution state and access functions use this execution state to resume/suspend across \emph{callers}, but resume/suspend does not retain a function's local state.
A stackless structure, often called a \newterm{generator} or \emph{iterator}, is \newterm{stackless} because it still borrows the caller's stack and thread, but the stack is used only to preserve state across its callees not callers.
Generators provide the first step toward directly solving problems like finite-state machines that retain data and execution state between calls, whereas normal functions restart on each call.
Case 4 is cases 2 and 3 with thread safety during execution of the generator's access functions.
A @mutex@ generator extends generators into the concurrent domain.
Cases 5 and 6 are like cases 3 and 4 where the structure is extended with an implicit separate stack, so only the thread is borrowed by access functions.
A stackful generator, often called a \newterm{coroutine}, is \newterm{stackful} because resume/suspend now context switch to/from the caller's and coroutine's stack.
A coroutine extends the state retained between calls beyond the generator's structure to arbitrary call depth in the access functions.
Cases 7, 8, 9 and 10 are rejected because a new thread must have its own stack, where the thread begins and stack frames are stored for calls, \ie it is unrealistic for a thread to borrow a stack.
For cases 9 and 10, the stackless frame is not growable, precluding accepting nested calls, making calls, blocking as it requires calls, or preemption as it requires pushing an interrupt frame, all of which compound to require an unknown amount of execution state.
Hence, if this kind of uninterruptable thread exists, it must execute to completion, \ie computation only, which severely restricts runtime management.
Cases 11 and 12 are a stackful thread with and without safe access to shared state.
A thread is the language mechanism to start another thread of control in a program with growable execution state for call/return execution.
In general, language constructs with more execution properties increase the cost of creation and execution along with complexity of usage.

Given the execution-properties taxonomy, programmers now ask three basic questions: is state necessary across callers and how much, is a separate thread necessary, is thread safety necessary.
Table~\ref{t:ExecutionPropertyComposition} then suggests the optimal language feature needed for implementing a programming problem.
The following sections describe how \CFA fills in \emph{all} the non-rejected table entries with language features, while other programming languages may only provide a subset of the table.


\subsection{Design Requirements}

The following design requirements largely stem from building \CFA on top of C.
\begin{itemize}[topsep=3pt,parsep=0pt]
\item
All communication must be statically type checkable for early detection of errors and efficient code generation.
This requirement is consistent with the fact that C is a statically-typed programming-language.

\item
Direct interaction among language features must be possible allowing any feature to be selected without restricting comm\-unication.
For example, many concurrent languages do not provide direct communication calls among threads, \ie threads only communicate indirectly through monitors, channels, messages, and/or futures.
Indirect communication increases the number of objects, consuming more resources, and requires additional synchronization and possibly data transfer.

\item
All communication is performed using function calls, \ie data is transmitted from argument to parameter and results are returned from function calls.
Alternative forms of communication, such as call-backs, message passing, channels, or communication ports, step outside of C's normal form of communication.

\item
All stateful features must follow the same declaration scopes and lifetimes as other language data.
For C that means at program startup, during block and function activation, and on demand using dynamic allocation.

\item
MES must be available implicitly in language constructs, \eg Java built-in monitors, as well as explicitly for specialized requirements, \eg @java.util.concurrent@, because requiring programmers to build MES using low-level locks often leads to incorrect programs.
Furthermore, reducing synchronization scope by encapsulating it within language constructs further reduces errors in concurrent programs.

\item
Both synchronous and asynchronous communication are needed.
However, we believe the best way to provide asynchrony, such as call-buffering/chaining and/or returning futures~\cite{multilisp}, is building it from expressive synchronous features.

\item
Synchronization must be able to control the service order of requests including prioritizing selection from different kinds of outstanding requests, and postponing a request for an unspecified time while continuing to accept new requests.
Otherwise, certain concurrency problems are difficult, \eg web server, disk scheduling, and the amount of concurrency is inhibited~\cite{Gentleman81}.
\end{itemize}
We have satisfied these requirements in \CFA while maintaining backwards compatibility with the huge body of legacy C programs.
% In contrast, other new programming languages must still access C programs (\eg operating-system service routines), but do so through fragile C interfaces.


\subsection{Asynchronous Await / Call}

Asynchronous await/call is a caller mechanism for structuring programs and/or increasing concurrency, where the caller (client) postpones an action into the future, which is subsequently executed by a callee (server).
The caller detects the action's completion through a \newterm{future} or \newterm{promise}.
The benefit is asynchronous caller execution with respect to the callee until future resolution.
For single-threaded languages like JavaScript, an asynchronous call passes a callee action, which is queued in the event-engine, and continues execution with a promise.
When the caller needs the promise to be fulfilled, it executes @await@.
A promise-completion call-back can be part of the callee action or the caller is rescheduled;
in either case, the call back is executed after the promise is fulfilled.
While asynchronous calls generate new callee (server) events, we contend this mechanism is insufficient for advanced control-flow mechanisms like generators or coroutines, which are discussed next.
Specifically, control between caller and callee occurs indirectly through the event-engine precluding direct handoff and cycling among events, and requires complex resolution of a control promise and data.
Note, @async-await@ is just syntactic-sugar over the event engine so it does not solve these deficiencies.
For multi-threaded languages like Java, the asynchronous call queues a callee action with an executor (server), which subsequently executes the work by a thread in the executor thread-pool.
The problem is when concurrent work-units need to interact and/or block as this effects the executor by stopping threads.
While it is possible to extend this approach to support the necessary mechanisms, \eg message passing in Actors, we show monitors and threads provide an equally competitive approach that does not deviate from normal call communication and can be used to build asynchronous call, as is done in Java.


\section{Stateful Function}
\label{s:StatefulFunction}

A \emph{stateful function} has the ability to remember state between calls, where state can be either data or execution, \eg plugin, device driver, finite-state machine (FSM).
A simple technique to retain data state between calls is @static@ declarations within a function, which is often implemented by hoisting the declarations to the global scope but hiding the names within the function using name mangling.
However, each call starts the function at the top making it difficult to determine the last point of execution in an algorithm, and requiring multiple flag variables and testing to reestablish the continuation point.
Hence, the next step of generalizing function state is implicitly remembering the return point between calls and reentering the function at this point rather than the top, called \emph{generators}\,/\,\emph{iterators} or \emph{stackless coroutines}.
For example, a Fibonacci generator retains data and execution state allowing it to remember prior values needed to generate the next value and the location in the algorithm to compute that value.
The next step of generalization is instantiating the function to allow multiple named instances, \eg multiple Fibonacci generators, where each instance has its own state, and hence, can generate an independent sequence of values.
Note, a subset of generator state is a function \emph{closure}, \ie the technique of capturing lexical references when returning a nested function.
A further generalization is adding a stack to a generator's state, called a \emph{coroutine}, so it can suspend outside of itself, \eg call helper functions to arbitrary depth before suspending back to its resumer without unwinding these calls.
For example, a coroutine iterator for a binary tree can stop the traversal at the visit point (pre, infix, post traversal), return the node value to the caller, and then continue the recursive traversal from the current node on the next call.

There are two styles of activating a stateful function, \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles).
These styles \emph{do not} cause incremental stack growth, \eg a million resume/suspend or resume/resume cycles do not remember each cycle just the last resumer for each cycle.
Selecting between stackless/stackful semantics and asymmetric/symmetric style is a tradeoff between programming requirements, performance, and design, where stackless is faster and smaller using modified call/return between closures, stackful is more general but slower and larger using context switching between distinct stacks, and asymmetric is simpler control-flow than symmetric.
Additionally, storage management for the closure/stack must be factored into design and performance, especially in unmanaged languages without garbage collection.
Note, creation cost (closure/stack) is amortized across usage, so activation cost (resume/suspend) is usually the dominant factor.

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

For example, Python presents asymmetric generators as a function object, \uC presents symmetric coroutines as a \lstinline[language=C++]|class|-like object, and many languages present threading using function pointers, @pthreads@~\cite{Butenhof97}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}.
\begin{center}
\begin{tabular}{@{}l|l|l@{}}
\multicolumn{1}{@{}c|}{Python asymmetric generator} & \multicolumn{1}{c|}{\uC symmetric coroutine} & \multicolumn{1}{c@{}}{Pthreads thread} \\
\hline
\begin{python}
`def Gen():` $\LstCommentStyle{\color{red}// function}$
	... yield val ...
gen = Gen()
for i in range( 10 ):
	print( next( gen ) )
\end{python}
&
\begin{uC++}
`_Coroutine Cycle {` $\LstCommentStyle{\color{red}// class}$
	Cycle * p;
	void main() { p->cycle(); }
	void cycle() { resume(); }  `};`
Cycle c1, c2; c1.p=&c2; c2.p=&c1; c1.cycle();
\end{uC++}
&
\begin{cfa}
void * `rtn`( void * arg ) { ... }
int i = 3, rc;
pthread_t t; $\C{// thread id}$
$\LstCommentStyle{\color{red}// function pointer}$
rc=pthread_create(&t, `rtn`, (void *)i);
\end{cfa}
\end{tabular}
\end{center}
\CFA's preferred presentation model for generators/coroutines/threads is a hybrid of functions and classes, giving an object-oriented flavour.
Essentially, the generator/coroutine/thread function is semantically coupled with a generator/coroutine/thread custom type via the type's name.
The custom type solves several issues, while accessing the underlying mechanisms used by the custom types is still allowed for flexibility reasons.
Each custom type is discussed in detail in the following sections.


\subsection{Generator}

Stackless generators (Table~\ref{t:ExecutionPropertyComposition} case 3) have the potential to be very small and fast, \ie as small and fast as function call/return for both creation and execution.
The \CFA goal is to achieve this performance target, possibly at the cost of some semantic complexity.
A series of different kinds of generators and their implementation demonstrate how this goal is accomplished.\footnote{
The \CFA operator syntax uses \lstinline|?| to denote operands, which allows precise definitions for pre, post, and infix operators, \eg \lstinline|?++|, \lstinline|++?|, and \lstinline|?+?|, in addition \lstinline|?\{\}| denotes a constructor, as in \lstinline|foo `f` = `\{`...`\}`|, \lstinline|^?\{\}| denotes a destructor, and \lstinline|?()| is \CC function call \lstinline|operator()|.
Operator \lstinline+|+ is overloaded for printing, like bit-shift \lstinline|<<| in \CC.
The \CFA \lstinline|with| clause opens an aggregate scope making its fields directly accessible, like Pascal \lstinline|with|, but using parallel semantics;
multiple aggregates may be opened.
\CFA has rebindable references \lstinline|int i, & ip = i, j; `&ip = &j;`| and non-rebindable references \lstinline|int i, & `const` ip = i, j; `&ip = &j;` // disallowed|.
}%

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





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

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

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


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

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

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

\subfloat[C]{\label{f:CFibonacci}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[\CFA]{\label{f:CFAFibonacciGen}\usebox\myboxB}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[C generated code for \CFA version]{\label{f:CFibonacciSim}\usebox\myboxC}
\caption{Fibonacci output asymmetric generator}
\label{f:FibonacciAsymmetricGenerator}

\bigskip

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

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

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

\subfloat[\CFA]{\label{f:CFAFormatGen}\usebox\myboxA}
\hspace{35pt}
\vrule
\hspace{3pt}
\subfloat[C generated code for \CFA version]{\label{f:CFormatGenImpl}\usebox\myboxB}
\hspace{3pt}
\caption{Formatter input asymmetric generator}
\label{f:FormatterAsymmetricGenerator}
\end{figure}

Figure~\ref{f:FibonacciAsymmetricGenerator} shows an unbounded asymmetric generator for an infinite sequence of Fibonacci numbers written left to right in C, \CFA, and showing the underlying C implementation for the \CFA version.
This generator is an \emph{output generator}, producing a new result on each resumption.
To compute Fibonacci, the previous two values in the sequence are retained to generate the next value, \ie @fn1@ and @fn@, plus the execution location where control restarts when the generator is resumed, \ie top or middle.
An additional requirement is the ability to create an arbitrary number of generators of any kind, \ie retaining one state in global variables is insufficient;
hence, state is retained in a closure between calls.
Figure~\ref{f:CFibonacci} shows the C approach of manually creating the closure in structure @Fib@, and multiple instances of this closure provide multiple Fibonacci generators.
The C version only has the middle execution state because the top execution state is declaration initialization.
Figure~\ref{f:CFAFibonacciGen} shows the \CFA approach, which also has a manual closure, but replaces the structure with a custom \CFA @generator@ type.
Each generator type must have a function named \lstinline|main|,
% \footnote{
% The name \lstinline|main| has special meaning in C, specifically the function where a program starts execution.
% Leveraging starting semantics to this name for generator/coroutine/thread is a logical extension.}
called a \emph{generator main} (leveraging the starting semantics for program @main@ in C), which is connected to the generator type via its single reference parameter.
The generator main contains @suspend@ statements that suspend execution without ending the generator versus @return@.
For the Fibonacci generator-main,
the top initialization state appears at the start and the middle execution state is denoted by statement @suspend@.
Any local variables in @main@ \emph{are not retained} between calls;
hence local variables are only for temporary computations \emph{between} suspends.
All retained state \emph{must} appear in the generator's type.
As well, generator code containing a @suspend@ cannot be refactored into a helper function called by the generator, because @suspend@ is implemented via @return@, so a return from the helper function goes back to the current generator not the resumer.
The generator is started by calling function @resume@ with a generator instance, which begins execution at the top of the generator main, and subsequent @resume@ calls restart the generator at its point of last suspension.
Resuming an ended (returned) generator is undefined.
Function @resume@ returns its argument generator so it can be cascaded in an expression, in this case to print the next Fibonacci value @fn@ computed in the generator instance.
Figure~\ref{f:CFibonacciSim} shows the C implementation of the \CFA asymmetric generator.
Only one execution-state field, @restart@, is needed to subscript the suspension points in the generator.
At the start of the generator main, the @static@ declaration, @states@, is initialized to the N suspend points in the generator, where operator @&&@ dereferences or references a label~\cite{gccValueLabels}.
Next, the computed @goto@ selects the last suspend point and branches to it.
The  cost of setting @restart@ and branching via the computed @goto@ adds very little cost to the suspend and resume calls.

An advantage of the \CFA explicit generator type is the ability to allow multiple type-safe interface functions taking and returning arbitrary types.
\begin{cfa}
int ?()( Fib & fib ) { return `resume( fib )`.fn; } $\C[3.9in]{// function-call interface}$
int ?()( Fib & fib, int N ) { for ( N - 1 ) `fib()`; return `fib()`; } $\C{// add parameter to skip N values}$
double ?()( Fib & fib ) { return (int)`fib()` / 3.14159; } $\C{// different return type, cast prevents recursive call}$
Fib f;  int i;  double d;
i = f();  i = f( 2 );  d = f();						$\C{// alternative interfaces}\CRT$
\end{cfa}
Now, the generator can be a separately compiled opaque-type only accessed through its interface functions.
For contrast, Figure~\ref{f:PythonFibonacci} shows the equivalent Python Fibonacci generator, which does not use a generator type, and hence only has a single interface, but an implicit closure.

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










\end{python}
\end{lrbox}

\newbox\myboxB
\begin{lrbox}{\myboxB}
\begin{python}[aboveskip=0pt,belowskip=0pt]
def Fmt():
	try:
		while True:						$\C[2.5in]{\# until destructor call}$
			for g in range( 5 ):		$\C{\# groups}$
				for b in range( 4 ):	$\C{\# blocks}$
					while True:
						ch = (yield)	$\C{\# receive from send}$
						if '\n' not in ch: $\C{\# ignore newline}$
							break
					print( ch, end='' )	$\C{\# print character}$
				print( '  ', end='' )	$\C{\# block separator}$
			print()						$\C{\# group separator}$
	except GeneratorExit:				$\C{\# destructor}$
		if g != 0 | b != 0:				$\C{\# special case}$
			print()
fmt = Fmt()
`next( fmt )`							$\C{\# prime, next prewritten}$
for i in range( 41 ):
	`fmt.send( 'a' );`					$\C{\# send to yield}$
\end{python}
\end{lrbox}

\hspace{30pt}
\subfloat[Fibonacci]{\label{f:PythonFibonacci}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[Formatter]{\label{f:PythonFormatter}\usebox\myboxB}
\caption{Python generator}
\label{f:PythonGenerator}
\end{figure}

Having to manually create the generator closure by moving local-state variables into the generator type is an additional programmer burden (removed by the coroutine in Section~\ref{s:Coroutine}).
This manual requirement follows from the generality of allowing variable-size local-state, \eg local state with a variable-length array requires dynamic allocation as the array size is unknown at compile time.
However, dynamic allocation significantly increases the cost of generator creation/destruction and is a showstopper for embedded real-time programming.
But more importantly, the size of the generator type is tied to the local state in the generator main, which precludes separate compilation of the generator main, \ie a generator must be inlined or local state must be dynamically allocated.
With respect to safety, we believe static analysis can discriminate persistent generator state from temporary generator-main state and raise a compile-time error for temporary usage spanning suspend points.
Our experience using generators is that the problems have simple data state, including local state, but complex execution state, so the burden of creating the generator type is small.
As well, C programmers are not afraid of this kind of semantic programming requirement, if it results in very small and fast generators.

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

% https://dl-acm-org.proxy.lib.uwaterloo.ca/

An important application for the asymmetric generator is a device-driver, because device drivers are a significant source of operating-system errors: 85\% in Windows XP~\cite[p.~78]{Swift05} and 51.6\% in Linux~\cite[p.~1358,]{Xiao19}. %\cite{Palix11}
Swift \etal~\cite[p.~86]{Swift05} restructure device drivers using the Extension Procedure Call (XPC) within the kernel via functions @nooks_driver_call@ and @nooks_kernel_call@, which have coroutine properties context switching to separate stacks with explicit hand-off calls;
however, the calls do not retain execution state, and hence always start from the top.
The alternative approach for implementing device drivers is using stack-ripping.
However, Adya \etal~\cite{Adya02} argue against stack ripping in Section 3.2 and suggest a hybrid approach in Section 4 using cooperatively scheduled \emph{fibers}, which is coroutining.

Figure~\ref{f:DeviceDriverGen} shows the generator advantages in implementing a simple network device-driver with the following protocol:
\begin{center}
\ldots\, STX \ldots\, message \ldots\, ESC ETX \ldots\, message \ldots\, ETX 2-byte crc \ldots
\end{center}
where the network message begins with the control character STX, ends with an ETX, and is followed by a 2-byte cyclic-redundancy check.
Control characters may appear in a message if preceded by an ESC.
When a message byte arrives, it triggers an interrupt, and the operating system services the interrupt by calling the device driver with the byte read from a hardware register.
The device driver returns a status code of its current state, and when a complete message is obtained, the operating system reads the message accumulated in the supplied buffer.
Hence, the device driver is an input/output generator, where the cost of resuming the device-driver generator is the same as call and return, so performance in an operating-system kernel is excellent.
The key benefits of using a generator are correctness, safety, and maintenance because the execution states are transcribed directly into the programming language rather than table lookup or stack ripping.
% The conclusion is that FSMs are complex and occur in important domains, so direct generator support is important in a system programming language.

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

Generators can also have symmetric activation using resume/resume to create control-flow cycles among generators.
(The trivial cycle is a generator resuming itself.)
This control flow is similar to recursion for functions but without stack growth.
Figure~\ref{f:PingPongFullCoroutineSteps} shows the steps for symmetric control-flow using for the ping/pong program in Figure~\ref{f:CFAPingPongGen}.
The program starts by creating the generators, @ping@ and @pong@, and then assigns the partners that form the cycle.
Constructing the cycle must deal with definition-before-use to close the cycle, \ie, the first generator must know about the last generator, which is not within scope.
(This issue occurs for any cyclic data structure.)
% (Alternatively, the constructor can assign the partners as they are declared, except the first, and the first-generator partner is set after the last generator declaration to close the cycle.)
Once the cycle is formed, the program main resumes one of the generators, @ping@, and the generators can then traverse an arbitrary number of cycles using @resume@ to activate partner generator(s).
Terminating the cycle is accomplished by @suspend@ or @return@, both of which go back to the stack frame that started the cycle (program main in the example).
Note, the creator and starter may be different, \eg if the creator calls another function that starts the cycle.
The starting stack-frame is below the last active generator because the resume/resume cycle does not grow the stack.
Also, since local variables are not retained in the generator function, there are no objects with destructors to be called, so the cost is the same as a function return.
Destructor cost occurs when the generator instance is deallocated by the creator.

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

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

void `main( PingPong & pp )` with(pp) {


	for ( ; i < N; i += 1 ) {
		sout | name | i;
		`resume( partner );`
	}
}
int main() {
	enum { N = 5 };
	PingPong ping = {"ping",N,0}, pong = {"pong",N,0};
	&ping.partner = &pong;  &pong.partner = &ping;
	`resume( ping );`
}
\end{cfa}
\end{lrbox}

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

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

Figure~\ref{f:CPingPongSim} shows the C implementation of the \CFA symmetric generator, where there is still only one additional field, @restart@, but @resume@ is more complex because it does a forward rather than backward jump.
Before the jump, the parameter for the next call @partner@ is placed into the register used for the first parameter, @rdi@, and the remaining registers are reset for a return.
The @jmp comain@ restarts the function but with a different parameter, so the new call's behaviour depends on the state of the coroutine type, i.e., branch to restart location with different data state.
While the semantics of call forward is a tail-call optimization, which compilers perform, the generator state is different on each call rather a common state for a tail-recursive function (i.e., the parameter to the function never changes during the forward calls.
However, this assembler code depends on what entry code is generated, specifically if there are local variables and the level of optimization.
Hence, internal compiler support is necessary for any forward call or backwards return, \eg LLVM has various coroutine support~\cite{CoroutineTS}, and \CFA can leverage this support should it eventually fork @clang@.
For this reason, \CFA does not support general symmetric generators at this time, but, it is possible to hand generate any symmetric generators, as in Figure~\ref{f:CPingPongSim}, for proof of concept and performance testing.

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


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

Stackful coroutines (Table~\ref{t:ExecutionPropertyComposition} case 5) extend generator semantics with an implicit closure and @suspend@ may appear in a helper function called from the coroutine main because of the separate stack.
Note, simulating coroutines with stacks of generators, \eg Python with @yield from@ cannot handle symmetric control-flow.
Furthermore, all stack components must be of generators, so it is impossible to call a library function passing a generator that yields.
Creating a generator copy of the library function maybe impossible because the library function is opaque.

A \CFA coroutine is specified by replacing @generator@ with @coroutine@ for the type.
Coroutine generality results in higher cost for creation, due to dynamic stack allocation, for execution, due to context switching among stacks, and for terminating, due to possible stack unwinding and dynamic stack deallocation.
A series of different kinds of coroutines and their implementations demonstrate how coroutines extend generators.

First, the previous generator examples are converted to their coroutine counterparts, allowing local-state variables to be moved from the generator type into the coroutine main.
Now the coroutine type only contains communication variables between interface functions and the coroutine main.
\begin{center}
\begin{tabular}{@{}l|l|l|l@{}}
\multicolumn{1}{c|}{Fibonacci} & \multicolumn{1}{c|}{Formatter} & \multicolumn{1}{c|}{Device Driver} & \multicolumn{1}{c}{PingPong} \\
\hline
\begin{cfa}[xleftmargin=0pt]
void main( Fib & fib ) ...
	`int fn1;`


\end{cfa}
&
\begin{cfa}[xleftmargin=0pt]
for ( `g`; 5 ) {
	for ( `b`; 4 ) {


\end{cfa}
&
\begin{cfa}[xleftmargin=0pt]
status = CONT;
`int lnth = 0, sum = 0;`
...
`short int crc = byte << 8;`
\end{cfa}
&
\begin{cfa}[xleftmargin=0pt]
void main( PingPong & pp ) ...
	for ( `i`; N ) {


\end{cfa}
\end{tabular}
\end{center}
It is also possible to refactor code containing local-state and @suspend@ statements into a helper function, like the computation of the CRC for the device driver.
\begin{cfa}
int Crc() {
	`suspend;`  short int crc = byte << 8;
	`suspend;`  status = (crc | byte) == sum ? MSG : ECRC;
	return crc;
}
\end{cfa}
A call to this function is placed at the end of the device driver's coroutine-main.
For complex finite-state machines, refactoring is part of normal program abstraction, especially when code is used in multiple places.
Again, this complexity is usually associated with execution state rather than data state.

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

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

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



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

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


\end{cfa}
\end{lrbox}

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

def Fib():

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


// next prewritten


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



\end{python}
\end{lrbox}

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

\bigskip

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

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


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

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

\begin{figure}
\centering
\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
\begin{cfa}
`coroutine` Prod {
	Cons & c;			$\C[1.5in]{// communication}$
	int N, money, receipt;
};
void main( Prod & prod ) with( prod ) {
	for ( i; N ) {		$\C{// 1st resume}\CRT$
		int p1 = random( 100 ), p2 = random( 100 );
		int status = delivery( c, p1, p2 );
		receipt += 1;
	}
	stop( c );
}
int payment( Prod & prod, int money ) {
	prod.money = money;
	`resume( prod );`
	return prod.receipt;
}
void start( Prod & prod, int N, Cons &c ) {
	&prod.c = &c;
	prod.[N, receipt] = [N, 0];
	`resume( prod );`
}
int main() {
	Prod prod;
	Cons cons = { prod };
	start( prod, 5, cons );
}
\end{cfa}
&
\begin{cfa}
`coroutine` Cons {
	Prod & p;			$\C[1.5in]{// communication}$
	int p1, p2, status;
	bool done;
};
void ?{}( Cons & cons, Prod & p ) {
	&cons.p = &p;		$\C{// reassignable reference}$
	cons.[status, done ] = [0, false];
}
void main( Cons & cons ) with( cons ) {
	int money = 1, receipt; $\C{// 1st resume}\CRT$
	for ( ; ! done; ) {
		status += 1;
		receipt = payment( p, money );
		money += 1;
	}
}
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, bidirectional communication}
\label{f:ProdCons}
\end{figure}

Figure~\ref{f:ProdCons} shows the ping-pong example in Figure~\ref{f:CFAPingPongGen} extended into a producer/consumer symmetric-coroutine performing bidirectional communication.
This example is illustrative because both producer and consumer have two interface functions with @resume@s that suspend execution in these interface functions.
The program main creates the producer coroutine, passes it to the consumer coroutine in its initialization, and closes the cycle at the call to @start@ along with the number of items to be produced.
The call to @start@ is the first @resume@ of @prod@, which remembers the program main as the starter and creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
@prod@'s coroutine main starts, creates local-state variables that are retained between coroutine activations, and executes $N$ iterations, each generating two random values, calling the consumer's @deliver@ function to transfer the values, and printing the status returned from the consumer.
The producer's call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
Similarly on the first resume, @cons@'s stack is created and initialized, holding local-state variables retained between subsequent activations of the coroutine.
The symmetric coroutine cycle forms when the consumer calls the producer's @payment@ function, which resumes the producer in the consumer's delivery function.
When the producer calls @delivery@ again, it resumes the consumer in the @payment@ function.
Both interface functions then return to their corresponding coroutine-main functions for the next cycle.
Figure~\ref{f:ProdConsRuntimeStacks} shows the runtime stacks of the program main, and the coroutine mains for @prod@ and @cons@ during the cycling.
As a consequence of a coroutine retaining its last resumer for suspending back, these reverse pointers allow @suspend@ to cycle \emph{backwards} around a symmetric coroutine cycle.

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

Terminating a coroutine cycle is more complex than a generator cycle, because it requires context switching to the program main's \emph{stack} to shutdown the program, whereas generators started by the program main run on its stack.
Furthermore, each deallocated coroutine must execute all destructors for objects allocated in the coroutine type \emph{and} allocated on the coroutine's stack at the point of suspension, which can be arbitrarily deep.
In the example, termination begins with the producer's loop stopping after N iterations and calling the consumer's @stop@ function, which sets the @done@ flag, resumes the consumer in function @payment@, terminating the call, and the consumer's loop in its coroutine main.
% (Not shown is having @prod@ raise a nonlocal @stop@ exception at @cons@ after it finishes generating values and suspend back to @cons@, which catches the @stop@ exception to terminate its loop.)
When the consumer's main ends, its stack is already unwound so any stack allocated objects with destructors are finalized.
The question now is where does control continue?

The na\"{i}ve semantics for coroutine-cycle termination is to context switch to the last resumer, like executing a @suspend@ or @return@ in a generator.
However, for coroutines, the last resumer is \emph{not} implicitly below the current stack frame, as for generators, because each coroutine's stack is independent.
Unfortunately, it is impossible to determine statically if a coroutine is in a cycle and unrealistic to check dynamically (graph-cycle problem).
Hence, a compromise solution is necessary that works for asymmetric (acyclic) and symmetric (cyclic) coroutines.
Our solution is to retain a coroutine's starter (first resumer), and context switch back to the starter when the coroutine ends.
Hence, the consumer restarts its first resumer, @prod@, in @stop@, and when the producer ends, it restarts its first resumer, program main, in @start@ (see dashed lines from the end of the coroutine mains in Figure~\ref{f:ProdConsRuntimeStacks}).
This semantics works well for the most common asymmetric and symmetric coroutine usage patterns.
For asymmetric coroutines, it is common for the first resumer (starter) coroutine to be the only resumer;
for symmetric coroutines, it is common for the cycle creator to persist for the lifetime of the cycle.
For other scenarios, it is always possible to devise a solution with additional programming effort, such as forcing the cycle forward or backward to a safe point before starting termination.

Note, the producer/consumer example does not illustrate the full power of the starter semantics because @cons@ always ends first.
Assume generator @PingPong@ in Figure~\ref{f:PingPongSymmetricGenerator} is converted to a coroutine.
Unlike generators, coroutines have a starter structure with multiple levels, where the program main starts @ping@ and @ping@ starts @pong@.
By adjusting $N$ for either @ping@ or @pong@, it is possible to have either finish first.
If @pong@ ends first, it resumes its starter @ping@ in its coroutine main, then @ping@ ends and resumes its starter the program main on return;
if @ping@ ends first, it resumes its starter the program main on return.
Regardless of the cycle complexity, the starter structure always leads back to the program main, but the path can be entered at an arbitrary point.
Once back at the program main (creator), coroutines @ping@ and @pong@ are deallocated, running any destructors for objects within the coroutine and possibly deallocating any coroutine stacks for non-terminated coroutines, where stack deallocation implies stack unwinding to find destructors for allocated objects on the stack.
Hence, the \CFA termination semantics for the generator and coroutine ensure correct deallocation semantics, regardless of the coroutine's state (terminated or active), like any other aggregate object.


\subsection{Generator / Coroutine Implementation}

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

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

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

Part of the mechanism to generalize custom types is the \CFA trait~\cite[\S~2.3]{Moss18}, \eg the definition for custom-type @coroutine@ is anything satisfying the trait @is_coroutine@, and this trait both enforces and restricts the coroutine-interface functions.
\begin{cfa}
trait is_coroutine( `dtype` T ) {
	void main( T & );
	coroutine_desc * get_coroutine( T & );
};
forall( `dtype` T | is_coroutine(T) ) void $suspend$( T & ), resume( T & );
\end{cfa}
Note, copying generators, coroutines, and threads is undefined because multiple objects cannot execute on a shared stack and stack copying does not work in unmanaged languages (no garbage collection), like C, because the stack may contain pointers to objects within it that require updating for the copy.
The \CFA @dtype@ property provides no \emph{implicit} copying operations and the @is_coroutine@ trait provides no \emph{explicit} copying operations, so all coroutines must be passed by reference or pointer.
The function definitions ensure there is a statically typed @main@ function that is the starting point (first stack frame) of a coroutine, and a mechanism to read the coroutine descriptor from its handle.
The @main@ function has no return value or additional parameters because the coroutine type allows an arbitrary number of interface functions with arbitrary typed input and output values versus fixed ones.
The advantage of this approach is that users can easily create different types of coroutines, \eg changing the memory layout of a coroutine is trivial when implementing the @get_coroutine@ function, and possibly redefining \textsf{suspend} and @resume@.

The \CFA custom-type @coroutine@ implicitly implements the getter and forward declarations for the coroutine main.
\begin{cquote}
\begin{tabular}{@{}ccc@{}}
\begin{cfa}
coroutine MyCor {
	int value;

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



\end{cfa}
\end{tabular}
\end{tabular}
\end{cquote}
The combination of custom types and fundamental @trait@ description of these types allows a concise specification for programmers and tools, while more advanced programmers can have tighter control over memory layout and initialization.

Figure~\ref{f:CoroutineMemoryLayout} shows different memory-layout options for a coroutine (where a thread is similar).
The coroutine handle is the @coroutine@ instance containing programmer specified type global and communication variables across interface functions.
The coroutine descriptor contains all implicit declarations needed by the runtime, \eg @suspend@/@resume@, and can be part of the coroutine handle or separate.
The coroutine stack can appear in a number of locations and be fixed or variable sized.
Hence, the coroutine's stack could be a variable-length structure (VLS)
% \footnote{
% We are examining VLSs, where fields can be variable-sized structures or arrays.
% Once allocated, a VLS is fixed sized.}
on the allocating stack, provided the allocating stack is large enough.
For a VLS stack allocation and deallocation is an inexpensive adjustment of the stack pointer, modulo any stack constructor costs to initial frame setup.
For stack allocation in the heap, allocation and deallocation is an expensive allocation, where the heap can be a shared resource, modulo any stack constructor costs.
It is also possible to use a split or segmented stack calling convention, available with gcc and clang, allowing a variable-sized stack via a set of connected blocks in the heap.
Currently, \CFA supports stack and heap allocated descriptors but only fixed-sized heap allocated stacks.
In \CFA debug-mode, the fixed-sized stack is terminated with a write-only page, which catches most stack overflows.
Experience teaching concurrency with \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue for students.
Split-stack allocation is under development but requires recompilation of legacy code, which is not always possible.

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


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

Concurrency is nondeterministic scheduling of independent sequential execution paths (threads), where each thread has its own stack.
A single thread with multiple stacks, \ie coroutining, does \emph{not} imply concurrency~\cite[\S~3]{Buhr05a}.
Coroutining self-schedule the thread across stacks so execution is deterministic.
(It is \emph{impossible} to generate a concurrency error when coroutining.)

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

A scheduler can also be stackless or stackful.
For stackless, the scheduler performs scheduling on the stack of the current coroutine and switches directly to the next coroutine, so there is one context switch.
For stackful, the current coroutine switches to the scheduler, which performs scheduling, and it then switches to the next coroutine, so there are two context switches.
The \CFA runtime uses a stackful scheduler for uniformity and security.


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

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

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

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


\subsection{Thread Implementation}

Threads in \CFA are user level run by runtime kernel threads (see Section~\ref{s:CFARuntimeStructure}), where user threads provide concurrency and kernel threads provide parallelism.
Like coroutines, and for the same design reasons, \CFA provides a custom @thread@ type and a @trait@ to enforce and restrict the thread-interface functions.
\begin{cquote}
\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
\begin{cfa}
thread myThread {
	... // declaration/communication variables
};


\end{cfa}
&
\begin{cfa}
trait is_thread( `dtype` T ) {
	void main( T & );
	thread_desc * get_thread( T & );
	void ^?{}( T & `mutex` );
};
\end{cfa}
\end{tabular}
\end{cquote}
Like coroutines, the @dtype@ property prevents \emph{implicit} copy operations and the @is_thread@ trait provides no \emph{explicit} copy operations, so threads must be passed by reference or pointer.
Similarly, the function definitions ensure there is a statically typed @main@ function that is the thread starting point (first stack frame), a mechanism to read the thread descriptor from its handle, and a special destructor to prevent deallocation while the thread is executing.
(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitor}.)
The difference between the coroutine and thread is that a coroutine borrows a thread from its caller, so the first thread resuming a coroutine creates the coroutine's stack and starts running the coroutine main on the stack;
whereas, a thread is scheduling for execution in @main@ immediately after its constructor is run.
No return value or additional parameters are necessary for this function because the @thread@ type allows an arbitrary number of interface functions with corresponding arbitrary typed input and output values.


\section{Mutual Exclusion / Synchronization}
\label{s:MutualExclusionSynchronization}

Unrestricted nondeterminism is meaningless as there is no way to know when a result is completed and safe to access.
To produce meaningful execution requires clawing back some determinism using mutual exclusion and synchronization, where mutual exclusion provides access control for threads using shared data, and synchronization is a timing relationship among threads~\cite[\S~4]{Buhr05a}.
The shared data protected by mutual exclusion is called a \newterm{critical section}~\cite{Dijkstra65}, and the protection can be simple, only 1 thread, or complex, only N kinds of threads, \eg group~\cite{Joung00} or readers/writer~\cite{Courtois71} problems.
Without synchronization control in a critical section, an arriving thread can barge ahead of preexisting waiter threads resulting in short/long-term starvation, staleness and freshness problems, and incorrect transfer of data.
Preventing or detecting barging is a challenge with low-level locks, but made easier through higher-level constructs.
This challenge is often split into two different approaches: barging \emph{avoidance} and \emph{prevention}.
Approaches that unconditionally releasing a lock for competing threads to acquire must use barging avoidance with flag/counter variable(s) to force barging threads to wait;
approaches that conditionally hold locks during synchronization, \eg baton-passing~\cite{Andrews89}, prevent barging completely.

At the lowest level, concurrent control is provided by atomic operations, upon which different kinds of locking mechanisms are constructed, \eg spin locks, 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 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.
Some concurrent systems eliminate mutable shared-state by switching to non-shared communication like message passing~\cite{Thoth,Harmony,V-Kernel,MPI} (Erlang, MPI), channels~\cite{CSP} (CSP,Go), actors~\cite{Akka} (Akka, Scala), or functional techniques (Haskell).
However, these approaches introduce a new communication mechanism for concurrency different from the standard communication using function call/return.
Hence, a programmer must learn and manipulate two sets of design and programming patterns.
While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
In contrast, approaches based on shared-state models more closely resemble the standard call and return programming model, resulting in a single programming paradigm.
Finally, 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~\cite{Cascaval08,Boehm09} to be the main concurrency paradigm for system languages.


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

One of the most natural, elegant, efficient, high-level mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor} (Table~\ref{t:ExecutionPropertyComposition} case 2).
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 manually implement a monitor.
For these reasons, \CFA selected monitors as the core high-level concurrency construct, upon which higher-level approaches can be easily constructed.

Figure~\ref{f:AtomicCounter} compares a \CFA and Java monitor implementing an atomic counter.
(Like other concurrent programming languages, \CFA and Java have performant specializations for the basic types using atomic instructions.)
A \newterm{monitor} is a set of functions that ensure mutual exclusion when accessing shared state.
(Note, in \CFA, @monitor@ is short-hand for @mutex struct@.)
More precisely, a monitor is a programming technique that implicitly binds mutual exclusion to static function scope by call and return, as opposed to locks, where mutual exclusion is defined by acquire/release calls, independent of lexical context (analogous to block and heap storage allocation).
Restricting acquire and release points eases programming, comprehension, and maintenance, at a slight cost in flexibility and efficiency.
As for other special types, \CFA has a custom @monitor@ type.

\begin{figure}
\centering

\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
`monitor` Aint { // atomic integer counter
	int cnt;
};
int ++?( Aint & `mutex` this ) with(this) { return ++cnt; }
int ?=?( Aint & `mutex` lhs, int rhs ) with(lhs) { cnt = rhs; }
int ?=?(int & lhs, Aint & rhs) with(rhs) { lhs = cnt; }

int i = 0, j = 0, k = 5;
Aint x = { 0 }, y = { 0 }, z = { 5 }; // no mutex
++x; ++y; ++z;     // mutex
x = 2; y = i; z = k;  // mutex
i = x; j = y; k = z;  // no mutex
\end{cfa}
\end{lrbox}

\begin{lrbox}{\myboxB}
\begin{java}[aboveskip=0pt,belowskip=0pt]
class Aint {
    private int cnt;
    public Aint( int init ) { cnt = init; }
    `synchronized` public int inc() { return ++cnt; }
    `synchronized` public void set( int rhs ) {cnt=rhs;}
    public int get() { return cnt; }
}
int i = 0, j = 0, k = 5;
Aint x=new Aint(0), y=new Aint(0), z=new Aint(5);
x.inc(); y.inc(); z.inc();
x.set( 2 ); y.set( i ); z.set( k );
i = x.get(); j = y.get(); k = z.get();
\end{java}
\end{lrbox}

\subfloat[\CFA]{\label{f:AtomicCounterCFA}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[Java]{\label{f:AtomicCounterJava}\usebox\myboxB}
\caption{Atomic counter}
\label{f:AtomicCounter}
\end{figure}

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

Both Java and \CFA use a keyword @mutex@/\lstinline[language=java]|synchronized| to designate functions that implicitly acquire/release the monitor lock on call/return providing mutual exclusion to the stared data.
Non-designated functions provide no mutual exclusion for read-only access or as an interface to a multi-step protocol requiring several steps of acquiring and releasing the monitor.
Monitor objects can be passed through multiple helper functions without acquiring mutual exclusion, until a designated function associated with the object is called.
\CFA designated functions are marked by an explicitly parameter-only pointer/reference qualifier @mutex@ (discussed further in Section\ref{s:MutexAcquisition}).
Whereas, Java designated members are marked with \lstinline[language=java]|synchronized| that applies to the implicit reference parameter @this@.
In the example, the increment and setter operations need mutual exclusion while the read-only getter operation can be non-mutex if reading the implementation is atomic.


\subsection{Monitor Implementation}

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

\end{cfa}
&
\begin{cfa}
trait is_monitor( `dtype` T ) {
	monitor_desc * get_monitor( T & );
	void ^?{}( T & mutex );
};
\end{cfa}
\end{tabular}
\end{cquote}
The @dtype@ property prevents \emph{implicit} copy operations and the @is_monitor@ trait provides no \emph{explicit} copy operations, so monitors must be passed by reference or pointer.
Similarly, the function definitions ensure there is a mechanism to read the monitor descriptor from its handle, and a special destructor to prevent deallocation if a thread is using the shared data.
The custom monitor type also inserts any locks needed to implement the mutual exclusion semantics.
\CFA relies heavily on traits as an abstraction mechanism, so the @mutex@ qualifier prevents coincidentally matching of a monitor trait with a type that is not a monitor, similar to coincidental inheritance where a shape and playing card can both be drawable.


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

For object-oriented programming languages, the mutex property applies to one object, the implicit pointer/reference to the monitor type.
Because \CFA uses a pointer qualifier, other possibilities exist, \eg:
\begin{cfa}
monitor M { ... };
int f1( M & mutex m ); $\C{// single parameter object}$
int f2( M * mutex m ); $\C{// single or multiple parameter object}$
int f3( M * mutex m[$\,$] ); $\C{// multiple parameter object}$
int f4( stack( M * ) & mutex m ); $\C{// multiple parameters object}$
\end{cfa}
Function @f1@ has a single object parameter, while functions @f2@ to @f4@ can be a single or multi-element parameter with statically unknown size.
Because of the statically unknown size, \CFA only supports a single reference @mutex@ parameter, @f1@.

The \CFA @mutex@ qualifier does allow the ability to support multi-monitor functions,\footnote{
While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.}
where the number of acquisitions is statically known, called \newterm{bulk acquire}.
\CFA guarantees bulk acquisition order is consistent across calls to @mutex@ functions using the same monitors as arguments, so acquiring multiple monitors in a bulk acquire is safe from deadlock.
Figure~\ref{f:BankTransfer} shows a trivial solution to the bank transfer problem~\cite{BankTransfer}, where two resources must be locked simultaneously, using \CFA monitors with implicit locking and \CC with explicit locking.
A \CFA programmer only has to manage when to acquire mutual exclusion;
a \CC programmer must select the correct lock and acquisition mechanism from a panoply of locking options.
Making good choices for common cases in \CFA simplifies the programming experience and enhances safety.

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

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

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

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

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

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

Users can still force the acquiring order by using or not using @mutex@.
\begin{cfa}
void foo( M & mutex m1, M & mutex m2 ); $\C{// acquire m1 and m2}$
void bar( M & mutex m1, M & m2 ) { $\C{// only acquire m1}$
	... foo( m1, m2 ); ... $\C{// acquire m2}$
}
void baz( M & m1, M & mutex m2 ) { $\C{// only acquire m2}$
	... foo( m1, m2 ); ... $\C{// acquire m1}$
}
\end{cfa}
The bulk-acquire semantics allow @bar@ or @baz@ to acquire a monitor lock and reacquire it in @foo@.
The calls to @bar@ and @baz@ acquired the monitors in opposite order, possibly resulting in deadlock.
However, this case is the simplest instance of the \emph{nested-monitor problem}~\cite{Lister77}, where monitors are acquired in sequence versus bulk.
Detecting the nested-monitor problem requires dynamic tracking of monitor calls, and dealing with it requires rollback semantics~\cite{Dice10}.
\CFA does not deal with this fundamental problem.

Finally, like Java, \CFA offers an alternative @mutex@ statement to reduce refactoring and naming.
\begin{cquote}
\renewcommand{\arraystretch}{0.0}
\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
\multicolumn{1}{c}{\textbf{\lstinline@mutex@ call}} & \multicolumn{1}{c}{\lstinline@mutex@ \textbf{statement}} \\
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
monitor M { ... };
void foo( M & mutex m1, M & mutex m2 ) {
	// critical section
}
void bar( M & m1, M & m2 ) {
	foo( m1, m2 );
}
\end{cfa}
&
\begin{cfa}[aboveskip=0pt,belowskip=0pt]

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

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


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

% There are many aspects of scheduling in a concurrency system, all related to resource utilization by waiting threads, \ie which thread gets the resource next.
% Different forms of scheduling include access to processors by threads (see Section~\ref{s:RuntimeStructureCluster}), another is access to a shared resource by a lock or monitor.
This section discusses scheduling for waiting threads eligible for monitor entry~\cite{Buhr95b}, \ie which user thread gets the shared resource next. (See Section~\ref{s:RuntimeStructureCluster} for scheduling kernel threads on virtual processors.)
While monitor mutual-exclusion provides safe access to its shared data, the data may indicate a thread cannot proceed, \eg a bounded buffer may be full/\-empty so produce/consumer threads must block.
Leaving the monitor and retrying (busy waiting) is impractical for high-level programming.

Monitors eliminate busy waiting by providing synchronization within the monitor critical-section to schedule threads needing access to the shared data, where threads block versus spin.
Synchronization is generally achieved with internal~\cite{Hoare74} or external~\cite[\S~2.9.2]{uC++} scheduling.
\newterm{Internal} largely schedules threads located \emph{inside} the monitor and is accomplished using condition variables with signal and wait.
\newterm{External} largely schedules threads located \emph{outside} the monitor and is accomplished with the @waitfor@ statement.
Note, internal scheduling has a small amount of external scheduling and vice versa, so the naming denotes where the majority of the block threads reside (inside or outside) for scheduling.
For complex scheduling, the approaches can be combined, so there are threads waiting inside and outside.

\CFA monitors do not allow calling threads to barge ahead of signalled threads via barging prevention, which simplifies synchronization among threads in the monitor and increases correctness.
A direct consequence of this semantics is that unblocked waiting threads are not required to recheck the waiting condition, \ie waits are not in a starvation-prone busy-loop as required by the signals-as-hints style with barging.
Preventing barging comes directly from Hoare's semantics in the seminal paper on monitors~\cite[p.~550]{Hoare74}.
% \begin{cquote}
% However, we decree that a signal operation be followed immediately by resumption of a waiting program, without possibility of an intervening procedure call from yet a third program.
% It is only in this way that a waiting program has an absolute guarantee that it can acquire the resource just released by the signalling program without any danger that a third program will interpose a monitor entry and seize the resource instead.~\cite[p.~550]{Hoare74}
% \end{cquote}
Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implicit self barging.

Monitor mutual-exclusion means signalling cannot have the signaller and signalled thread in the monitor simultaneously, so only the signaller or signallee can proceed and the other waits on an implicit urgent list~\cite[p.~551]{Hoare74}.
Figure~\ref{f:MonitorScheduling} shows internal and external scheduling for the bounded-buffer examples in Figure~\ref{f:GenericBoundedBuffer}.
For internal scheduling in Figure~\ref{f:BBInt}, the @signal@ moves the signallee, front thread of the specified condition queue, to the urgent list (see Figure~\ref{f:MonitorScheduling}) and the signaller continues (solid line).
Multiple signals move multiple signallees to urgent until the condition queue is empty.
When the signaller exits or waits, a thread is implicitly unblocked from urgent, if available, before unblocking a calling thread to prevent barging.
(Java conceptually moves the signalled thread to the calling queue, and hence, allows barging.)
Signal is used when the signaller is providing the cooperation needed by the signallee, \eg creating an empty slot in a buffer for a producer, and the signaller immediately exits the monitor to run concurrently consuming the buffer element, and passes control of the monitor to the signalled thread, which can immediately take advantage of the state change.
Specifically, the @wait@ function atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the function's parameter list.
Signalling is unconditional because signalling an empty condition queue does nothing.
It is common to declare condition queues as monitor fields to prevent shared access, hence no locking is required for access as the queues are protected by the monitor lock.
In \CFA, a condition queue can be created and stored independently.

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

\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) & buf ) with(buf) {
		front = back = count = 0;
	}

	void insert(Buffer(T) & mutex buf, T elm) with(buf){
		if ( count == 10 ) `wait( empty )`; // full ?
		// insert elm into buf
		`signal( full )`;
	}
	T remove( Buffer(T) & mutex buf ) with(buf) {
		if ( count == 0 ) `wait( full )`; // empty ?
		// remove elm from buf
		`signal( empty )`;
		return elm;
	}
}
\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) & buf ) with(buf) {
		front = back = count = 0;
	}
	T remove( Buffer(T) & mutex buf ); // forward
	void insert(Buffer(T) & mutex buf, T elm) with(buf){
		if ( count == 10 ) `waitfor( remove : buf )`;
		// insert elm into buf

	}
	T remove( Buffer(T) & mutex buf ) with(buf) {
		if ( count == 0 ) `waitfor( insert : buf )`;
		// remove elm from buf

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

\subfloat[Internal scheduling]{\label{f:BBInt}\usebox\myboxA}
\hspace{1pt}
\vrule
\hspace{3pt}
\subfloat[External scheduling]{\label{f:BBExt}\usebox\myboxB}

\caption{Generic bounded buffer}
\label{f:GenericBoundedBuffer}
\end{figure}

The @signal_block@ provides the opposite unblocking order, where the signaller is moved to urgent and the signallee continues and a thread is implicitly unblocked from urgent when the signallee exits or waits (dashed line)~\cite[p.~551]{Hoare74}.
Signal block is used when the signallee is providing the cooperation needed by the signaller, \eg if the buffer is removed and a producer hands off an item to a consumer as in Figure~\ref{f:DatingSignalBlock}, so the signaller must wait until the signallee unblocks, provides the cooperation, exits the monitor to run concurrently, and passes control of the monitor to the signaller, which can immediately take advantage of the state change.
Using @signal@ or @signal_block@ can be a dynamic decision based on whether the thread providing the cooperation arrives before or after the thread needing the cooperation.

For external scheduling in Figure~\ref{f:BBExt}, the internal scheduling is replaced, eliminating condition queues and @signal@/@wait@ (cases where it cannot are discussed shortly), and has existed in the programming language Ada for almost 40 years with variants in other languages~\cite{SR,ConcurrentC++,uC++}.
While prior languages use external scheduling solely for thread interaction, \CFA generalizes it to both monitors and threads.
External scheduling allows waiting for events from other threads while restricting unrelated events, that would otherwise have to wait on condition queues in the monitor.
Scheduling is controlled by the @waitfor@ statement, which atomically blocks the calling thread, releases the monitor lock, and restricts the function calls that can next acquire mutual exclusion.
Specifically, a thread calling the monitor is unblocked directly from the calling queue based on function names that can fulfill the cooperation required by the signaller.
(The linear search through the calling queue to locate a particular call can be reduced to $O(1)$.)
Hence, the @waitfor@ has the same semantics as @signal_block@, where the signallee thread from the calling queue executes before the signaller, which waits on urgent.
Now when a producer/consumer detects a full/empty buffer, the necessary cooperation for continuation is specified by indicating the next function call that can occur.
For example, a producer detecting a full buffer must have cooperation from a consumer to remove an item so function @remove@ is accepted, which prevents producers from entering the monitor, and after a consumer calls @remove@, the producer waiting on urgent is \emph{implicitly} unblocked because it can now continue its insert operation.
Hence, this mechanism is done in terms of control flow, next call, versus in terms of data, channels, as in Go and Rust @select@.
While both mechanisms have strengths and weaknesses, \CFA uses the control-flow mechanism to be consistent with other language features.

Figure~\ref{f:ReadersWriterLock} shows internal and external scheduling for a readers/writer lock with no barging and threads are serviced in FIFO order to eliminate staleness and freshness among the reader/writer threads.
For internal scheduling in Figure~\ref{f:RWInt}, the readers and writers wait on the same condition queue in FIFO order, making it impossible to tell if a waiting thread is a reader or writer.
To clawback the kind of thread, a \CFA condition can store user data in the node for a blocking thread at the @wait@, \ie whether the thread is a @READER@ or @WRITER@.
An unblocked reader thread checks if the thread at the front of the queue is a reader and unblock it, \ie the readers daisy-chain signal the next group of readers demarcated by the next writer or end of the queue.
For external scheduling in Figure~\ref{f:RWExt}, a waiting reader checks if a writer is using the resource, and if so, restricts further calls until the writer exits by calling @EndWrite@.
The writer does a similar action for each reader or writer using the resource.
Note, no new calls to @StartRead@/@StartWrite@ may occur when waiting for the call to @EndRead@/@EndWrite@.

\begin{figure}
\centering
\newbox\myboxA
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
enum RW { READER, WRITER };
monitor ReadersWriter {
	int rcnt, wcnt;	// readers/writer using resource
	`condition RWers;`
};
void ?{}( ReadersWriter & rw ) with(rw) {
	rcnt = wcnt = 0;
}
void EndRead( ReadersWriter & mutex rw ) with(rw) {
	rcnt -= 1;
	if ( rcnt == 0 ) `signal( RWers )`;
}
void EndWrite( ReadersWriter & mutex rw ) with(rw) {
	wcnt = 0;
	`signal( RWers );`
}
void StartRead( ReadersWriter & mutex rw ) with(rw) {
	if ( wcnt !=0 || ! empty( RWers ) )
		`wait( RWers, READER )`;
	rcnt += 1;
	if ( ! empty(RWers) && `front(RWers) == READER` )
		`signal( RWers )`;  // daisy-chain signalling
}
void StartWrite( ReadersWriter & mutex rw ) with(rw) {
	if ( wcnt != 0 || rcnt != 0 ) `wait( RWers, WRITER )`;

	wcnt = 1;
}
\end{cfa}
\end{lrbox}

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

monitor ReadersWriter {
	int rcnt, wcnt; // readers/writer using resource

};
void ?{}( ReadersWriter & rw ) with(rw) {
	rcnt = wcnt = 0;
}
void EndRead( ReadersWriter & mutex rw ) with(rw) {
	rcnt -= 1;

}
void EndWrite( ReadersWriter & mutex rw ) with(rw) {
	wcnt = 0;

}
void StartRead( ReadersWriter & mutex rw ) with(rw) {
	if ( wcnt > 0 ) `waitfor( EndWrite : rw );`

	rcnt += 1;


}
void StartWrite( ReadersWriter & mutex rw ) with(rw) {
	if ( wcnt > 0 ) `waitfor( EndWrite : rw );`
	else while ( rcnt > 0 ) `waitfor( EndRead : rw );`
	wcnt = 1;
}
\end{cfa}
\end{lrbox}

\subfloat[Internal scheduling]{\label{f:RWInt}\usebox\myboxA}
\hspace{1pt}
\vrule
\hspace{3pt}
\subfloat[External scheduling]{\label{f:RWExt}\usebox\myboxB}

\caption{Readers / writer lock}
\label{f:ReadersWriterLock}
\end{figure}

Finally, external scheduling requires urgent to be a stack, because the signaller expects to execute immediately after the specified monitor call has exited or waited.
Internal schedulling performing multiple signalling results in unblocking from urgent in the reverse order from signalling.
It is rare for the unblocking order to be important as an unblocked thread can be time-sliced immediately after leaving the monitor.
If the unblocking order is important, multiple signalling can be restructured into daisy-chain signalling, where each thread signals the next thread.
Hence, \CFA uses a single urgent stack to correctly handle @waitfor@ and adequately support both forms of signalling.
(Advanced @waitfor@ features are discussed in Section~\ref{s:ExtendedWaitfor}.)

\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 ( empty( Boys[ccode] ) ) {
		wait( Girls[ccode] );
		GirlPhNo = phNo;
		`signal( exchange );`
	} else {
		GirlPhNo = phNo;
		`signal( Boys[ccode] );`
		`wait( exchange );`
	}
	return BoyPhNo;
}
int boy( DS & mutex ds, int phNo, int ccode ) {
	// as above with boy/girl interchanged
}
\end{cfa}
\end{lrbox}

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

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

};
int girl( DS & mutex ds, int phNo, int ccode ) {
	if ( 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 Monitor}
\label{f:DatingServiceMonitor}
\end{figure}

Figure~\ref{f:DatingServiceMonitor} 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 explicit @exchange@-condition and @signal_block@ puts the finding thread on the urgent stack and unblocks the matcher.
Note, barging corrupts the dating service during an exchange because a barger may also match and change the phone numbers, invalidating the previous exchange phone number.
This situation shows rechecking the waiting condition and waiting again (signals-as-hints) fails, requiring significant restructured to account for barging.

Given external and internal scheduling, what guidelines can a programmer use to select between them?
In general, external scheduling is easier to understand and code because only the next logical action (mutex function(s)) is stated, and the monitor implicitly handles all the details.
Therefore, there are no condition variables, and hence, no wait and signal, which reduces coding complexity and synchronization errors.
If external scheduling is simpler than internal, why not use it all the time?
Unfortunately, external scheduling cannot be used if: scheduling depends on parameter value(s) or scheduling must block across an unknown series of calls on a condition variable, \ie internal scheduling.
For example, the dating service cannot be written using external scheduling.
First, scheduling requires knowledge of calling parameters to make matching decisions and parameters of calling threads are unavailable within the monitor.
Specifically, a thread within the monitor cannot examine the @ccode@ of threads waiting on the calling queue to determine if there is a matching partner.
(Similarly, if the bounded buffer or readers/writer are restructured with a single interface function with a parameter denoting producer/consumer or reader/write, they cannot be solved with external scheduling.)
Second, a scheduling decision may be delayed across an unknown number of calls when there is no immediate match so the thread in the monitor must block on a condition.
Specifically, if a thread determines there is no opposite calling thread with the same @ccode@, it must wait an unknown period until a matching thread arrives.
For complex synchronization, both external and internal scheduling can be used to take advantage of best of properties of each.

Finally, both internal and external scheduling extend to multiple monitors in a natural way.
\begin{cquote}
\begin{tabular}{@{}l@{\hspace{2\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 ); // overload rtn
void rtn$\(_2\)$( M & mutex m1 );
void bar( M & mutex m1, M & mutex m2 ) {
	... waitfor( `rtn`${\color{red}\(_1\)}$ ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\) : m1, m2 )}$
	... waitfor( `rtn${\color{red}\(_2\)}$ : m1` ); ...
}
\end{cfa}
\end{tabular}
\end{cquote}
For @wait( e )@, the default semantics is to atomically block the signaller and release all acquired mutex parameters, \ie @wait( e, m1, m2 )@.
To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
Wait cannot statically verify the released monitors are the acquired mutex-parameters without disallowing separately compiled helper functions calling @wait@.
While \CC supports bulk locking, @wait@ only accepts a single lock for a condition queue, so bulk locking with condition queues is asymmetric.
Finally, a signaller,
\begin{cfa}
void baz( M & mutex m1, M & mutex m2 ) {
	... signal( e ); ...
}
\end{cfa}
must have acquired at least the same locks as the waiting thread signalled from a condition queue to allow the locks to be passed, and hence, prevent barging.

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

The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock (see Section~\ref{s:MutexAcquisition}).
\begin{cfa}
void foo( M & mutex m1, M & mutex m2 ) {
	... wait( `e, m1` ); ...				$\C{// release m1, keeping m2 acquired}$
void bar( M & mutex m1, M & mutex m2 ) {	$\C{// must acquire m1 and m2}$
	... signal( `e` ); ...
\end{cfa}
The @wait@ only releases @m1@ so the signalling thread cannot acquire @m1@ and @m2@ to enter @bar@ and @signal@ the condition.
While deadlock can occur with multiple/nesting acquisition, this is a consequence of locks, and by extension monitor locking is not perfectly composable.


\subsection{\texorpdfstring{Extended \protect\lstinline@waitfor@}{Extended waitfor}}
\label{s:ExtendedWaitfor}

Figure~\ref{f:ExtendedWaitfor} shows the extended form of the @waitfor@ statement to conditionally accept one of a group of mutex functions, with an optional statement to be performed \emph{after} the mutex function finishes.
For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding function(s) must exist.
The \emph{conditional-expression} of a @when@ may call a function, but the function must not block or context switch.
If there are multiple acceptable mutex calls, selection is prioritized top-to-bottom among the @waitfor@ clauses, whereas some programming languages with similar mechanisms accept nondeterministically for this case, \eg Go \lstinline[morekeywords=select]@select@.
If some accept guards are true and there are no outstanding calls to these functions, the acceptor is blocked until a call to one of these functions is made.
If there is a @timeout@ clause, it provides an upper bound on waiting.
If all the accept guards are false, the statement does nothing, unless there is a terminating @else@ clause with a true guard, which is executed instead.
Hence, the terminating @else@ clause allows a conditional attempt to accept a call without blocking.
If both @timeout@ and @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered.
% There is also a traditional future wait queue (not shown) (\eg Microsoft @WaitForMultipleObjects@), to wait for a specified number of future elements in the queue.
Finally, there is a shorthand for specifying multiple functions using the same set of monitors: @waitfor( f, g, h : m1, m2, m3 )@.

\begin{figure}
\centering
\begin{cfa}
`when` ( $\emph{conditional-expression}$ )	$\C{// optional guard}$
	waitfor( $\emph{mutex-function-name}$ ) $\emph{statement}$ $\C{// action after call}$
`or` `when` ( $\emph{conditional-expression}$ ) $\C{// any number of functions}$
	waitfor( $\emph{mutex-function-name}$ ) $\emph{statement}$
`or`	...
`when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
	`timeout` $\emph{statement}$ $\C{// optional terminating timeout clause}$
`when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
	`else`  $\emph{statement}$ $\C{// optional terminating clause}$
\end{cfa}
\caption{Extended \protect\lstinline@waitfor@}
\label{f:ExtendedWaitfor}
\end{figure}

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

An interesting use of @waitfor@ is accepting the @mutex@ destructor to know when an object is deallocated, \eg assume the bounded buffer is restructured from a monitor to a thread with the following @main@.
\begin{cfa}
void main( Buffer(T) & buffer ) with(buffer) {
	for () {
		`waitfor( ^?{} : buffer )` break;
		or when ( count != 20 ) waitfor( insert : buffer ) { ... }
		or when ( count != 0 ) waitfor( remove : buffer ) { ... }
	}
	// clean up
}
\end{cfa}
When the program main deallocates the buffer, it first calls the buffer's destructor, which is accepted, the destructor runs, and the buffer is deallocated.
However, the buffer thread cannot continue after the destructor call because the object is gone;
hence, clean up in @main@ cannot occur, which means destructors for local objects are not run.
To make this useful capability work, the semantics for accepting the destructor is the same as @signal@, \ie the destructor call is placed on urgent and the acceptor continues execution, which ends the loop, cleans up, and the thread terminates.
Then, the destructor caller unblocks from urgent to deallocate the object.
Accepting the destructor is the idiomatic way in \CFA to terminate a thread performing direct communication.


\subsection{Bulk Barging Prevention}

Figure~\ref{f:BulkBargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signalling semantics.
The complexity begins at the end of the inner @mutex@ statement, where the semantics of internal scheduling need to be extended for multiple monitors.
The problem is that bulk acquire is used in the inner @mutex@ statement where one of the monitors is already acquired.
When the signalling thread reaches the end of the inner @mutex@ statement, it should transfer ownership of @m1@ and @m2@ to the waiting threads to prevent barging into the outer @mutex@ statement by another thread.
However, both the signalling and waiting threads W1 and W2 need some subset of monitors @m1@ and @m2@.
\begin{cquote}
condition c: (order 1) W2(@m2@), W1(@m1@,@m2@)\ \ \ or\ \ \ (order 2) W1(@m1@,@m2@), W2(@m2@) \\
S: acq. @m1@ $\rightarrow$ acq. @m1,m2@ $\rightarrow$ @signal(c)@ $\rightarrow$ rel. @m2@ $\rightarrow$ pass @m2@ unblock W2 (order 2) $\rightarrow$ rel. @m1@ $\rightarrow$ pass @m1,m2@ unblock W1 \\
\hspace*{2.75in}$\rightarrow$ rel. @m1@ $\rightarrow$ pass @m1,m2@ unblock W1 (order 1)
\end{cquote}

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

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


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

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


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




\end{cfa}
\end{lrbox}

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

One scheduling solution is for the signaller S to keep ownership of all locks until the last lock is ready to be transferred, because this semantics fits most closely to the behaviour of single-monitor scheduling.
However, this solution is inefficient if W2 waited first and immediate passed @m2@ when released, while S retains @m1@ until completion of the outer mutex statement.
If W1 waited first, the signaller must retain @m1@ amd @m2@ until completion of the outer mutex statement and then pass both to W1.
% Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
To support these efficient semantics and prevent barging, the implementation maintains a list of monitors acquired for each blocked thread.
When a signaller exits or waits in a mutex function or statement, the front waiter on urgent is unblocked if all its monitors are released.
Implementing a fast subset check for the necessarily released monitors is important and discussed in the following sections.
% 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{\texorpdfstring{\protect\lstinline@waitfor@ Implementation}{waitfor Implementation}}
\label{s:waitforImplementation}

In a statically-typed object-oriented programming language, a class has an exhaustive list of members, even when members are added via static inheritance (see Figure~\ref{f:uCinheritance}).
Knowing all members at compilation, even separate compilation, allows uniquely numbered them so the accept-statement implementation can use a fast and compact bit mask with $O(1)$ compare.

\begin{figure}
\centering
\begin{lrbox}{\myboxA}
\begin{uC++}[aboveskip=0pt,belowskip=0pt]
$\emph{translation unit 1}$
_Monitor B { // common type in .h file
	_Mutex virtual void `f`( ... );
	_Mutex virtual void `g`( ... );
	_Mutex virtual void w1( ... ) { ... _Accept(`f`, `g`); ... }
};
$\emph{translation unit 2}$
// include B
_Monitor D : public B { // inherit
	_Mutex void `h`( ... ); // add
	_Mutex void w2( ... ) { ... _Accept(`f`, `h`); ... }
};
\end{uC++}
\end{lrbox}

\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
$\emph{translation unit 1}$
monitor M { ... }; // common type in .h file
void `f`( M & mutex m, ... );
void `g`( M & mutex m, ... );
void w1( M & mutex m, ... ) { ... waitfor(`f`, `g` : m); ... }

$\emph{translation unit 2}$
// include M
extern void `f`( M & mutex m, ... ); // import f but not g
void `h`( M & mutex m ); // add
void w2( M & mutex m, ... ) { ... waitfor(`f`, `h` : m); ... }

\end{cfa}
\end{lrbox}

\subfloat[\uC]{\label{f:uCinheritance}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[\CFA]{\label{f:CFinheritance}\usebox\myboxB}
\caption{Member / Function visibility}
\label{f:MemberFunctionVisibility}
\end{figure}

However, the @waitfor@ statement in translation unit 2 (see Figure~\ref{f:CFinheritance}) cannot see function @g@ in translation unit 1 precluding a unique numbering for a bit-mask because the monitor type only carries the protected shared-data.
(A possible way to construct a dense mapping is at link or load-time.)
Hence, function pointers are used to identify the functions listed in the @waitfor@ statement, stored in a variable-sized array.
Then, the same implementation approach used for the urgent stack (see Section~\ref{s:Scheduling}) is used for the calling queue.
Each caller has a list of monitors acquired, and the @waitfor@ statement performs a short linear search matching functions in the @waitfor@ list with called functions, and then verifying the associated mutex locks can be transferred.


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

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

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

\begin{figure}
\centering
\begin{lrbox}{\myboxA}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
monitor M1 {} m11, m12;
monitor M2 {} m2;
condition c;
void f( M1 & mutex m1, M2 & mutex m2 ) {
	signal( c );
}
void g( M1 & mutex m1, M2 & mutex m2 ) {
	wait( c );
}
g( `m11`, m2 ); // block on wait
f( `m12`, m2 ); // cannot fulfil
\end{cfa}
\end{lrbox}

\begin{lrbox}{\myboxB}
\begin{cfa}[aboveskip=0pt,belowskip=0pt]
monitor M1 {} m11, m12;
monitor M2 {} m2;

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

}
void g( M1 & mutex m1, M2 & mutex m2 ) {
	waitfor( f : m1, m2 );
}
g( `m11`, m2 ); // block on accept
f( `m12`, m2 ); // cannot fulfil
\end{cfa}
\end{lrbox}
\subfloat[Internal scheduling]{\label{f:InternalScheduling}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[External scheduling]{\label{f:ExternalScheduling}\usebox\myboxB}
\caption{Unmatched \protect\lstinline@mutex@ sets}
\label{f:UnmatchedMutexSets}
\end{figure}

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

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

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

	for () {

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

	}

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


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

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

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

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

\subfloat[\CFA]{\label{f:CFAwaitfor}\usebox\myboxA}
\hspace{3pt}
\vrule
\hspace{3pt}
\subfloat[Go]{\label{f:Gochannel}\usebox\myboxB}
\caption{Direct versus indirect communication}
\label{f:DirectCommunicationComparison}

\medskip

\begin{cfa}
mutex thread DatingService {
	condition Girls[CompCodes], Boys[CompCodes];
	int girlPhoneNo, boyPhoneNo, ccode;
};
int girl( DatingService & mutex ds, int phoneno, int code ) with( ds ) {
	girlPhoneNo = phoneno;  ccode = code;
	`wait( Girls[ccode] );`								$\C{// wait for boy}$
	girlPhoneNo = phoneno;  return boyPhoneNo;
}
int boy( DatingService & mutex ds, int phoneno, int code ) with( ds ) {
	boyPhoneNo = phoneno;  ccode = code;
	`wait( Boys[ccode] );`								$\C{// wait for girl}$
	boyPhoneNo = phoneno;  return girlPhoneNo;
}
void main( DatingService & ds ) with( ds ) {			$\C{// thread starts, ds defaults to mutex}$
	for () {
		waitfor( ^?{} ) break;							$\C{// high priority}$
		or waitfor( girl )								$\C{// girl called, compatible boy ? restart boy then girl}$
			if ( ! is_empty( Boys[ccode] ) ) { `signal_block( Boys[ccode] );  signal_block( Girls[ccode] );` }
		or waitfor( boy ) {								$\C{// boy called, compatible girl ? restart girl then boy}$
			if ( ! is_empty( Girls[ccode] ) ) { `signal_block( Girls[ccode] );  signal_block( Boys[ccode] );` }
	}
}
\end{cfa}
\caption{Direct communication dating service}
\label{f:DirectCommunicationDatingService}
\end{figure}

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

\end{cfa}
\end{tabular}
\end{cquote}
% \lstMakeShortInline@%
% \caption{Threads ping/pong using external scheduling}
% \label{f:pingpong}
% \end{figure}
Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start and possibly complete before the program main starts.
\end{comment}


\subsection{\texorpdfstring{\protect\lstinline@mutex@ Generators / Coroutines / Threads}{monitor Generators / Coroutines / Threads}}

\CFA generators, coroutines, and threads can also be @mutex@ (Table~\ref{t:ExecutionPropertyComposition} cases 4, 6, 12) allowing safe \emph{direct communication} with threads, \ie the custom types can have mutex functions that are called by other threads.
All monitor features are available within these mutex functions.
For example, if the formatter generator or coroutine equivalent in Figure~\ref{f:CFAFormatGen} is extended with the monitor property and this interface function is used to communicate with the formatter:
\begin{cfa}
void fmt( Fmt & mutex fmt, char ch ) { fmt.ch = ch; resume( fmt ) }
\end{cfa}
multiple threads can safely pass characters for formatting.

Figure~\ref{f:DirectCommunicationComparison} shows a comparison of direct call-communication in \CFA versus indirect channel-communication in Go.
(Ada has a similar mechanism to \CFA direct communication.)
% The thread main function is by default @mutex@, so the @mutex@ qualifier for the thread parameter is optional.
% The reason is that the thread logically starts instantaneously in the thread main acquiring its mutual exclusion, so it starts before any calls to prepare for synchronizing these calls.
The \CFA program @main@ uses the call/return paradigm to directly communicate with the @GoRtn main@, whereas Go switches to the unbuffered channel paradigm to indirectly communicate with the goroutine.
Communication by multiple threads is safe for the @gortn@ thread via mutex calls in \CFA or channel assignment in Go.
The difference between call and channel send occurs for buffered channels making the send asynchronous.
In \CFA, asynchronous call and multiple buffers are provided using an administrator and worker threads~\cite{Gentleman81} and/or futures (not discussed).

Figure~\ref{f:DirectCommunicationDatingService} shows the dating-service problem in Figure~\ref{f:DatingServiceMonitor} extended from indirect monitor communication to direct thread communication.
When converting a monitor to a thread (server), the coding pattern is to move as much code as possible from the accepted functions into the thread main so it does as much work as possible.
Notice, the dating server is postponing requests for an unspecified time while continuing to accept new requests.
For complex servers, \eg web-servers, there can be hundreds of lines of code in the thread main and safe interaction with clients can be complex.


\subsection{Low-level Locks}

For completeness and efficiency, \CFA provides a standard set of low-level locks: recursive mutex, condition, semaphore, barrier, \etc, and atomic instructions: @fetchAssign@, @fetchAdd@, @testSet@, @compareSet@, \etc.
Some of these low-level mechanisms are used to build the \CFA runtime, but we always advocate using high-level mechanisms whenever possible.


% \section{Parallelism}
% \label{s:Parallelism}
%
% Historically, computer performance was about processor speeds.
% However, with heat dissipation being a direct consequence of speed increase, parallelism is the new source for increased performance~\cite{Sutter05, Sutter05b}.
% Therefore, high-performance applications must care about parallelism, which requires concurrency.
% The lowest-level approach of parallelism is to use \newterm{kernel threads} in combination with semantics like @fork@, @join@, \etc.
% However, kernel threads are better as an implementation tool because of complexity and higher cost.
% Therefore, different abstractions are often layered onto kernel threads to simplify them, \eg pthreads.
%
%
% \subsection{User Threads}
%
% A direct improvement on kernel threads is user threads, \eg Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
% This approach provides an interface that matches the language paradigms, gives more control over concurrency by the language runtime, and an abstract (and portable) interface to the underlying kernel threads across operating systems.
% In many cases, user threads can be used on a much larger scale (100,000 threads).
% Like kernel threads, user threads support preemption, which maximizes nondeterminism, but increases the potential for concurrency errors: race, livelock, starvation, and deadlock.
% \CFA adopts user-threads to provide more flexibility and a low-cost mechanism to build any other concurrency approach, \eg thread pools and actors~\cite{Actors}.
%
% A variant of user thread is \newterm{fibres}, which removes preemption, \eg Go~\cite{Go} @goroutine@s.
% Like functional programming, which removes mutation and its associated problems, removing preemption from concurrency reduces nondeterminism, making race and deadlock errors more difficult to generate.
% However, preemption is necessary for fairness and to reduce tail-latency.
% For concurrency that relies on spinning, if all cores spin the system is livelocked, whereas preemption breaks the livelock.


\begin{comment}
\subsection{Thread Pools}

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

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




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


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

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

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


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

A \newterm{cluster} is a collection of user and kernel threads, where the kernel threads run the user threads from the cluster's ready queue, and the operating system runs the kernel threads on the processors from its ready queue~\cite{Buhr90a}.
The term \newterm{virtual processor} is introduced as a synonym for kernel thread to disambiguate between user and kernel thread.
From the language perspective, a virtual processor is an actual processor (core).

The purpose of a cluster is to control the amount of parallelism that is possible among threads, plus scheduling and other execution defaults.
The default cluster-scheduler is single-queue multi-server, which provides automatic load-balancing of threads on processors.
However, the design allows changing the scheduler, \eg multi-queue multi-server with work-stealing/sharing across the virtual processors.
If several clusters exist, both threads and virtual processors, can be explicitly migrated from one cluster to another.
No automatic load balancing among clusters is performed by \CFA.

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


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

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


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

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

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

To improve performance and simplicity, context switching occurs inside a function call, so only callee-saved registers are copied onto the stack and then the stack register is switched;
the corresponding registers are then restored for the other context.
Note, the instruction pointer is untouched since the context switch is always inside the same function.
Experimental results (not presented) for a stackless or stackful scheduler (1 versus 2 context switches) (see Section~\ref{s:Concurrency}) show the performance is virtually equivalent, because both approaches are dominated by locking to prevent a race condition.

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


\subsection{Preemption}

Nondeterministic preemption provides fairness from long-running threads, and forces concurrent programmers to write more robust programs, rather than relying on code between cooperative scheduling to be atomic.
This atomic reliance can fail on multi-core machines, because execution across cores is nondeterministic.
A different reason for not supporting preemption is that it significantly complicates the runtime system, \eg Windows runtime does not support interrupts and on Linux systems, interrupts are complex (see below).
Preemption is normally handled by setting a countdown timer on each virtual processor.
When the timer expires, an interrupt is delivered, and its signal handler resets the countdown timer, and if the virtual processor is executing in user code, the signal handler performs a user-level context-switch, or if executing in the language runtime kernel, the preemption is ignored or rolled forward to the point where the runtime kernel context switches back to user code.
Multiple signal handlers may be pending.
When control eventually switches back to the signal handler, it returns normally, and execution continues in the interrupted user thread, even though the return from the signal handler may be on a different kernel thread than the one where the signal is delivered.
The only issue with this approach is that signal masks from one kernel thread may be restored on another as part of returning from the signal handler;
therefore, the same signal mask is required for all virtual processors in a cluster.
Because preemption interval is usually long (1 millisecond) performance cost is negligible.

Linux switched a decade ago from specific to arbitrary virtual-processor signal-delivery for applications with multiple kernel threads.
In the new semantics, a virtual-processor directed signal may be delivered to any virtual processor created by the application that does not have the signal blocked.
Hence, the timer-expiry signal, which is generated \emph{externally} by the Linux kernel to an application, is delivered to any of its Linux subprocesses (kernel threads).
To ensure each virtual processor receives a preemption signal, a discrete-event simulation is run on a special virtual processor, and only it sets and receives timer events.
Virtual processors register an expiration time with the discrete-event simulator, which is inserted in sorted order.
The simulation sets the countdown timer to the value at the head of the event list, and when the timer expires, all events less than or equal to the current time are processed.
Processing a preemption event sends an \emph{internal} @SIGUSR1@ signal to the registered virtual processor, which is always delivered to that processor.


\subsection{Debug Kernel}

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


\section{Performance}
\label{s:Performance}

To test the performance of the \CFA runtime, a series of microbenchmarks are used to compare \CFA with pthreads, Java 11.0.6, Go 1.12.6, Rust 1.37.0, Python 3.7.6, Node.js 12.14.1, and \uC 7.0.0.
For comparison, the package must be multi-processor (M:N), which excludes libdil and libmil~\cite{libdill} (M:1)), and use a shared-memory programming model, \eg not message passing.
The benchmark computer is an AMD Opteron\texttrademark\ 6380 NUMA 64-core, 8 socket, 2.5 GHz processor, running Ubuntu 16.04.6 LTS, and pthreads/\CFA/\uC are compiled with gcc 9.2.1.

All benchmarks are run using the following harness. (The Java harness is augmented to circumvent JIT issues.)
\begin{cfa}
#define BENCH( `run` ) uint64_t start = cputime_ns();  `run;`  double result = (double)(cputime_ns() - start) / N;
\end{cfa}
where CPU time in nanoseconds is from the appropriate language clock.
Each benchmark is performed @N@ times, where @N@ is selected so the benchmark runs in the range of 2--20 seconds for the specific programming language;
each @N@ appears after the experiment name in the following tables.
The total time is divided by @N@ to obtain the average time for a benchmark.
Each benchmark experiment is run 13 times and the average appears in the table.
For languages with a runtime JIT (Java, Node.js, Python), a single half-hour long experiment is run to check stability;
all long-experiment results are statistically equivalent, \ie median/average/standard-deviation correlate with the short-experiment results, indicating the short experiments reached a steady state.
All omitted tests for other languages are functionally identical to the \CFA tests and available online~\cite{CforallConcurrentBenchmarks}.

\paragraph{Creation}

Creation is measured by creating and deleting a specific kind of control-flow object.
Figure~\ref{f:creation} shows the code for \CFA with results in Table~\ref{t:creation}.
Note, the call stacks of \CFA coroutines are lazily created on the first resume, therefore the cost of creation with and without a stack are presented.

\begin{multicols}{2}
\begin{cfa}[xleftmargin=0pt]
`coroutine` MyCoroutine {};
void ?{}( MyCoroutine & this ) {
#ifdef EAGER
	resume( this );
#endif
}
void main( MyCoroutine & ) {}
int main() {
	BENCH( for ( N ) { `MyCoroutine c;` } )
	sout | result;
}
\end{cfa}
\captionof{figure}{\CFA creation benchmark}
\label{f:creation}

\columnbreak

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

\begin{tabular}[t]{@{}r*{3}{D{.}{.}{5.2}}@{}}
\multicolumn{1}{@{}r}{N\hspace*{10pt}} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
\CFA generator (1B)			& 0.6		& 0.6		& 0.0		\\
\CFA coroutine lazy	(100M)	& 13.4		& 13.1		& 0.5		\\
\CFA coroutine eager (10M)	& 144.7		& 143.9		& 1.5		\\
\CFA thread (10M)			& 466.4		& 468.0		& 11.3		\\
\uC coroutine (10M)			& 155.6		& 155.7		& 1.7		\\
\uC thread (10M)			& 523.4		& 523.9		& 7.7		\\
Python generator (10M)		& 123.2		& 124.3		& 4.1		\\
Node.js generator (10M)		& 33.4		& 33.5		& 0.3		\\
Goroutine thread (10M)		& 751.0		& 750.5		& 3.1		\\
Rust tokio thread (10M)		& 1860.0	& 1881.1	& 37.6		\\
Rust thread	(250K)			& 53801.0	& 53896.8	& 274.9		\\
Java thread (250K)			& 119256.0	& 119679.2	& 2244.0	\\
% Java thread (1 000 000)		& 123100.0	& 123052.5	& 751.6 	\\
Pthreads thread	(250K)		& 31465.5	& 31419.5	& 140.4
\end{tabular}
\end{multicols}

\vspace*{-10pt}
\paragraph{Internal Scheduling}

Internal scheduling is measured using a cycle of two threads signalling and waiting.
Figure~\ref{f:schedint} shows the code for \CFA, with results in Table~\ref{t:schedint}.
Note, the \CFA incremental cost for bulk acquire is a fixed cost for small numbers of mutex objects.
User-level threading has one kernel thread, eliminating contention between the threads (direct handoff of the kernel thread).
Kernel-level threading has two kernel threads allowing some contention.

\begin{multicols}{2}
\setlength{\tabcolsep}{3pt}
\begin{cfa}[xleftmargin=0pt]
volatile int go = 0;
`condition c;`
`monitor` M {} m1/*, m2, m3, m4*/;
void call( M & `mutex p1/*, p2, p3, p4*/` ) {
	`signal( c );`
}
void wait( M & `mutex p1/*, p2, p3, p4*/` ) {
	go = 1;	// continue other thread
	for ( N ) { `wait( c );` } );
}
thread T {};
void main( T & ) {
	while ( go == 0 ) { yield(); } // waiter must start first
	BENCH( for ( N ) { call( m1/*, m2, m3, m4*/ ); } )
	sout | result;
}
int main() {
	T t;
	wait( m1/*, m2, m3, m4*/ );
}
\end{cfa}
\vspace*{-8pt}
\captionof{figure}{\CFA Internal-scheduling benchmark}
\label{f:schedint}

\columnbreak

\vspace*{-16pt}
\captionof{table}{Internal-scheduling comparison (nanoseconds)}
\label{t:schedint}
\bigskip

\begin{tabular}{@{}r*{3}{D{.}{.}{5.2}}@{}}
\multicolumn{1}{@{}r}{N\hspace*{10pt}} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
\CFA @signal@, 1 monitor (10M)	& 364.4		& 364.2		& 4.4		\\
\CFA @signal@, 2 monitor (10M)	& 484.4		& 483.9		& 8.8		\\
\CFA @signal@, 4 monitor (10M)	& 709.1		& 707.7		& 15.0		\\
\uC @signal@ monitor (10M)		& 328.3		& 327.4		& 2.4		\\
Rust cond. variable	(1M)		& 7514.0	& 7437.4	& 397.2		\\
Java @notify@ monitor (1M)		& 8717.0	& 8774.1	& 471.8		\\
% Java @notify@ monitor (100 000 000)		& 8634.0	& 8683.5	& 330.5		\\
Pthreads cond. variable (1M)	& 5553.7	& 5576.1	& 345.6
\end{tabular}
\end{multicols}


\paragraph{External Scheduling}

External scheduling is measured using a cycle of two threads calling and accepting the call using the @waitfor@ statement.
Figure~\ref{f:schedext} shows the code for \CFA with results in Table~\ref{t:schedext}.
Note, the \CFA incremental cost for bulk acquire is a fixed cost for small numbers of mutex objects.

\begin{multicols}{2}
\setlength{\tabcolsep}{5pt}
\vspace*{-16pt}
\begin{cfa}[xleftmargin=0pt]
`monitor` M {} m1/*, m2, m3, m4*/;
void call( M & `mutex p1/*, p2, p3, p4*/` ) {}
void wait( M & `mutex p1/*, p2, p3, p4*/` ) {
	for ( N ) { `waitfor( call : p1/*, p2, p3, p4*/ );` }
}
thread T {};
void main( T & ) {
	BENCH( for ( N ) { call( m1/*, m2, m3, m4*/ ); } )
	sout | result;
}
int main() {
	T t;
	wait( m1/*, m2, m3, m4*/ );
}
\end{cfa}
\captionof{figure}{\CFA external-scheduling benchmark}
\label{f:schedext}

\columnbreak

\vspace*{-18pt}
\captionof{table}{External-scheduling comparison (nanoseconds)}
\label{t:schedext}
\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
\multicolumn{1}{@{}r}{N\hspace*{10pt}} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
\CFA @waitfor@, 1 monitor (10M)	& 367.1	& 365.3	& 5.0	\\
\CFA @waitfor@, 2 monitor (10M)	& 463.0	& 464.6	& 7.1	\\
\CFA @waitfor@, 4 monitor (10M)	& 689.6	& 696.2	& 21.5	\\
\uC \lstinline[language=uC++]|_Accept| monitor (10M)	& 328.2	& 329.1	& 3.4	\\
Go \lstinline[language=Golang]|select| channel (10M)	& 365.0	& 365.5	& 1.2
\end{tabular}
\end{multicols}

\paragraph{Mutual-Exclusion}

Uncontented mutual exclusion, which frequently occurs, is measured by entering and leaving a critical section.
For monitors, entering and leaving a mutex function is measured, otherwise the language-appropriate mutex-lock is measured.
For comparison, a spinning (versus blocking) test-and-test-set lock is presented.
Figure~\ref{f:mutex} shows the code for \CFA with results in Table~\ref{t:mutex}.
Note the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.

\begin{multicols}{2}
\setlength{\tabcolsep}{3pt}
\begin{cfa}[xleftmargin=0pt]
`monitor` M {} m1/*, m2, m3, m4*/;
call( M & `mutex p1/*, p2, p3, p4*/` ) {}
int main() {
	BENCH( for( N ) call( m1/*, m2, m3, m4*/ ); )
	sout | result;
}
\end{cfa}
\captionof{figure}{\CFA acquire/release mutex benchmark}
\label{f:mutex}

\columnbreak

\vspace*{-16pt}
\captionof{table}{Mutex comparison (nanoseconds)}
\label{t:mutex}
\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
\multicolumn{1}{@{}r}{N\hspace*{10pt}} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
test-and-test-set lock (50M)		& 19.1	& 18.9	& 0.4	\\
\CFA @mutex@ function, 1 arg. (50M)	& 48.3	& 47.8	& 0.9	\\
\CFA @mutex@ function, 2 arg. (50M)	& 86.7	& 87.6	& 1.9	\\
\CFA @mutex@ function, 4 arg. (50M)	& 173.4	& 169.4	& 5.9	\\
\uC @monitor@ member rtn. (50M)		& 54.8	& 54.8	& 0.1	\\
Goroutine mutex lock (50M)			& 34.0	& 34.0	& 0.0	\\
Rust mutex lock (50M)				& 33.0	& 33.2	& 0.8	\\
Java synchronized method (50M)		& 31.0	& 30.9	& 0.5	\\
% Java synchronized method (10 000 000 000)		& 31.0 & 30.2 & 0.9 \\
Pthreads mutex Lock (50M)			& 31.0	& 31.1	& 0.4
\end{tabular}
\end{multicols}

\paragraph{Context Switching}

In procedural programming, the cost of a function call is important as modularization (refactoring) increases.
(In many cases, a compiler inlines function calls to increase the size and number of basic blocks for optimizing.)
Similarly, when modularization extends to coroutines and threads, the time for a context switch becomes a relevant factor.
The coroutine test is from resumer to suspender and from suspender to resumer, which is two context switches.
%For async-await systems, the test is scheduling and fulfilling @N@ empty promises, where all promises are allocated before versus interleaved with fulfillment to avoid garbage collection.
For async-await systems, the test measures the cost of the @await@ expression entering the event engine by awaiting @N@ promises, where each created promise is resolved by an immediate event in the engine (using Node.js @setImmediate@).
The thread test is using yield to enter and return from the runtime kernel, which is two context switches.
The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling.
Figure~\ref{f:ctx-switch} shows the \CFA code for a coroutine and thread with results in Table~\ref{t:ctx-switch}.

% From: Gregor Richards <gregor.richards@uwaterloo.ca>
% To: "Peter A. Buhr" <pabuhr@plg2.cs.uwaterloo.ca>
% Date: Fri, 24 Jan 2020 13:49:18 -0500
%
% I can also verify that the previous version, which just tied a bunch of promises together, *does not* go back to the
% event loop at all in the current version of Node. Presumably they're taking advantage of the fact that the ordering of
% events is intentionally undefined to just jump right to the next 'then' in the chain, bypassing event queueing
% entirely. That's perfectly correct behavior insofar as its difference from the specified behavior isn't observable, but
% it isn't typical or representative of much anything useful, because most programs wouldn't have whole chains of eager
% promises. Also, it's not representative of *anything* you can do with async/await, as there's no way to encode such an
% eager chain that way.

\begin{multicols}{2}
\begin{cfa}[xleftmargin=0pt]
`coroutine` C {};
void main( C & ) { for () { `suspend;` } }
int main() { // coroutine test
	C c;
	BENCH( for ( N ) { `resume( c );` } )
	sout | result;
}
int main() { // thread test
	BENCH( for ( N ) { `yield();` } )
	sout | result;
}
\end{cfa}
\captionof{figure}{\CFA context-switch benchmark}
\label{f:ctx-switch}

\columnbreak

\vspace*{-16pt}
\captionof{table}{Context switch comparison (nanoseconds)}
\label{t:ctx-switch}
\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
\multicolumn{1}{@{}r}{N\hspace*{10pt}} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
C function (10B)			& 1.8		& 1.8		& 0.0	\\
\CFA generator (5B)			& 1.8		& 2.0		& 0.3	\\
\CFA coroutine (100M)		& 32.5		& 32.9		& 0.8	\\
\CFA thread (100M)			& 93.8		& 93.6		& 2.2	\\
\uC coroutine (100M)		& 50.3		& 50.3		& 0.2	\\
\uC thread (100M)			& 97.3		& 97.4		& 1.0	\\
Python generator (100M)		& 40.9		& 41.3		& 1.5	\\
Node.js await (5M)			& 1852.2	& 1854.7	& 16.4	\\
Node.js generator (100M)	& 33.3		& 33.4		& 0.3	\\
Goroutine thread (100M)		& 143.0		& 143.3		& 1.1	\\
Rust async await (100M)		& 32.0		& 32.0		& 0.0	\\
Rust tokio thread (100M)	& 143.0		& 143.0		& 1.7	\\
Rust thread (25M)			& 332.0		& 331.4		& 2.4	\\
Java thread (100M)			& 405.0		& 415.0		& 17.6	\\
% Java thread (  100 000 000)			& 413.0 & 414.2 & 6.2 \\
% Java thread (5 000 000 000)			& 415.0 & 415.2 & 6.1 \\
Pthreads thread (25M)		& 334.3		& 335.2		& 3.9
\end{tabular}
\end{multicols}


\subsection{Discussion}

Languages using 1:1 threading based on pthreads can at best meet or exceed, due to language overhead, the pthread results.
Note, pthreads has a fast zero-contention mutex lock checked in user space.
Languages with M:N threading have better performance than 1:1 because there is no operating-system interactions (context-switching or locking).
As well, for locking experiments, M:N threading has less contention if only one kernel thread is used.
Languages with stackful coroutines have higher cost than stackless coroutines because of stack allocation and context switching;
however, stackful \uC and \CFA coroutines have approximately the same performance as stackless Python and Node.js generators.
The \CFA stackless generator is approximately 25 times faster for suspend/resume and 200 times faster for creation than stackless Python and Node.js generators.
The Node.js context-switch is costly when asynchronous await must enter the event engine because a promise is not fulfilled.
Finally, the benchmark results correlate across programming languages with and without JIT, indicating the JIT has completed any runtime optimizations.


\section{Conclusions and Future Work}

Advanced control-flow will always be difficult, especially when there is temporal ordering and nondeterminism.
However, many systems exacerbate the difficulty through their presentation mechanisms.
This paper shows it is possible to understand high-level control-flow using three properties: statefulness, thread, mutual-exclusion/synchronization.
Combining these properties creates a number of high-level, efficient, and maintainable control-flow types: generator, coroutine, thread, each of which can be a monitor.
Eliminated from \CFA are barging and spurious wakeup, which are nonintuitive and lead to errors, and having to work with a bewildering set of low-level locks and acquisition techniques.
\CFA high-level race-free monitors and threads, when used with mutex access function, provide the core mechanisms for mutual exclusion and synchronization, without having to resort to magic qualifiers like @volatile@ or @atomic@.
Extending these mechanisms to handle high-level deadlock-free bulk acquire across both mutual exclusion and synchronization is a unique contribution.
The \CFA runtime provides concurrency based on a preemptive M:N user-level threading-system, executing in clusters, which encapsulate scheduling of work on multiple kernel threads providing parallelism.
The M:N model is judged to be efficient and provide greater flexibility than a 1:1 threading model.
These concepts and the \CFA runtime-system are written in the \CFA language, extensively leveraging the \CFA type-system, which demonstrates the expressiveness of the \CFA language.
Performance comparisons with other concurrent systems and languages show the \CFA approach is competitive across all basic operations, which translates directly into good performance in well-written applications with advanced control-flow.
C programmers should feel comfortable using these mechanisms for developing complex control-flow in applications, with the ability to obtain maximum available performance by selecting mechanisms at the appropriate level of need using only calling communication.

While control flow in \CFA has a strong start, development is still underway to complete a number of missing features.

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

\smallskip
\textbf{Non-Blocking I/O:}
Many modern workloads are not bound by computation but IO operations, common cases 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.

\smallskip
\textbf{Other Concurrency Tools:}
While monitors offer flexible and powerful concurrency for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
Examples of such tools can include futures and promises~\cite{promises}, executors and actors.
These additional features are useful for applications that can be constructed without shared data and direct blocking.
As well, new \CFA extensions should make it possible to create a uniform interface for virtually all mutual exclusion, including monitors and low-level locks.

\smallskip
\textbf{Implicit Threading:}
Basic \emph{embarrassingly parallel} applications can benefit greatly from implicit concurrency, where sequential programs are converted to concurrent, 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 mechanisms 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 recognize the design assistance of Aaron Moss, Rob Schluntz, Andrew Beach, and Michael Brooks; David Dice for commenting and helping with the Java benchmarks; and Gregor Richards for helping with the Node.js benchmarks.
This research is funded by the NSERC/Waterloo-Huawei (\url{http://www.huawei.com}) Joint Innovation Lab. %, and Peter Buhr is partially funded by the Natural Sciences and Engineering Research Council of Canada.

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

\end{document}

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