source: doc/papers/concurrency/Paper.tex @ e782290

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since e782290 was 200fcb3, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

add auto newline to sout, change endl to nl

  • Property mode set to 100644
File size: 123.2 KB
RevLine 
[d5ccbe9]1\documentclass[AMA,STIX1COL]{WileyNJD-v2}
2
3\articletype{RESEARCH ARTICLE}%
4
[fe3cd36]5\received{XXXXX}
6\revised{XXXXX}
7\accepted{XXXXX}
[d5ccbe9]8
9\raggedbottom
[604e76d]10
11%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
12
13% Latex packages used in the document.
[d046db2]14
[604e76d]15\usepackage{epic,eepic}
16\usepackage{xspace}
[d5ccbe9]17\usepackage{comment}
18\usepackage{upquote}                                            % switch curled `'" to straight
19\usepackage{listings}                                           % format program code
[0a89a8f]20\usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig}
[c8ad5d9]21\renewcommand{\thesubfigure}{(\Alph{subfigure})}
22\captionsetup{justification=raggedright,singlelinecheck=false}
[b199e54]23\usepackage{dcolumn}                                            % align decimal points in tables
[64188cc]24\usepackage{capt-of}
[d5ccbe9]25
26\hypersetup{breaklinks=true}
27\definecolor{OliveGreen}{cmyk}{0.64 0 0.95 0.40}
28\definecolor{Mahogany}{cmyk}{0 0.85 0.87 0.35}
29\definecolor{Plum}{cmyk}{0.50 1 0 0}
30
31\usepackage[pagewise]{lineno}
32\renewcommand{\linenumberfont}{\scriptsize\sffamily}
[604e76d]33
[9f66811]34\renewcommand{\topfraction}{0.8}                        % float must be greater than X of the page before it is forced onto its own page
35\renewcommand{\bottomfraction}{0.8}                     % float must be greater than X of the page before it is forced onto its own page
36\renewcommand{\floatpagefraction}{0.8}          % float must be greater than X of the page before it is forced onto its own page
[a87c86f]37\renewcommand{\textfraction}{0.0}                       % the entire page maybe devoted to floats with no text on the page at all
[d046db2]38
39\lefthyphenmin=3                                                        % hyphen only after 4 characters
40\righthyphenmin=3
[604e76d]41
42%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
43
44% Names used in the document.
45
[aac7197]46\newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
47\newcommand{\CFA}{\protect\CFAIcon}             % safe for section/caption
48\newcommand{\CFL}{\textrm{Cforall}\xspace}      % Cforall symbolic name
49\newcommand{\Celeven}{\textrm{C11}\xspace}      % C11 symbolic name
50\newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
51\newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
52\newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
53\newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
54\newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name
55\newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name
56
57%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[604e76d]58
59\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
60\newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}}
61\newcommand{\uC}{$\mu$\CC}
[08b5a7e]62\newcommand{\TODO}[1]{{\Textbf{#1}}}
[604e76d]63
[aac7197]64%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[604e76d]65
[aac7197]66% Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
67% removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
68% AFTER HYPERREF.
69%\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}
70\renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}
71
[48b9b36]72\renewcommand*{\thefootnote}{\Alph{footnote}} % hack because fnsymbol does not work
73%\renewcommand*{\thefootnote}{\fnsymbol{footnote}}
74
[aac7197]75\makeatletter
76% parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
77% use rather than use \parident directly.
78\newlength{\parindentlnth}
79\setlength{\parindentlnth}{\parindent}
80
81\newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{\lst@basicstyle{#1}}}}
82\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
83\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
84
85\newlength{\gcolumnposn}                                        % temporary hack because lstlisting does not handle tabs correctly
86\newlength{\columnposn}
87\setlength{\gcolumnposn}{3.5in}
88\setlength{\columnposn}{\gcolumnposn}
[48b9b36]89
[aac7197]90\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}}}}
91\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
92
93% Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
94% The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
95% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
96\newcommand{\newtermFontInline}{\emph}
97\newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
98\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
99\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
100
101% Latin abbreviation
102\newcommand{\abbrevFont}{\textit}                       % set empty for no italics
[0a89a8f]103\@ifundefined{eg}{
[c8ad5d9]104\newcommand{\EG}{\abbrevFont{e}\abbrevFont{g}}
[aac7197]105\newcommand*{\eg}{%
106        \@ifnextchar{,}{\EG}%
107                {\@ifnextchar{:}{\EG}%
108                        {\EG,\xspace}}%
[0a89a8f]109}}{}%
110\@ifundefined{ie}{
[c8ad5d9]111\newcommand{\IE}{\abbrevFont{i}\abbrevFont{e}}
[aac7197]112\newcommand*{\ie}{%
113        \@ifnextchar{,}{\IE}%
114                {\@ifnextchar{:}{\IE}%
115                        {\IE,\xspace}}%
[0a89a8f]116}}{}%
117\@ifundefined{etc}{
[aac7197]118\newcommand{\ETC}{\abbrevFont{etc}}
119\newcommand*{\etc}{%
120        \@ifnextchar{.}{\ETC}%
121        {\ETC.\xspace}%
[0a89a8f]122}}{}%
123\@ifundefined{etal}{
[aac7197]124\newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}}
[0a89a8f]125\newcommand*{\etal}{%
[aac7197]126        \@ifnextchar{.}{\protect\ETAL}%
127                {\protect\ETAL.\xspace}%
[0a89a8f]128}}{}%
129\@ifundefined{viz}{
[aac7197]130\newcommand{\VIZ}{\abbrevFont{viz}}
131\newcommand*{\viz}{%
132        \@ifnextchar{.}{\VIZ}%
133                {\VIZ.\xspace}%
[0a89a8f]134}}{}%
[aac7197]135\makeatother
136
[9f66811]137\newenvironment{cquote}
138               {\list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
139                \item\relax}
140               {\endlist}
141
142%\newenvironment{cquote}{%
143%\list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
144%\item\relax%
145%}{%
146%\endlist%
147%}% cquote
[aac7197]148
149% CFA programming language, based on ANSI C (with some gcc additions)
150\lstdefinelanguage{CFA}[ANSI]{C}{
151        morekeywords={
[0a89a8f]152                _Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, __attribute, __attribute__,
153                auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__, __const, __const__,
[c8ad5d9]154                coroutine, disable, dtype, enable, exception, __extension__, fallthrough, fallthru, finally,
[0a89a8f]155                __float80, float80, __float128, float128, forall, ftype, _Generic, _Imaginary, __imag, __imag__,
156                inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
157                otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread,
158                _Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
159                virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
[aac7197]160        moredirectives={defined,include_next}%
161}
162
163\lstset{
164language=CFA,
165columns=fullflexible,
166basicstyle=\linespread{0.9}\sf,                                                 % reduce line spacing and use sanserif font
167stringstyle=\tt,                                                                                % use typewriter font
168tabsize=5,                                                                                              % N space tabbing
169xleftmargin=\parindentlnth,                                                             % indent code to paragraph indentation
170%mathescape=true,                                                                               % LaTeX math escape in CFA code $...$
171escapechar=\$,                                                                                  % LaTeX escape in CFA code
172keepspaces=true,                                                                                %
173showstringspaces=false,                                                                 % do not show spaces with cup
174showlines=true,                                                                                 % show blank lines at end of code
175aboveskip=4pt,                                                                                  % spacing above/below code block
176belowskip=3pt,
177% replace/adjust listing characters that look bad in sanserif
178literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
179        {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
[48b9b36]180        {<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
181        {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex{\textrm{\textgreater}}}2,
[aac7197]182moredelim=**[is][\color{red}]{`}{`},
183}% lstset
184
185% uC++ programming language, based on ANSI C++
186\lstdefinelanguage{uC++}[ANSI]{C++}{
187        morekeywords={
188                _Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _CatchResume, _Cormonitor, _Coroutine, _Disable,
189                _Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
190                _Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
191}
192\lstdefinelanguage{Golang}{
193        morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
194        morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
195                bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
196        morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
197        morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
198        morekeywords=[5]{Println,Printf,Error,},
199        sensitive=true,
200        morecomment=[l]{//},
201        morecomment=[s]{/*}{*/},
202        morestring=[b]',
203        morestring=[b]",
204        morestring=[s]{`}{`},
205}
206
207\lstnewenvironment{cfa}[1][]
208{\lstset{#1}}
209{}
210\lstnewenvironment{C++}[1][]                            % use C++ style
211{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
212{}
213\lstnewenvironment{uC++}[1][]
214{\lstset{#1}}
215{}
216\lstnewenvironment{Go}[1][]
217{\lstset{#1}}
218{}
219
220% inline code @...@
221\lstMakeShortInline@%
[604e76d]222
[48b9b36]223\let\OLDthebibliography\thebibliography
224\renewcommand\thebibliography[1]{
225  \OLDthebibliography{#1}
226  \setlength{\parskip}{0pt}
227  \setlength{\itemsep}{4pt plus 0.3ex}
228}
[604e76d]229
[d5ccbe9]230\title{\texorpdfstring{Concurrency in \protect\CFA}{Concurrency in Cforall}}
[604e76d]231
[d5ccbe9]232\author[1]{Thierry Delisle}
233\author[1]{Peter A. Buhr*}
[c8ad5d9]234\authormark{DELISLE \textsc{et al.}}
[604e76d]235
[c8ad5d9]236\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}
[604e76d]237
[c8ad5d9]238\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}}
[d5ccbe9]239
[c8ad5d9]240\fundingInfo{Natural Sciences and Engineering Research Council of Canada}
[d5ccbe9]241
242\abstract[Summary]{
243\CFA is a modern, polymorphic, \emph{non-object-oriented} extension of the C programming language.
[adb60242]244This paper discusses the design of the concurrency and parallelism features in \CFA, and its concurrent runtime-system.
[287da46]245These features are created from scratch as ISO C lacks concurrency, relying largely on the pthreads library for concurrency.
[adb60242]246Coroutines and lightweight (user) threads are introduced into \CFA;
247as well, monitors are added as a high-level mechanism for mutual exclusion and synchronization.
248A unique contribution of this work is allowing multiple monitors to be safely acquired \emph{simultaneously}.
[d5ccbe9]249All features respect the expectations of C programmers, while being fully integrate with the \CFA polymorphic type-system and other language features.
[adb60242]250Experimental results show comparable performance of the new features with similar mechanisms in other concurrent programming-languages.
[d5ccbe9]251}%
[604e76d]252
[0a89a8f]253\keywords{concurrency, parallelism, coroutines, threads, monitors, runtime, C, Cforall}
[604e76d]254
[d5ccbe9]255
256\begin{document}
257\linenumbers                                            % comment out to turn off line numbering
258
259\maketitle
[604e76d]260
[a87c86f]261
[604e76d]262\section{Introduction}
[5ff188f]263
[08b5a7e]264This paper provides a minimal concurrency \newterm{Application Program Interface} (API) that is simple, efficient and can be used to build other concurrency features.
[aac7197]265While the simplest concurrency system is a thread and a lock, this low-level approach is hard to master.
266An easier approach for programmers is to support higher-level constructs as the basis of concurrency.
[287da46]267Indeed, for highly-productive concurrent-programming, high-level approaches are much more popular~\cite{Hochstein05}.
268Examples of high-level approaches are jobs (thread pool)~\cite{TBB}, implicit threading~\cite{OpenMP}, monitors~\cite{Java}, channels~\cite{CSP,Go}, and message passing~\cite{Erlang,MPI}.
[604e76d]269
[48b9b36]270The following terminology is used.
[aac7197]271A \newterm{thread} is a fundamental unit of execution that runs a sequence of code and requires a stack to maintain state.
[287da46]272Multiple simultaneous threads give rise to \newterm{concurrency}, which requires locking to ensure access to shared data and safe communication.
[48b9b36]273\newterm{Locking}, and by extension \newterm{locks}, are defined as a mechanism to prevent progress of threads to provide safety.
[aac7197]274\newterm{Parallelism} is running multiple threads simultaneously.
275Parallelism implies \emph{actual} simultaneous execution, where concurrency only requires \emph{apparent} simultaneous execution.
[48b9b36]276As such, parallelism only affects performance, which is observed through differences in space and/or time at runtime.
277Hence, there are two problems to be solved: concurrency and parallelism.
[c8ad5d9]278While these two concepts are often combined, they are distinct, requiring different tools~\cite[\S~2]{Buhr05a}.
[e04aec4]279Concurrency tools handle mutual exclusion and synchronization, while parallelism tools handle performance, cost, and resource utilization.
[604e76d]280
[9f66811]281The proposed concurrency API is implemented in a dialect of C, called \CFA (pronounced C-for-all).
[287da46]282The paper discusses how the language features are added to the \CFA translator with respect to parsing, semantics, and type checking, and the corresponding high-performance runtime-library to implement the concurrent features.
[604e76d]283
[a87c86f]284
[604e76d]285\section{\CFA Overview}
286
287The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency.
[48b9b36]288Extended versions and explanation of the following code examples are available at the \CFA website~\cite{Cforall} or in Moss~\etal~\cite{Moss18}.
[604e76d]289
[e04aec4]290\CFA is a non-object-oriented extension of ISO-C, and hence, supports all C paradigms.
291Like C, the building blocks of \CFA are structures and routines.
[a87c86f]292Virtually all of the code generated by the \CFA translator respects C memory layouts and calling conventions.
[9f66811]293While \CFA is not object oriented, lacking the concept of a receiver (\eg @this@) and nominal inheritance-relationships, C has a notion of objects: ``region of data storage in the execution environment, the contents of which can represent values''~\cite[3.15]{C11}.
294While some object-oriented features appear in \CFA, they are independent capabilities, allowing \CFA to adopt them while maintaining a procedural paradigm.
[aac7197]295
[604e76d]296
[5ff188f]297\subsection{References}
[604e76d]298
[a87c86f]299\CFA provides multi-level rebindable references, as an alternative to pointers, which significantly reduces syntactic noise.
[aac7197]300\begin{cfa}
[a87c86f]301int x = 1, y = 2, z = 3;
302int * p1 = &x, ** p2 = &p1,  *** p3 = &p2,      $\C{// pointers to x}$
[e04aec4]303    `&` r1 = x,   `&&` r2 = r1,   `&&&` r3 = r2;        $\C{// references to x}$
[a87c86f]304int * p4 = &z, `&` r4 = z;
305
306*p1 = 3; **p2 = 3; ***p3 = 3;       // change x
307r1 =  3;     r2 = 3;      r3 = 3;        // change x: implicit dereferences *r1, **r2, ***r3
308**p3 = &y; *p3 = &p4;                // change p1, p2
[48b9b36]309`&`r3 = &y; `&&`r3 = &`&`r4;             // change r1, r2: cancel implicit dereferences (&*)**r3, (&(&*)*)*r3, &(&*)r4
[aac7197]310\end{cfa}
[a87c86f]311A reference is a handle to an object, like a pointer, but is automatically dereferenced the specified number of levels.
312Referencing (address-of @&@) a reference variable cancels one of the implicit dereferences, until there are no more implicit references, after which normal expression behaviour applies.
313
314
315\subsection{\texorpdfstring{\protect\lstinline{with} Statement}{with Statement}}
316\label{s:WithStatement}
317
[48b9b36]318Heterogeneous data is aggregated into a structure/union.
[a87c86f]319To reduce syntactic noise, \CFA provides a @with@ statement (see Pascal~\cite[\S~4.F]{Pascal}) to elide aggregate field-qualification by opening a scope containing the field identifiers.
320\begin{cquote}
321\vspace*{-\baselineskip}%???
322\lstDeleteShortInline@%
323\begin{cfa}
324struct S { char c; int i; double d; };
325struct T { double m, n; };
326// multiple aggregate parameters
327\end{cfa}
[48b9b36]328\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
[a87c86f]329\begin{cfa}
330void f( S & s, T & t ) {
331        `s.`c; `s.`i; `s.`d;
332        `t.`m; `t.`n;
333}
334\end{cfa}
335&
336\begin{cfa}
337void f( S & s, T & t ) `with ( s, t )` {
338        c; i; d;                // no qualification
339        m; n;
340}
341\end{cfa}
342\end{tabular}
343\lstMakeShortInline@%
344\end{cquote}
345Object-oriented programming languages only provide implicit qualification for the receiver.
346
[9f66811]347In detail, the @with@-statement syntax is:
[a87c86f]348\begin{cfa}
349$\emph{with-statement}$:
350        'with' '(' $\emph{expression-list}$ ')' $\emph{compound-statement}$
351\end{cfa}
[9a72c4d]352and may appear as the body of a routine or nested within a routine body.
[a87c86f]353Each expression in the expression-list provides a type and object.
354The type must be an aggregate type.
355(Enumerations are already opened.)
356The object is the implicit qualifier for the open structure-fields.
[9f66811]357All expressions in the expression list are opened in parallel within the compound statement, which is different from Pascal, which nests the openings from left to right.
[a87c86f]358
[604e76d]359
[5ff188f]360\subsection{Overloading}
[604e76d]361
[a87c86f]362\CFA maximizes the ability to reuse names via overloading to aggressively address the naming problem.
[9f66811]363Both variables and routines may be overloaded, where selection is based on number and types of returns and arguments (as in Ada~\cite{Ada}).
364\newpage
365\vspace*{-2\baselineskip}%???
[a87c86f]366\begin{cquote}
367\begin{cfa}
368// selection based on type
369\end{cfa}
[9f66811]370\lstDeleteShortInline@%
[48b9b36]371\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
[a87c86f]372\begin{cfa}
[48b9b36]373const short int `MIN` = -32768;
374const int `MIN` = -2147483648;
375const long int `MIN` = -9223372036854775808L;
[a87c86f]376\end{cfa}
377&
378\begin{cfa}
[48b9b36]379short int si = `MIN`;
380int i = `MIN`;
381long int li = `MIN`;
[a87c86f]382\end{cfa}
383\end{tabular}
[aac7197]384\begin{cfa}
385// selection based on type and number of parameters
386\end{cfa}
[48b9b36]387\begin{tabular}{@{}l@{\hspace{2.7\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
[a87c86f]388\begin{cfa}
[48b9b36]389void `f`( void );
390void `f`( char );
391void `f`( int, double );
[a87c86f]392\end{cfa}
393&
394\begin{cfa}
[48b9b36]395`f`();
396`f`( 'a' );
397`f`( 3, 5.2 );
[a87c86f]398\end{cfa}
399\end{tabular}
400\begin{cfa}
401// selection based on type and number of returns
402\end{cfa}
[48b9b36]403\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
[a87c86f]404\begin{cfa}
[48b9b36]405char `f`( int );
406double `f`( int );
407[char, double] `f`( int );
[a87c86f]408\end{cfa}
409&
410\begin{cfa}
[48b9b36]411char c = `f`( 3 );
412double d = `f`( 3 );
413[d, c] = `f`( 3 );
[a87c86f]414\end{cfa}
415\end{tabular}
416\lstMakeShortInline@%
417\end{cquote}
418Overloading is important for \CFA concurrency since the runtime system relies on creating different types to represent concurrency objects.
[e04aec4]419Therefore, overloading eliminates long prefixes and other naming conventions to prevent name clashes.
[287da46]420As seen in Section~\ref{s:Concurrency}, routine @main@ is heavily overloaded.
[9f66811]421As another example, variable overloading is useful in the parallel semantics of the @with@ statement for fields with the same name:
[aac7197]422\begin{cfa}
[a87c86f]423struct S { int `i`; int j; double m; } s;
424struct T { int `i`; int k; int m; } t;
425with ( s, t ) {
426        j + k;                                                                  $\C{// unambiguous, s.j + t.k}$
[48b9b36]427        m = 5.0;                                                                $\C{// unambiguous, s.m = 5.0}$
428        m = 1;                                                                  $\C{// unambiguous, t.m = 1}$
429        int a = m;                                                              $\C{// unambiguous, a = t.m }$
430        double b = m;                                                   $\C{// unambiguous, b = s.m}$
[a87c86f]431        int c = `s.i` + `t.i`;                                  $\C{// unambiguous, qualification}$
[48b9b36]432        (double)m;                                                              $\C{// unambiguous, cast s.m}$
[604e76d]433}
[aac7197]434\end{cfa}
[e04aec4]435For parallel semantics, both @s.i@ and @t.i@ are visible with the same type, so only @i@ is ambiguous without qualification.
[a87c86f]436
437
438\subsection{Operators}
[604e76d]439
[a87c86f]440Overloading also extends to operators.
[9a72c4d]441Operator-overloading syntax creates a routine name with an operator symbol and question marks for the operands:
[a87c86f]442\begin{cquote}
443\lstDeleteShortInline@%
444\begin{tabular}{@{}ll@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
[aac7197]445\begin{cfa}
[b199e54]446int ++?(int op);
447int ?++(int op);
448int `?+?`(int op1, int op2);
[a87c86f]449int ?<=?(int op1, int op2);
450int ?=? (int & op1, int op2);
451int ?+=?(int & op1, int op2);
[aac7197]452\end{cfa}
[a87c86f]453&
[aac7197]454\begin{cfa}
[a87c86f]455// unary prefix increment
456// unary postfix increment
457// binary plus
458// binary less than
459// binary assignment
460// binary plus-assignment
461\end{cfa}
462&
463\begin{cfa}
464struct S { int i, j; };
465S `?+?`( S op1, S op2) { // add two structures
466        return (S){op1.i + op2.i, op1.j + op2.j};
467}
468S s1 = {1, 2}, s2 = {2, 3}, s3;
469s3 = s1 `+` s2;         // compute sum: s3 == {2, 5}
[aac7197]470\end{cfa}
[a87c86f]471\end{tabular}
472\lstMakeShortInline@%
473\end{cquote}
474
[604e76d]475
[e04aec4]476\subsection{Constructors / Destructors}
477
478Object lifetime is a challenge in non-managed programming languages.
[9f66811]479\CFA responds with \CC-like constructors and destructors, using a different operator-overloading syntax.
[e04aec4]480\begin{cfa}
481struct VLA { int len, * data; };                        $\C{// variable length array of integers}$
482void ?{}( VLA & vla ) with ( vla ) { len = 10;  data = alloc( len ); }  $\C{// default constructor}$
483void ?{}( VLA & vla, int size, char fill ) with ( vla ) { len = size;  data = alloc( len, fill ); } // initialization
484void ?{}( VLA & vla, VLA other ) { vla.len = other.len;  vla.data = other.data; } $\C{// copy, shallow}$
485void ^?{}( VLA & vla ) with ( vla ) { free( data ); } $\C{// destructor}$
486{
487        VLA  x,            y = { 20, 0x01 },     z = y; $\C{// z points to y}$
[287da46]488        // $\LstCommentStyle{\color{red}\ \ \ x\{\};\ \ \ \ \ \ \ \ \ y\{ 20, 0x01 \};\ \ \ \ \ \ \ \ \ \ z\{ z, y \};\ \ \ \ \ \ \ implicit calls}$
[e04aec4]489        ^x{};                                                                   $\C{// deallocate x}$
490        x{};                                                                    $\C{// reallocate x}$
491        z{ 5, 0xff };                                                   $\C{// reallocate z, not pointing to y}$
492        ^y{};                                                                   $\C{// deallocate y}$
493        y{ x };                                                                 $\C{// reallocate y, points to x}$
494        x{};                                                                    $\C{// reallocate x, not pointing to y}$
[287da46]495}       //  $\LstCommentStyle{\color{red}\^{}z\{\};\ \ \^{}y\{\};\ \ \^{}x\{\};\ \ \ implicit calls}$
[e04aec4]496\end{cfa}
497Like \CC, construction is implicit on allocation (stack/heap) and destruction is implicit on deallocation.
498The object and all their fields are constructed/destructed.
[9f66811]499\CFA also provides @new@ and @delete@ as library routines, which behave like @malloc@ and @free@, in addition to constructing and destructing objects:
[e04aec4]500\begin{cfa}
501{
502        ... struct S s = {10}; ...                              $\C{// allocation, call constructor}$
503}                                                                                       $\C{// deallocation, call destructor}$
504struct S * s = new();                                           $\C{// allocation, call constructor}$
505...
506delete( s );                                                            $\C{// deallocation, call destructor}$
507\end{cfa}
508\CFA concurrency uses object lifetime as a means of mutual exclusion and/or synchronization.
509
510
[5ff188f]511\subsection{Parametric Polymorphism}
[604e76d]512\label{s:ParametricPolymorphism}
[a87c86f]513
[b199e54]514The signature feature of \CFA is parametric-polymorphic routines~\cite{Cforall} with routines generalized using a @forall@ clause (giving the language its name), which allow separately compiled routines to support generic usage over multiple types.
[9a72c4d]515For example, the following sum routine works for any type that supports construction from 0 and addition:
[aac7197]516\begin{cfa}
[a87c86f]517forall( otype T | { void `?{}`( T *, zero_t ); T `?+?`( T, T ); } ) // constraint type, 0 and +
518T sum( T a[$\,$], size_t size ) {
519        `T` total = { `0` };                                    $\C{// initialize by 0 constructor}$
520        for ( size_t i = 0; i < size; i += 1 )
521                total = total `+` a[i];                         $\C{// select appropriate +}$
[604e76d]522        return total;
523}
524S sa[5];
[a87c86f]525int i = sum( sa, 5 );                                           $\C{// use S's 0 construction and +}$
[aac7197]526\end{cfa}
[9f66811]527Type variables can be @otype@ or @dtype@.
528@otype@ refers to a \emph{complete type}, \ie, a type with size, alignment, default constructor, copy constructor, destructor, and assignment operator.
529@dtype@ refers to an \emph{incomplete type}, \eg, void or a forward-declared type.
530The builtin types @zero_t@ and @one_t@ overload constant 0 and 1 for a new types, where both 0 and 1 have special meaning in C.
[604e76d]531
[9a72c4d]532\CFA provides \newterm{traits} to name a group of type assertions, where the trait name allows specifying the same set of assertions in multiple locations, preventing repetition mistakes at each routine declaration:
[aac7197]533\begin{cfa}
[a87c86f]534trait `sumable`( otype T ) {
535        void `?{}`( T &, zero_t );                              $\C{// 0 literal constructor}$
536        T `?+?`( T, T );                                                $\C{// assortment of additions}$
537        T ?+=?( T &, T );
538        T ++?( T & );
539        T ?++( T & );
[604e76d]540};
[a87c86f]541forall( otype T `| sumable( T )` )                      $\C{// use trait}$
542T sum( T a[$\,$], size_t size );
[aac7197]543\end{cfa}
[604e76d]544
[287da46]545Using the return type for overload discrimination, it is possible to write a type-safe @alloc@ based on the C @malloc@:
[aac7197]546\begin{cfa}
[a87c86f]547forall( dtype T | sized(T) ) T * alloc( void ) { return (T *)malloc( sizeof(T) ); }
548int * ip = alloc();                                                     $\C{// select type and size from left-hand side}$
549double * dp = alloc();
550struct S {...} * sp = alloc();
551\end{cfa}
552where the return type supplies the type/size of the allocation, which is impossible in most type systems.
553
554
[287da46]555\section{Concurrency}
556\label{s:Concurrency}
[604e76d]557
[48b9b36]558At its core, concurrency is based on multiple call-stacks and scheduling threads executing on these stacks.
559Multiple call stacks (or contexts) and a single thread of execution, called \newterm{coroutining}~\cite{Conway63,Marlin80}, does \emph{not} imply concurrency~\cite[\S~2]{Buhr05a}.
[287da46]560In coroutining, the single thread is self-scheduling across the stacks, so execution is deterministic, \ie the execution path from input to output is fixed and predictable.
[48b9b36]561A \newterm{stackless} coroutine executes on the caller's stack~\cite{Python} but this approach is restrictive, \eg preventing modularization and supporting only iterator/generator-style programming;
[9f66811]562a \newterm{stackful} coroutine executes on its own stack, allowing full generality.
563Only stackful coroutines are a stepping stone to concurrency.
[48b9b36]564
[287da46]565The transition to concurrency, even for execution with a single thread and multiple stacks, occurs when coroutines also context switch to a \newterm{scheduling oracle}, introducing non-determinism from the coroutine perspective~\cite[\S~3]{Buhr05a}.
[48b9b36]566Therefore, a minimal concurrency system is possible using coroutines (see Section \ref{coroutine}) in conjunction with a scheduler to decide where to context switch next.
567The resulting execution system now follows a cooperative threading-model, called \newterm{non-preemptive scheduling}.
568
[9f66811]569Because the scheduler is special, it can either be a stackless or stackful coroutine.
[48b9b36]570For 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.
[9f66811]571For 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.
572A stackful scheduler is often used for simplicity and security.
[48b9b36]573
574Regardless of the approach used, a subset of concurrency related challenges start to appear.
575For the complete set of concurrency challenges to occur, the missing feature is \newterm{preemption}, where context switching occurs randomly between any two instructions, often based on a timer interrupt, called \newterm{preemptive scheduling}.
[9f66811]576While a scheduler introduces uncertainty in the order of execution, preemption introduces uncertainty about where context switches occur.
[48b9b36]577Interestingly, uncertainty is necessary for the runtime (operating) system to give the illusion of parallelism on a single processor and increase performance on multiple processors.
578The reason is that only the runtime has complete knowledge about resources and how to best utilized them.
579However, the introduction of unrestricted non-determinism results in the need for \newterm{mutual exclusion} and \newterm{synchronization} to restrict non-determinism for correctness;
580otherwise, it is impossible to write meaningful programs.
[d5ccbe9]581Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows.
[604e76d]582
[90cedbdd]583An important missing feature in C is threading\footnote{While the C11 standard defines a \protect\lstinline@threads.h@ header, it is minimal and defined as optional.
[d5ccbe9]584As such, library support for threading is far from widespread.
[90cedbdd]585At the time of writing the paper, neither \protect\lstinline@gcc@ nor \protect\lstinline@clang@ support \protect\lstinline@threads.h@ in their standard libraries.}.
[08b5a7e]586In modern programming languages, a lack of threading is unacceptable~\cite{Sutter05, Sutter05b}, and therefore existing and new programming languages must have tools for writing efficient concurrent programs to take advantage of parallelism.
[d5ccbe9]587As an extension of C, \CFA needs to express these concepts in a way that is as natural as possible to programmers familiar with imperative languages.
[48b9b36]588Furthermore, because C is a system-level language, programmers expect to choose precisely which features they need and which cost they are willing to pay.
589Hence, concurrent programs should be written using high-level mechanisms, and only step down to lower-level mechanisms when performance bottlenecks are encountered.
[604e76d]590
[aac7197]591
[0a89a8f]592\subsection{Coroutines: A Stepping Stone}\label{coroutine}
593
[287da46]594While the focus of this discussion is concurrency and parallelism, it is important to address coroutines, which are a significant building block of a concurrency system (but not concurrent among themselves).
[adb60242]595Coroutines are generalized routines allowing execution to be temporarily suspended and later resumed.
[48b9b36]596Hence, unlike a normal routine, a coroutine may not terminate when it returns to its caller, allowing it to be restarted with the values and execution location present at the point of suspension.
[adb60242]597This capability is accomplished via the coroutine's stack, where suspend/resume context switch among stacks.
[48b9b36]598Because threading design-challenges are present in coroutines, their design effort is relevant, and this effort can be easily exposed to programmers giving them a useful new programming paradigm because a coroutine handles the class of problems that need to retain state between calls, \eg plugins, device drivers, and finite-state machines.
[9f66811]599Therefore, the two fundamental features of the core \CFA coroutine-API are independent call-stacks and @suspend@/@resume@ operations.
[0a89a8f]600
[287da46]601For example, a problem made easier with coroutines is unbounded generators, \eg generating an infinite sequence of Fibonacci numbers
[0a89a8f]602\begin{displaymath}
[48b9b36]603\mathsf{fib}(n) = \left \{
[0a89a8f]604\begin{array}{ll}
[48b9b36]6050                                       & n = 0         \\
6061                                       & n = 1         \\
607\mathsf{fib}(n-1) + \mathsf{fib}(n-2)   & n \ge 2       \\
[0a89a8f]608\end{array}
609\right.
610\end{displaymath}
[287da46]611where Figure~\ref{f:C-fibonacci} shows conventional approaches for writing a Fibonacci generator in C.
612Figure~\ref{f:GlobalVariables} illustrates the following problems: unique unencapsulated global variables necessary to retain state between calls, only one Fibonacci generator, and execution state must be explicitly retained via explicit state variables.
613Figure~\ref{f:ExternalState} addresses these issues: unencapsulated program global variables become encapsulated structure variables, unique global variables are replaced by multiple Fibonacci objects, and explicit execution state is removed by precomputing the first two Fibonacci numbers and returning $\mathsf{fib}(n-2)$.
[604e76d]614
[aac7197]615\begin{figure}
[0a89a8f]616\centering
617\newbox\myboxA
618\begin{lrbox}{\myboxA}
[08b5a7e]619\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[0a89a8f]620`int f1, f2, state = 1;`   // single global variables
621int fib() {
622        int fn;
623        `switch ( state )` {  // explicit execution state
624          case 1: fn = 0;  f1 = fn;  state = 2;  break;
625          case 2: fn = 1;  f2 = f1;  f1 = fn;  state = 3;  break;
626          case 3: fn = f1 + f2;  f2 = f1;  f1 = fn;  break;
[604e76d]627        }
[0a89a8f]628        return fn;
[604e76d]629}
630int main() {
[0a89a8f]631
632        for ( int i = 0; i < 10; i += 1 ) {
633                printf( "%d\n", fib() );
[604e76d]634        }
635}
[08b5a7e]636\end{cfa}
[0a89a8f]637\end{lrbox}
[aac7197]638
[0a89a8f]639\newbox\myboxB
640\begin{lrbox}{\myboxB}
[08b5a7e]641\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[0a89a8f]642#define FIB_INIT `{ 0, 1 }`
643typedef struct { int f2, f1; } Fib;
644int fib( Fib * f ) {
645
646        int ret = f->f2;
647        int fn = f->f1 + f->f2;
648        f->f2 = f->f1; f->f1 = fn;
649
650        return ret;
[604e76d]651}
652int main() {
[0a89a8f]653        Fib f1 = FIB_INIT, f2 = FIB_INIT;
654        for ( int i = 0; i < 10; i += 1 ) {
655                printf( "%d %d\n", fib( &f1 ), fib( &f2 ) );
[604e76d]656        }
657}
[08b5a7e]658\end{cfa}
[0a89a8f]659\end{lrbox}
[766309d]660
[287da46]661\subfloat[3 States: global variables]{\label{f:GlobalVariables}\usebox\myboxA}
[0a89a8f]662\qquad
[287da46]663\subfloat[1 State: external variables]{\label{f:ExternalState}\usebox\myboxB}
[0a89a8f]664\caption{C Fibonacci Implementations}
665\label{f:C-fibonacci}
666
667\bigskip
668
669\newbox\myboxA
670\begin{lrbox}{\myboxA}
[08b5a7e]671\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[0a89a8f]672`coroutine` Fib { int fn; };
[48b9b36]673void main( Fib & fib ) with( fib ) {
[0a89a8f]674        int f1, f2;
675        fn = 0;  f1 = fn;  `suspend()`;
676        fn = 1;  f2 = f1;  f1 = fn;  `suspend()`;
677        for ( ;; ) {
678                fn = f1 + f2;  f2 = f1;  f1 = fn;  `suspend()`;
679        }
680}
681int next( Fib & fib ) with( fib ) {
682        `resume( fib );`
683        return fn;
[604e76d]684}
685int main() {
[0a89a8f]686        Fib f1, f2;
687        for ( int i = 1; i <= 10; i += 1 ) {
[200fcb3]688                sout | next( f1 ) | next( f2 );
[0a89a8f]689        }
690}
[08b5a7e]691\end{cfa}
[0a89a8f]692\end{lrbox}
693\newbox\myboxB
694\begin{lrbox}{\myboxB}
[08b5a7e]695\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[0a89a8f]696`coroutine` Fib { int ret; };
[48b9b36]697void main( Fib & f ) with( fib ) {
[0a89a8f]698        int fn, f1 = 1, f2 = 0;
699        for ( ;; ) {
700                ret = f2;
[766309d]701
[0a89a8f]702                fn = f1 + f2;  f2 = f1;  f1 = fn; `suspend();`
[604e76d]703        }
704}
[0a89a8f]705int next( Fib & fib ) with( fib ) {
706        `resume( fib );`
707        return ret;
708}
709
710
711
712
713
714
[08b5a7e]715\end{cfa}
[0a89a8f]716\end{lrbox}
717\subfloat[3 States, internal variables]{\label{f:Coroutine3States}\usebox\myboxA}
[c8ad5d9]718\qquad\qquad
[0a89a8f]719\subfloat[1 State, internal variables]{\label{f:Coroutine1State}\usebox\myboxB}
720\caption{\CFA Coroutine Fibonacci Implementations}
[287da46]721\label{f:cfa-fibonacci}
[aac7197]722\end{figure}
[604e76d]723
[48b9b36]724Using a coroutine, it is possible to express the Fibonacci formula directly without any of the C problems.
[e04aec4]725Figure~\ref{f:Coroutine3States} creates a @coroutine@ type, @`coroutine` Fib { int fn; }@, which provides communication, @fn@, for the \newterm{coroutine main}, @main@, which runs on the coroutine stack, and possibly multiple interface routines, \eg @next@.
[48b9b36]726Like 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.
[9f66811]727The 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@.
[9a72c4d]728The interface routine @next@, takes a Fibonacci instance and context switches to it using @resume@;
[6f9bc09]729on restart, the Fibonacci field, @fn@, contains the next value in the sequence, which is returned.
[287da46]730The first @resume@ is special because it allocates the coroutine stack and cocalls its coroutine main on that stack;
[48b9b36]731when the coroutine main returns, its stack is deallocated.
732Hence, @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.
733Figure~\ref{f:Coroutine1State} shows the coroutine version of the C version in Figure~\ref{f:ExternalState}.
[6f9bc09]734Coroutine generators are called \newterm{output coroutines} because values are only returned.
[48b9b36]735
[6f9bc09]736Figure~\ref{f:CFAFmt} shows an \newterm{input coroutine}, @Format@, for restructuring text into groups of characters of fixed-size blocks.
[48b9b36]737For example, the input of the left is reformatted into the output on the right.
738\begin{quote}
739\tt
740\begin{tabular}{@{}l|l@{}}
741\multicolumn{1}{c|}{\textbf{\textrm{input}}} & \multicolumn{1}{c}{\textbf{\textrm{output}}} \\
742abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
743&
744\begin{tabular}[t]{@{}lllll@{}}
745abcd    & efgh  & ijkl  & mnop  & qrst  \\
746uvwx    & yzab  & cdef  & ghij  & klmn  \\
747opqr    & stuv  & wxyz  &               &
748\end{tabular}
749\end{tabular}
750\end{quote}
[6f9bc09]751The example takes advantage of resuming a coroutine in the constructor to prime the loops so the first character sent for formatting appears inside the nested loops.
[adb60242]752The destructor provides a newline, if formatted text ends with a full line.
753Figure~\ref{f:CFmt} shows the C equivalent formatter, where the loops of the coroutine are flattened (linearized) and rechecked on each call because execution location is not retained between calls.
[287da46]754(Linearized code is the bane of device drivers.)
[0a89a8f]755
[604e76d]756\begin{figure}
[48b9b36]757\centering
758\newbox\myboxA
759\begin{lrbox}{\myboxA}
[08b5a7e]760\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[0a89a8f]761`coroutine` Format {
[48b9b36]762        char ch;   // used for communication
763        int g, b;  // global because used in destructor
[0a89a8f]764};
765void main( Format & fmt ) with( fmt ) {
[35a9e41]766        for ( ;; ) {
[6f9bc09]767                for ( g = 0; g < 5; g += 1 ) {      // group
[48b9b36]768                        for ( b = 0; b < 4; b += 1 ) { // block
[0a89a8f]769                                `suspend();`
[48b9b36]770                                sout | ch;              // separator
[0a89a8f]771                        }
[48b9b36]772                        sout | "  ";               // separator
[0a89a8f]773                }
[200fcb3]774                sout | nl;
[604e76d]775        }
776}
[48b9b36]777void ?{}( Format & fmt ) { `resume( fmt );` }
778void ^?{}( Format & fmt ) with( fmt ) {
[200fcb3]779        if ( g != 0 || b != 0 ) sout | nl;
[48b9b36]780}
781void format( Format & fmt ) {
[0a89a8f]782        `resume( fmt );`
[604e76d]783}
[aac7197]784int main() {
[0a89a8f]785        Format fmt;
[48b9b36]786        eof: for ( ;; ) {
787                sin | fmt.ch;
788          if ( eof( sin ) ) break eof;
789                format( fmt );
790        }
791}
[08b5a7e]792\end{cfa}
[48b9b36]793\end{lrbox}
794
795\newbox\myboxB
796\begin{lrbox}{\myboxB}
[08b5a7e]797\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[48b9b36]798struct Format {
[0a89a8f]799        char ch;
[48b9b36]800        int g, b;
801};
802void format( struct Format * fmt ) {
[6f9bc09]803        if ( fmt->ch != -1 ) {      // not EOF ?
[48b9b36]804                printf( "%c", fmt->ch );
805                fmt->b += 1;
806                if ( fmt->b == 4 ) {  // block
807                        printf( "  " );      // separator
808                        fmt->b = 0;
809                        fmt->g += 1;
810                }
811                if ( fmt->g == 5 ) {  // group
[6f9bc09]812                        printf( "\n" );     // separator
[48b9b36]813                        fmt->g = 0;
814                }
815        } else {
816                if ( fmt->g != 0 || fmt->b != 0 ) printf( "\n" );
[604e76d]817        }
818}
[48b9b36]819int main() {
820        struct Format fmt = { 0, 0, 0 };
821        for ( ;; ) {
822                scanf( "%c", &fmt.ch );
823          if ( feof( stdin ) ) break;
824                format( &fmt );
825        }
826        fmt.ch = -1;
827        format( &fmt );
828}
[08b5a7e]829\end{cfa}
[48b9b36]830\end{lrbox}
831\subfloat[\CFA Coroutine]{\label{f:CFAFmt}\usebox\myboxA}
832\qquad
833\subfloat[C Linearized]{\label{f:CFmt}\usebox\myboxB}
[0a89a8f]834\caption{Formatting text into lines of 5 blocks of 4 characters.}
835\label{f:fmt-line}
[604e76d]836\end{figure}
837
[e04aec4]838The previous examples are \newterm{asymmetric (semi) coroutine}s because one coroutine always calls a resuming routine for another coroutine, and the resumed coroutine always suspends back to its last resumer, similar to call/return for normal routines.
[287da46]839However, @resume@ and @suspend@ context switch among existing stack-frames, rather than create new ones so there is no stack growth.
[9f66811]840\newterm{Symmetric (full) coroutine}s have a coroutine call to a resuming routine for another coroutine, and its coroutine main calls another resuming routine, which eventually forms a resuming-call cycle.
[48b9b36]841(The trivial cycle is a coroutine resuming itself.)
842This control flow is similar to recursion for normal routines, but again there is no stack growth from the context switch.
843
[604e76d]844\begin{figure}
[0a89a8f]845\centering
[48b9b36]846\lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $
[0a89a8f]847\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
848\begin{cfa}
849`coroutine` Prod {
850        Cons & c;
851        int N, money, receipt;
[604e76d]852};
[0a89a8f]853void main( Prod & prod ) with( prod ) {
854        // 1st resume starts here
855        for ( int i = 0; i < N; i += 1 ) {
856                int p1 = random( 100 ), p2 = random( 100 );
[200fcb3]857                sout | p1 | " " | p2;
[0a89a8f]858                int status = delivery( c, p1, p2 );
[200fcb3]859                sout | " $" | money | nl | status;
[0a89a8f]860                receipt += 1;
[604e76d]861        }
[0a89a8f]862        stop( c );
[200fcb3]863        sout | "prod stops";
[604e76d]864}
[0a89a8f]865int payment( Prod & prod, int money ) {
866        prod.money = money;
867        `resume( prod );`
868        return prod.receipt;
869}
870void start( Prod & prod, int N, Cons &c ) {
871        &prod.c = &c;
872        prod.[N, receipt] = [N, 0];
873        `resume( prod );`
[604e76d]874}
875int main() {
[0a89a8f]876        Prod prod;
877        Cons cons = { prod };
878        start( prod, 5, cons );
879}
880\end{cfa}
881&
882\begin{cfa}
883`coroutine` Cons {
884        Prod & p;
885        int p1, p2, status;
886        _Bool done;
887};
888void ?{}( Cons & cons, Prod & p ) {
889        &cons.p = &p;
890        cons.[status, done ] = [0, false];
891}
892void ^?{}( Cons & cons ) {}
893void main( Cons & cons ) with( cons ) {
894        // 1st resume starts here
895        int money = 1, receipt;
896        for ( ; ! done; ) {
[200fcb3]897                sout | p1 | " " | p2 | nl | " $" | money;
[0a89a8f]898                status += 1;
899                receipt = payment( p, money );
[200fcb3]900                sout | " #" | receipt;
[0a89a8f]901                money += 1;
[604e76d]902        }
[200fcb3]903        sout | "cons stops";
[0a89a8f]904}
905int delivery( Cons & cons, int p1, int p2 ) {
906        cons.[p1, p2] = [p1, p2];
907        `resume( cons );`
908        return cons.status;
909}
910void stop( Cons & cons ) {
911        cons.done = true;
912        `resume( cons );`
[604e76d]913}
[aac7197]914\end{cfa}
[0a89a8f]915\end{tabular}
916\caption{Producer / consumer: resume-resume cycle, bi-directional communication}
917\label{f:ProdCons}
[604e76d]918\end{figure}
919
[48b9b36]920Figure~\ref{f:ProdCons} shows a producer/consumer symmetric-coroutine performing bi-directional communication.
921Since the solution involves a full-coroutining cycle, the program main creates one coroutine in isolation, passes this coroutine to its partner, and closes the cycle at the call to @start@.
[287da46]922The @start@ routine communicates both the number of elements to be produced and the consumer into the producer's coroutine-structure.
[48b9b36]923Then the @resume@ to @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
[6f9bc09]924@prod@'s coroutine main starts, creates local variables that are retained between coroutine activations, and executes $N$ iterations, each generating two random values, calling the consumer to deliver the values, and printing the status returned from the consumer.
[48b9b36]925
926The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
927For the first resume, @cons@'s stack is initialized, creating local variables retained between subsequent activations of the coroutine.
[e04aec4]928The consumer iterates until the @done@ flag is set, prints the values delivered by the producer, increments status, and calls back to the producer via @payment@, and on return from @payment@, prints the receipt from the producer and increments @money@ (inflation).
[287da46]929The call from the consumer to @payment@ introduces the cycle between producer and consumer.
[48b9b36]930When @payment@ is called, the consumer copies values into the producer's communication variable and a resume is executed.
[9f66811]931The context switch restarts the producer at the point where it last context switched, so it continues in @delivery@ after the resume.
[48b9b36]932
[6f9bc09]933@delivery@ returns the status value in @prod@'s coroutine main, where the status is printed.
[48b9b36]934The loop then repeats calling @delivery@, where each call resumes the consumer coroutine.
935The context switch to the consumer continues in @payment@.
[6f9bc09]936The consumer increments and returns the receipt to the call in @cons@'s coroutine main.
[48b9b36]937The loop then repeats calling @payment@, where each call resumes the producer coroutine.
938
939After iterating $N$ times, the producer calls @stop@.
940The @done@ flag is set to stop the consumer's execution and a resume is executed.
941The context switch restarts @cons@ in @payment@ and it returns with the last receipt.
942The consumer terminates its loops because @done@ is true, its @main@ terminates, so @cons@ transitions from a coroutine back to an object, and @prod@ reactivates after the resume in @stop@.
[6f9bc09]943@stop@ returns and @prod@'s coroutine main terminates.
[48b9b36]944The program main restarts after the resume in @start@.
[6f9bc09]945@start@ returns and the program main terminates.
[48b9b36]946
[0a89a8f]947
[6f9bc09]948\subsection{Coroutine Implementation}
[0a89a8f]949
[fe3cd36]950A significant implementation challenge for coroutines (and threads, see Section~\ref{threads}) is adding extra fields and executing code after/before the coroutine constructor/destructor and coroutine main to create/initialize/de-initialize/destroy extra fields and the stack.
[6f9bc09]951There are several solutions to this problem and the chosen option forced the \CFA coroutine design.
[604e76d]952
[6f9bc09]953Object-oriented inheritance provides extra fields and code in a restricted context, but it requires programmers to explicitly perform the inheritance:
[287da46]954\begin{cfa}[morekeywords={class,inherits}]
955class mycoroutine inherits baseCoroutine { ... }
[aac7197]956\end{cfa}
[6f9bc09]957and the programming language (and possibly its tool set, \eg debugger) may need to understand @baseCoroutine@ because of the stack.
[adb60242]958Furthermore, the execution of constructors/destructors is in the wrong order for certain operations.
[e04aec4]959For example, for threads if the thread is implicitly started, it must start \emph{after} all constructors, because the thread relies on a completely initialized object, but the inherited constructor runs \emph{before} the derived.
[604e76d]960
[9f66811]961An alternative is composition:
[aac7197]962\begin{cfa}
[6f9bc09]963struct mycoroutine {
964        ... // declarations
965        baseCoroutine dummy; // composition, last declaration
[604e76d]966}
[aac7197]967\end{cfa}
[6f9bc09]968which also requires an explicit declaration that must be the last one to ensure correct initialization order.
969However, there is nothing preventing wrong placement or multiple declarations.
[604e76d]970
[9a72c4d]971For coroutines as for threads, many implementations are based on routine pointers or routine objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
[6f9bc09]972For example, Boost implements coroutines in terms of four functor object-types:
[aac7197]973\begin{cfa}
[604e76d]974asymmetric_coroutine<>::pull_type
975asymmetric_coroutine<>::push_type
976symmetric_coroutine<>::call_type
977symmetric_coroutine<>::yield_type
[aac7197]978\end{cfa}
[b199e54]979Similarly, the canonical threading paradigm is often based on routine pointers, \eg @pthreads@~\cite{Butenhof97}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}.
[6f9bc09]980However, the generic thread-handle (identifier) is limited (few operations), unless it is wrapped in a custom type.
[aac7197]981\begin{cfa}
[6f9bc09]982void mycor( coroutine_t cid, void * arg ) {
983        int * value = (int *)arg;                               $\C{// type unsafe, pointer-size only}$
[aac7197]984        // Coroutine body
[604e76d]985}
986int main() {
[6f9bc09]987        int input = 0, output;
988        coroutine_t cid = coroutine_create( &mycor, (void *)&input ); $\C{// type unsafe, pointer-size only}$
989        coroutine_resume( cid, (void *)input, (void **)&output ); $\C{// type unsafe, pointer-size only}$
[604e76d]990}
[aac7197]991\end{cfa}
[6f9bc09]992Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda-based coroutines adds very little.
[604e76d]993
[9a72c4d]994Note, the type @coroutine_t@ must be an abstract handle to the coroutine, because the coroutine descriptor and its stack are non-copyable.
995Copying the coroutine descriptor results in copies being out of date with the current state of the stack.
[e04aec4]996Correspondingly, copying the stack results is copies being out of date with the coroutine descriptor, and pointers in the stack being out of date to data on the stack.
[9a72c4d]997(There is no mechanism in C to find all stack-specific pointers and update them as part of a copy.)
998
[6f9bc09]999The selected approach is to use language support by introducing a new kind of aggregate (structure):
[aac7197]1000\begin{cfa}
[6f9bc09]1001coroutine Fibonacci {
1002        int fn; // communication variables
[604e76d]1003};
[6f9bc09]1004\end{cfa}
1005The @coroutine@ keyword means the compiler (and tool set) can find and inject code where needed.
1006The downside of this approach is that it makes coroutine a special case in the language.
1007Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language.
1008Furthermore, implementing coroutines without language supports also displays the power of a programming language.
[9f66811]1009While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can still be constructed without language support.
1010The reserved keyword simply eases use for the common case.
[604e76d]1011
[9f66811]1012Part of the mechanism to generalize coroutines is using a \CFA trait, which defines a coroutine as anything satisfying the trait @is_coroutine@, and this trait restricts the available set of coroutine-manipulation routines:
[6f9bc09]1013\begin{cfa}
[9a72c4d]1014trait is_coroutine( `dtype` T ) {
1015        void main( T & );
1016        coroutine_desc * get_coroutine( T & );
[6f9bc09]1017};
[9a72c4d]1018forall( `dtype` T | is_coroutine(T) ) void suspend( T & );
1019forall( `dtype` T | is_coroutine(T) ) void resume( T & );
1020\end{cfa}
[adb60242]1021The @dtype@ property provides no implicit copying operations and the @is_coroutine@ trait provides no explicit copying operations, so all coroutines must be passed by reference (pointer).
[9a72c4d]1022The routine definitions ensures there is a statically-typed @main@ routine that is the starting point (first stack frame) of a coroutine, and a mechanism to get (read) the currently executing coroutine handle.
1023The @main@ routine has no return value or additional parameters because the coroutine type allows an arbitrary number of interface routines with corresponding arbitrary typed input/output values versus fixed ones.
[e04aec4]1024The advantage of this approach is that users can easily create different types of coroutines, \eg changing the memory layout of a coroutine is trivial when implementing the @get_coroutine@ routine, and possibly redefining @suspend@ and @resume@.
[6f9bc09]1025The \CFA keyword @coroutine@ implicitly implements the getter and forward declarations required for implementing the coroutine main:
1026\begin{cquote}
1027\begin{tabular}{@{}ccc@{}}
1028\begin{cfa}
1029coroutine MyCor {
1030        int value;
[604e76d]1031
1032};
[6f9bc09]1033\end{cfa}
[08b5a7e]1034&
1035{\Large $\Rightarrow$}
1036&
[6f9bc09]1037\begin{tabular}{@{}ccc@{}}
1038\begin{cfa}
1039struct MyCor {
1040        int value;
1041        coroutine_desc cor;
[604e76d]1042};
[6f9bc09]1043\end{cfa}
1044&
1045\begin{cfa}
1046static inline coroutine_desc *
1047get_coroutine( MyCor & this ) {
1048        return &this.cor;
[604e76d]1049}
[6f9bc09]1050\end{cfa}
1051&
1052\begin{cfa}
1053void main( MyCor * this );
1054
1055
[604e76d]1056
[aac7197]1057\end{cfa}
[604e76d]1058\end{tabular}
[6f9bc09]1059\end{tabular}
1060\end{cquote}
1061The combination of these two approaches allows an easy and concise specification to coroutining (and concurrency) for normal users, while more advanced users have tighter control on memory layout and initialization.
[604e76d]1062
1063
[6f9bc09]1064\subsection{Thread Interface}
1065\label{threads}
[604e76d]1066
[6f9bc09]1067Both user and kernel threads are supported, where user threads provide concurrency and kernel threads provide parallelism.
1068Like coroutines and for the same design reasons, the selected approach for user threads is to use language support by introducing a new kind of aggregate (structure) and a \CFA trait:
1069\begin{cquote}
[9a72c4d]1070\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
[aac7197]1071\begin{cfa}
[6f9bc09]1072thread myThread {
1073        // communication variables
1074};
[604e76d]1075
1076
[6f9bc09]1077\end{cfa}
1078&
[aac7197]1079\begin{cfa}
[9a72c4d]1080trait is_thread( `dtype` T ) {
1081      void main( T & );
1082      thread_desc * get_thread( T & );
1083      void ^?{}( T & `mutex` );
[604e76d]1084};
[aac7197]1085\end{cfa}
[6f9bc09]1086\end{tabular}
1087\end{cquote}
[287da46]1088(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitor}.)
[9a72c4d]1089Like a coroutine, the statically-typed @main@ routine is the starting point (first stack frame) of a user thread.
[6f9bc09]1090The difference is that a coroutine borrows a thread from its caller, so the first thread resuming a coroutine creates an instance of @main@;
1091whereas, a user thread receives its own thread from the runtime system, which starts in @main@ as some point after the thread constructor is run.\footnote{
[e04aec4]1092The \lstinline@main@ routine is already a special routine in C, \ie where the program's initial thread begins, so it is a natural extension of this semantics to use overloading to declare \lstinline@main@s for user coroutines and threads.}
[9a72c4d]1093No return value or additional parameters are necessary for this routine because the task type allows an arbitrary number of interface routines with corresponding arbitrary typed input/output values.
[6f9bc09]1094
1095\begin{comment} % put in appendix with coroutine version ???
[aac7197]1096As such the @main@ routine of a thread can be defined as
1097\begin{cfa}
[604e76d]1098thread foo {};
1099
1100void main(foo & this) {
[200fcb3]1101        sout | "Hello World!";
[604e76d]1102}
[aac7197]1103\end{cfa}
[604e76d]1104
[aac7197]1105In this example, threads of type @foo@ start execution in the @void main(foo &)@ routine, which prints @"Hello World!".@ While this paper encourages this approach to enforce strongly typed programming, users may prefer to use the routine-based thread semantics for the sake of simplicity.
[9a72c4d]1106With the static semantics it is trivial to write a thread type that takes a routine pointer as a parameter and executes it on its stack asynchronously.
[aac7197]1107\begin{cfa}
[9a72c4d]1108typedef void (*voidRtn)(int);
[604e76d]1109
[9a72c4d]1110thread RtnRunner {
1111        voidRtn func;
[604e76d]1112        int arg;
1113};
1114
[9a72c4d]1115void ?{}(RtnRunner & this, voidRtn inRtn, int arg) {
1116        this.func = inRtn;
[604e76d]1117        this.arg  = arg;
1118}
1119
[9a72c4d]1120void main(RtnRunner & this) {
1121        // thread starts here and runs the routine
[604e76d]1122        this.func( this.arg );
1123}
1124
1125void hello(/*unused*/ int) {
[200fcb3]1126        sout | "Hello World!";
[604e76d]1127}
1128
1129int main() {
[9a72c4d]1130        RtnRunner f = {hello, 42};
[604e76d]1131        return 0?
1132}
[aac7197]1133\end{cfa}
[90cedbdd]1134A consequence of the strongly typed approach to main is that memory layout of parameters and return values to/from a thread are now explicitly specified in the \textbf{API}.
[6f9bc09]1135\end{comment}
[604e76d]1136
[6f9bc09]1137For user threads to be useful, it must be possible to start and stop the underlying thread, and wait for it to complete execution.
1138While using an API such as @fork@ and @join@ is relatively common, such an interface is awkward and unnecessary.
1139A simple approach is to use allocation/deallocation principles, and have threads implicitly @fork@ after construction and @join@ before destruction.
[aac7197]1140\begin{cfa}
[6f9bc09]1141thread World {};
1142void main( World & this ) {
[200fcb3]1143        sout | "World!";
[604e76d]1144}
[6f9bc09]1145int main() {
1146        World w`[10]`;                                                  $\C{// implicit forks after creation}$
[200fcb3]1147        sout | "Hello ";                                        $\C{// "Hello " and 10 "World!" printed concurrently}$
[6f9bc09]1148}                                                                                       $\C{// implicit joins before destruction}$
[aac7197]1149\end{cfa}
[6f9bc09]1150This semantics ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
1151This tree-structure (lattice) create/delete from C block-structure is generalized by using dynamic allocation, so threads can outlive the scope in which they are created, much like dynamically allocating memory lets objects outlive the scope in which they are created.
[aac7197]1152\begin{cfa}
[6f9bc09]1153int main() {
[9f66811]1154        MyThread * heapLive;
[604e76d]1155        {
[9f66811]1156                MyThread blockLive;                                     $\C{// fork block-based thread}$
1157                heapLive = `new`( MyThread );           $\C{// fork heap-based thread}$
[6f9bc09]1158                ...
1159        }                                                                               $\C{// join block-based thread}$
1160        ...
[9f66811]1161        `delete`( heapLive );                                   $\C{// join heap-based thread}$
[604e76d]1162}
[aac7197]1163\end{cfa}
[6f9bc09]1164The heap-based approach allows arbitrary thread-creation topologies, with respect to fork/join-style concurrency.
[604e76d]1165
[9f66811]1166Figure~\ref{s:ConcurrentMatrixSummation} shows concurrently adding the rows of a matrix and then totalling the subtotals sequentially, after all the row threads have terminated.
[1dc58fd]1167The program uses heap-based threads because each thread needs different constructor values.
1168(Python provides a simple iteration mechanism to initialize array elements to different values allowing stack allocation.)
[287da46]1169The allocation/deallocation pattern appears unusual because allocated objects are immediately deallocated without any intervening code.
[1dc58fd]1170However, for threads, the deletion provides implicit synchronization, which is the intervening code.
[adb60242]1171While 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.
[1dc58fd]1172
1173\begin{figure}
1174\begin{cfa}
[adb60242]1175`thread` Adder { int * row, cols, & subtotal; } $\C{// communication variables}$
[1dc58fd]1176void ?{}( Adder & adder, int row[], int cols, int & subtotal ) {
[251454a0]1177    adder.[ row, cols, &subtotal ] = [ row, cols, &subtotal ];
[1dc58fd]1178}
1179void main( Adder & adder ) with( adder ) {
[251454a0]1180    subtotal = 0;
[e04aec4]1181    for ( int c = 0; c < cols; c += 1 ) { subtotal += row[c]; }
[1dc58fd]1182}
1183int main() {
1184    const int rows = 10, cols = 1000;
1185    int matrix[rows][cols], subtotals[rows], total = 0;
1186    // read matrix
1187    Adder * adders[rows];
1188    for ( int r = 0; r < rows; r += 1 ) {       $\C{// start threads to sum rows}$
[adb60242]1189                adders[r] = `new( matrix[r], cols, &subtotals[r] );`
[1dc58fd]1190    }
1191    for ( int r = 0; r < rows; r += 1 ) {       $\C{// wait for threads to finish}$
[adb60242]1192                `delete( adders[r] );`                          $\C{// termination join}$
[1dc58fd]1193                total += subtotals[r];                          $\C{// total subtotal}$
1194    }
[200fcb3]1195    sout | total;
[1dc58fd]1196}
1197\end{cfa}
1198\caption{Concurrent Matrix Summation}
1199\label{s:ConcurrentMatrixSummation}
1200\end{figure}
1201
[604e76d]1202
[9a72c4d]1203\section{Mutual Exclusion / Synchronization}
[604e76d]1204
[6f9bc09]1205Uncontrolled non-deterministic execution is meaningless.
[e04aec4]1206To reestablish meaningful execution requires mechanisms to reintroduce determinism, \ie restrict non-determinism, called mutual exclusion and synchronization, where mutual exclusion is an access-control mechanism on data shared by threads, and synchronization is a timing relationship among threads~\cite[\S~4]{Buhr05a}.
[9a72c4d]1207Since many deterministic challenges appear with the use of mutable shared state, some languages/libraries disallow it, \eg Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, Akka~\cite{Akka} (Scala).
[adb60242]1208In these paradigms, interaction among concurrent objects is performed by stateless message-passing~\cite{Thoth,Harmony,V-Kernel} or other paradigms closely related to networking concepts, \eg channels~\cite{CSP,Go}.
[287da46]1209However, in call/return-based languages, these approaches force a clear distinction, \ie introduce a new programming paradigm between regular and concurrent computation, \eg routine call versus message passing.
[9a72c4d]1210Hence, a programmer must learn and manipulate two sets of design patterns.
[6f9bc09]1211While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
[adb60242]1212In contrast, approaches based on stateful models more closely resemble the standard call/return programming-model, resulting in a single programming paradigm.
[604e76d]1213
[287da46]1214At the lowest level, concurrent control is implemented by atomic operations, upon which different kinds of locking mechanisms are constructed, \eg semaphores~\cite{Dijkstra68b}, barriers, and path expressions~\cite{Campbell74}.
[6f9bc09]1215However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}.
[9a72c4d]1216A newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
[9f66811]1217While this approach is pursued in hardware~\cite{Nakaike15} and system languages, like \CC~\cite{Cpp-Transactions}, the performance and feature set is still too restrictive to be the main concurrency paradigm for system languages, which is why it is rejected as the core paradigm for concurrency in \CFA.
[604e76d]1218
[9a72c4d]1219One of the most natural, elegant, and efficient mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor}.
1220First 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}.
1221In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as mutex locks or semaphores to simulate monitors.
1222For these reasons, \CFA selected monitors as the core high-level concurrency-construct, upon which higher-level approaches can be easily constructed.
[604e76d]1223
[0a89a8f]1224
[251454a0]1225\subsection{Mutual Exclusion}
[0a89a8f]1226
[251454a0]1227A group of instructions manipulating a specific instance of shared data that must be performed atomically is called an (individual) \newterm{critical-section}~\cite{Dijkstra65}.
[9a72c4d]1228The generalization is called a \newterm{group critical-section}~\cite{Joung00}, where multiple tasks with the same session may use the resource simultaneously, but different sessions may not use the resource simultaneously.
[251454a0]1229The readers/writer problem~\cite{Courtois71} is an instance of a group critical-section, where readers have the same session and all writers have a unique session.
[9a72c4d]1230\newterm{Mutual exclusion} enforces that the correct kind and number of threads are using a critical section.
[604e76d]1231
[d5ccbe9]1232However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
[251454a0]1233Methods range from low-level locks, which are fast and flexible but require significant attention for correctness, to higher-level concurrency techniques, which sacrifice some performance to improve ease of use.
[e04aec4]1234Ease of use comes by either guaranteeing some problems cannot occur, \eg deadlock free, or by offering a more explicit coupling between shared data and critical section.
1235For example, the \CC @std::atomic<T>@ offers an easy way to express mutual-exclusion on a restricted set of operations, \eg reading/writing, for numerical types.
[9a72c4d]1236However, a significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock.
1237Easing composability is another feature higher-level mutual-exclusion mechanisms can offer.
[604e76d]1238
[0a89a8f]1239
[251454a0]1240\subsection{Synchronization}
[0a89a8f]1241
[251454a0]1242Synchronization enforces relative ordering of execution, and synchronization tools provide numerous mechanisms to establish these timing relationships.
[9a72c4d]1243Low-level synchronization primitives offer good performance and flexibility at the cost of ease of use;
[e04aec4]1244higher-level mechanisms often simplify usage by adding better coupling between synchronization and data, \eg message passing, or offering a simpler solution to otherwise involved challenges, \eg barrier lock.
[9a72c4d]1245Often synchronization is used to order access to a critical section, \eg ensuring a reader thread is the next kind of thread to enter a critical section.
[9f66811]1246If a writer thread is scheduled for next access, but another reader thread acquires the critical section first, that reader \newterm{barged}.
[9a72c4d]1247Barging can result in staleness/freshness problems, where a reader barges ahead of a writer and reads temporally stale data, or a writer barges ahead of another writer overwriting data with a fresh value preventing the previous value from ever being read (lost computation).
[d5ccbe9]1248Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
[9a72c4d]1249This challenge is often split into two different approaches: barging avoidance and barging prevention.
1250Algorithms that allow a barger, but divert it until later using current synchronization state (flags), are avoiding the barger;
1251algorithms that preclude a barger from entering during synchronization in the critical section prevent barging completely.
[adb60242]1252Techniques like baton-passing locks~\cite{Andrews89} between threads instead of unconditionally releasing locks is an example of barging prevention.
[604e76d]1253
[0a89a8f]1254
[287da46]1255\section{Monitor}
1256\label{s:Monitor}
[6f9bc09]1257
[9a72c4d]1258A \textbf{monitor} is a set of routines that ensure mutual exclusion when accessing shared state.
1259More precisely, a monitor is a programming technique that binds mutual exclusion to routine scope, as opposed to locks, where mutual-exclusion is defined by acquire/release calls, independent of lexical context (analogous to block and heap storage allocation).
1260The strong association with the call/return paradigm eases programmability, readability and maintainability, at a slight cost in flexibility and efficiency.
[604e76d]1261
[e04aec4]1262Note, like coroutines/threads, both locks and monitors require an abstract handle to reference them, because at their core, both mechanisms are manipulating non-copyable shared-state.
[9a72c4d]1263Copying a lock is insecure because it is possible to copy an open lock and then use the open copy when the original lock is closed to simultaneously access the shared data.
1264Copying a monitor is secure because both the lock and shared data are copies, but copying the shared data is meaningless because it no longer represents a unique entity.
[adb60242]1265As for coroutines/tasks, the @dtype@ property provides no implicit copying operations and the @is_monitor@ trait provides no explicit copying operations, so all locks/monitors must be passed by reference (pointer).
[9a72c4d]1266\begin{cfa}
1267trait is_monitor( `dtype` T ) {
1268        monitor_desc * get_monitor( T & );
1269        void ^?{}( T & mutex );
1270};
[aac7197]1271\end{cfa}
[604e76d]1272
1273
[9a72c4d]1274\subsection{Mutex Acquisition}
1275\label{s:MutexAcquisition}
[604e76d]1276
[adb60242]1277While correctness implies a monitor's mutual exclusion is acquired and released, there are implementation options about when and where the locking/unlocking occurs.
[9a72c4d]1278(Much of this discussion also applies to basic locks.)
1279For example, a monitor may need to be passed through multiple helper routines before it becomes necessary to acquire the monitor mutual-exclusion.
1280\begin{cfa}[morekeywords=nomutex]
1281monitor Aint { int cnt; };                                      $\C{// atomic integer counter}$
1282void ?{}( Aint & `nomutex` this ) with( this ) { cnt = 0; } $\C{// constructor}$
1283int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions}$
1284void ?{}( int & this, Aint & `mutex`$\(_{opt}\)$ v ) { this = v.cnt; }
1285int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; }
1286int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$
[aac7197]1287\end{cfa}
[9a72c4d]1288The @Aint@ constructor, @?{}@, uses the \lstinline[morekeywords=nomutex]@nomutex@ qualifier indicating mutual exclusion is unnecessary during construction because an object is inaccessible (private) until after it is initialized.
1289(While a constructor may publish its address into a global variable, doing so generates a race-condition.)
1290The conversion operators for initializing and assigning with a normal integer only need @mutex@, if reading/writing the implementation type is not atomic.
1291Finally, the prefix increment operato, @++?@, is normally @mutex@ to protect the incrementing from race conditions, unless there is an atomic increment instruction for the implementation type.
[604e76d]1292
[9a72c4d]1293The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics, which is similar to the \CC template @std::atomic@.
1294\begin{cfa}
1295Aint x, y, z;
1296++x; ++y; ++z;                                                          $\C{// safe increment by multiple threads}$
1297x = 2; y = 2; z = 2;                                            $\C{// conversions}$
1298int i = x, j = y, k = z;
1299i = x; j = y; k = z;
[aac7197]1300\end{cfa}
[604e76d]1301
[9a72c4d]1302For maximum usability, monitors have \newterm{multi-acquire} semantics allowing a thread to acquire it multiple times without deadlock.
1303\begin{cfa}
[fe3cd36]1304monitor M { ... } m;
1305void foo( M & mutex m ) { ... }                         $\C{// acquire mutual exclusion}$
1306void bar( M & mutex m ) {                                       $\C{// acquire mutual exclusion}$
1307        ... `foo( m );` ...                                             $\C{// reacquire mutual exclusion}$
[604e76d]1308}
[fe3cd36]1309`bar( m );`                                                                     $\C{// nested monitor call}$
[aac7197]1310\end{cfa}
[604e76d]1311
[adb60242]1312The benefit of mandatory monitor qualifiers is self-documentation, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameters is redundant.
1313Instead, the semantics have one qualifier as the default, and the other required.
1314For example, make the safe @mutex@ qualifier the default because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
1315Alternatively, make the unsafe \lstinline[morekeywords=nomutex]@nomutex@ qualifier the default because it is the \emph{normal} parameter semantics while @mutex@ parameters are rare.
[9a72c4d]1316Providing a default qualifier implies knowing whether a parameter is a monitor.
[d5ccbe9]1317Since \CFA relies heavily on traits as an abstraction mechanism, the distinction between a type that is a monitor and a type that looks like a monitor can become blurred.
[9a72c4d]1318For this reason, \CFA requires programmers to identify the kind of parameter with the @mutex@ keyword and uses no keyword to mean \lstinline[morekeywords=nomutex]@nomutex@.
1319
1320The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@.
1321Given:
1322\begin{cfa}
1323monitor M { ... }
1324int f1( M & mutex m );
1325int f2( M * mutex m );
1326int f3( M * mutex m[] );
1327int f4( stack( M * ) & mutex m );
1328\end{cfa}
1329the issue is that some of these parameter types are composed of multiple objects.
1330For @f1@, there is only a single parameter object.
1331Adding indirection in @f2@ still identifies a single object.
1332However, the matrix in @f3@ introduces multiple objects.
1333While shown shortly, multiple acquisition is possible;
1334however array lengths are often unknown in C.
1335This issue is exacerbated in @f4@, where the data structure must be safely traversed to acquire all of its elements.
1336
1337To make the issue tractable, \CFA only acquires one monitor per parameter with at most one level of indirection.
[9f66811]1338However, there is an ambiguity in the C type-system with respects to arrays.
[9a72c4d]1339Is the argument for @f2@ a single object or an array of objects?
1340If it is an array, only the first element of the array is acquired, which seems unsafe;
1341hence, @mutex@ is disallowed for array parameters.
1342\begin{cfa}
1343int f1( M & mutex m );                                          $\C{// allowed: recommended case}$
1344int f2( M * mutex m );                                          $\C{// disallowed: could be an array}$
1345int f3( M mutex m[$\,$] );                                      $\C{// disallowed: array length unknown}$
1346int f4( M ** mutex m );                                         $\C{// disallowed: could be an array}$
1347int f5( M * mutex m[$\,$] );                            $\C{// disallowed: array length unknown}$
1348\end{cfa}
1349% Note, not all array routines have distinct types: @f2@ and @f3@ have the same type, as do @f4@ and @f5@.
1350% However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
1351
1352For object-oriented monitors, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
[9f66811]1353\CFA has no receiver, and hence, must use an explicit mechanism to specify which object acquires mutual exclusion.
[9a72c4d]1354A positive consequence of this design decision is the ability to support multi-monitor routines.
1355\begin{cfa}
1356int f( M & mutex x, M & mutex y );              $\C{// multiple monitor parameter of any type}$
1357M m1, m2;
1358f( m1, m2 );
1359\end{cfa}
1360(While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.)
[e04aec4]1361In practice, writing multi-locking routines that do not deadlock is tricky.
[d5ccbe9]1362Having language support for such a feature is therefore a significant asset for \CFA.
[9a72c4d]1363
[adb60242]1364The capability to acquire multiple locks before entering a critical section is called \newterm{bulk acquire} (see Section~\ref{s:Implementation} for implementation details).
[e04aec4]1365In the previous example, \CFA guarantees the order of acquisition is consistent across calls to different routines using the same monitors as arguments.
[9a72c4d]1366This consistent ordering means acquiring multiple monitors is safe from deadlock.
1367However, users can force the acquiring order.
1368For example, notice the use of @mutex@/\lstinline[morekeywords=nomutex]@nomutex@ and how this affects the acquiring order:
[aac7197]1369\begin{cfa}
[9a72c4d]1370void foo( M & mutex m1, M & mutex m2 );         $\C{// acquire m1 and m2}$
1371void bar( M & mutex m1, M & /* nomutex */ m2 ) { $\C{// acquire m1}$
1372        ... foo( m1, m2 ); ...                                  $\C{// acquire m2}$
[604e76d]1373}
[9a72c4d]1374void baz( M & /* nomutex */ m1, M & mutex m2 ) { $\C{// acquire m2}$
1375        ... foo( m1, m2 ); ...                                  $\C{// acquire m1}$
[604e76d]1376}
[aac7197]1377\end{cfa}
[9a72c4d]1378The multi-acquire semantics allows @bar@ or @baz@ to acquire a monitor lock and reacquire it in @foo@.
1379In the calls to @bar@ and @baz@, the monitors are acquired in opposite order.
[604e76d]1380
[287da46]1381However, such use leads to lock acquiring order problems resulting in deadlock~\cite{Lister77}, where detecting it requires dynamic tracking of monitor calls, and dealing with it requires rollback semantics~\cite{Dice10}.
[adb60242]1382In \CFA, a safety aid is provided by using bulk acquire of all monitors to shared objects, whereas other monitor systems provide no aid.
1383While \CFA provides only a partial solution, it handles many useful cases, \eg:
[aac7197]1384\begin{cfa}
[9f66811]1385monitor BankAccount { ... };
1386void deposit( BankAccount & `mutex` b, int deposit );
1387void transfer( BankAccount & `mutex` my, BankAccount & `mutex` your, int me2you ) {
1388        deposit( my, `-`me2you );                               $\C{// debit}$
1389        deposit( your, me2you );                                $\C{// credit}$
[604e76d]1390}
[aac7197]1391\end{cfa}
[b199e54]1392This example shows a trivial solution to the bank-account transfer problem.
[9a72c4d]1393Without multi- and bulk acquire, the solution to this problem requires careful engineering.
[604e76d]1394
1395
[9f66811]1396\subsection{\protect\lstinline@mutex@ statement}
1397\label{mutex-stmt}
[aac7197]1398
[9a72c4d]1399The monitor call-semantics associate all locking semantics to routines.
1400Like Java, \CFA offers an alternative @mutex@ statement to reduce refactoring and naming.
1401\begin{cquote}
[b199e54]1402\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
[9a72c4d]1403\begin{cfa}
[fe3cd36]1404monitor M { ... };
[604e76d]1405void foo( M & mutex m1, M & mutex m2 ) {
[aac7197]1406        // critical section
[604e76d]1407}
1408void bar( M & m1, M & m2 ) {
1409        foo( m1, m2 );
1410}
[9a72c4d]1411\end{cfa}
1412&
1413\begin{cfa}
1414
[604e76d]1415void bar( M & m1, M & m2 ) {
[9a72c4d]1416        mutex( m1, m2 ) {       // remove refactoring and naming
[aac7197]1417                // critical section
[604e76d]1418        }
1419}
1420
[aac7197]1421\end{cfa}
[b199e54]1422\\
1423\multicolumn{1}{c}{\textbf{routine call}} & \multicolumn{1}{c}{\lstinline@mutex@ \textbf{statement}}
[604e76d]1424\end{tabular}
[9a72c4d]1425\end{cquote}
[604e76d]1426
1427
[e04aec4]1428\section{Scheduling}
1429\label{s:Scheduling}
[9a72c4d]1430
[90cedbdd]1431While monitor mutual-exclusion provides safe access to shared data, the monitor data may indicate that a thread accessing it cannot proceed.
1432For example, Figure~\ref{f:GenericBoundedBuffer} shows a bounded buffer that may be full/empty so produce/consumer threads must block.
[9a72c4d]1433Leaving the monitor and trying again (busy waiting) is impractical for high-level programming.
[adb60242]1434Monitors eliminate busy waiting by providing synchronization to schedule threads needing access to the shared data, where threads block versus spinning.
[90cedbdd]1435Synchronization is generally achieved with internal~\cite{Hoare74} or external~\cite[\S~2.9.2]{uC++} scheduling, where \newterm{scheduling} defines which thread acquires the critical section next.
[08b5a7e]1436\newterm{Internal scheduling} is characterized by each thread entering the monitor and making an individual decision about proceeding or blocking, while \newterm{external scheduling} is characterized by an entering thread making a decision about proceeding for itself and on behalf of other threads attempting entry.
[9a72c4d]1437
[287da46]1438Figure~\ref{f:BBInt} shows a \CFA generic bounded-buffer with internal scheduling, where producers/consumers enter the monitor, see the buffer is full/empty, and block on an appropriate condition lock, @full@/@empty@.
[9a72c4d]1439The @wait@ routine atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the routine's parameter list.
1440The appropriate condition lock is signalled to unblock an opposite kind of thread after an element is inserted/removed from the buffer.
1441Signalling is unconditional, because signalling an empty condition lock does nothing.
[e04aec4]1442
[9a72c4d]1443Signalling semantics cannot have the signaller and signalled thread in the monitor simultaneously, which means:
1444\begin{enumerate}
1445\item
[08b5a7e]1446The signalling thread returns immediately, and the signalled thread continues.
[9a72c4d]1447\item
[08b5a7e]1448The signalling thread continues and the signalled thread is marked for urgent unblocking at the next scheduling point (exit/wait).
[9a72c4d]1449\item
[08b5a7e]1450The signalling thread blocks but is marked for urgrent unblocking at the next scheduling point and the signalled thread continues.
[9a72c4d]1451\end{enumerate}
[287da46]1452The first approach is too restrictive, as it precludes solving a reasonable class of problems, \eg dating service (see Figure~\ref{f:DatingService}).
[9a72c4d]1453\CFA supports the next two semantics as both are useful.
1454Finally, while it is common to store a @condition@ as a field of the monitor, in \CFA, a @condition@ variable can be created/stored independently.
[287da46]1455Furthermore, a condition variable is tied to a \emph{group} of monitors on first use, called \newterm{branding}, which means that using internal scheduling with distinct sets of monitors requires one condition variable per set of monitors.
[604e76d]1456
[9a72c4d]1457\begin{figure}
1458\centering
1459\newbox\myboxA
1460\begin{lrbox}{\myboxA}
[08b5a7e]1461\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[9a72c4d]1462forall( otype T ) { // distribute forall
1463        monitor Buffer {
1464                `condition` full, empty;
1465                int front, back, count;
1466                T elements[10];
1467        };
1468        void ?{}( Buffer(T) & buffer ) with(buffer) {
1469                [front, back, count] = 0;
1470        }
1471
1472        void insert( Buffer(T) & mutex buffer, T elem )
1473                                with(buffer) {
1474                if ( count == 10 ) `wait( empty )`;
1475                // insert elem into buffer
1476                `signal( full )`;
1477        }
1478        T remove( Buffer(T) & mutex buffer ) with(buffer) {
1479                if ( count == 0 ) `wait( full )`;
1480                // remove elem from buffer
1481                `signal( empty )`;
1482                return elem;
1483        }
[604e76d]1484}
[08b5a7e]1485\end{cfa}
[9a72c4d]1486\end{lrbox}
[604e76d]1487
[9a72c4d]1488\newbox\myboxB
1489\begin{lrbox}{\myboxB}
[08b5a7e]1490\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[9a72c4d]1491forall( otype T ) { // distribute forall
1492        monitor Buffer {
1493
1494                int front, back, count;
1495                T elements[10];
1496        };
1497        void ?{}( Buffer(T) & buffer ) with(buffer) {
1498                [front, back, count] = 0;
1499        }
1500        T remove( Buffer(T) & mutex buffer ); // forward
1501        void insert( Buffer(T) & mutex buffer, T elem )
1502                                with(buffer) {
1503                if ( count == 10 ) `waitfor( remove, buffer )`;
1504                // insert elem into buffer
1505
1506        }
1507        T remove( Buffer(T) & mutex buffer ) with(buffer) {
1508                if ( count == 0 ) `waitfor( insert, buffer )`;
1509                // remove elem from buffer
1510
1511                return elem;
1512        }
[604e76d]1513}
[08b5a7e]1514\end{cfa}
[9a72c4d]1515\end{lrbox}
[604e76d]1516
[9a72c4d]1517\subfloat[Internal Scheduling]{\label{f:BBInt}\usebox\myboxA}
1518%\qquad
1519\subfloat[External Scheduling]{\label{f:BBExt}\usebox\myboxB}
1520\caption{Generic Bounded-Buffer}
[08b5a7e]1521\label{f:GenericBoundedBuffer}
[9a72c4d]1522\end{figure}
[604e76d]1523
[9f66811]1524Figure~\ref{f:BBExt} shows a \CFA generic bounded-buffer with external scheduling, where producers/consumers detecting a full/empty buffer block and prevent more producers/consumers from entering the monitor until there is a free/empty slot in the buffer.
[9a72c4d]1525External scheduling is controlled by the @waitfor@ statement, which atomically blocks the calling thread, releases the monitor lock, and restricts the routine calls that can next acquire mutual exclusion.
1526If the buffer is full, only calls to @remove@ can acquire the buffer, and if the buffer is empty, only calls to @insert@ can acquire the buffer.
[adb60242]1527Threads making calls to routines that are currently excluded, block outside of (external to) the monitor on a calling queue, versus blocking on condition queues inside of (internal to) the monitor.
[e04aec4]1528External scheduling allows users to wait for events from other threads without concern of unrelated events occurring.
1529The mechnaism can be done in terms of control flow, \eg Ada @accept@ or \uC @_Accept@, or in terms of data, \eg Go channels.
[6d43cc57]1530While both mechanisms have strengths and weaknesses, this project uses a control-flow mechanism to stay consistent with other language semantics.
1531Two challenges specific to \CFA for external scheduling are loose object-definitions (see Section~\ref{s:LooseObjectDefinitions}) and multiple-monitor routines (see Section~\ref{s:Multi-MonitorScheduling}).
[604e76d]1532
[332d3c2]1533For internal scheduling, non-blocking signalling (as in the producer/consumer example) is used when the signaller is providing the cooperation for a waiting thread;
1534the signaller enters the monitor and changes state, detects a waiting threads that can use the state, performs a non-blocking signal on the condition queue for the waiting thread, and exits the monitor to run concurrently.
[287da46]1535The waiter unblocks next from the urgent queue, uses/takes the state, and exits the monitor.
[332d3c2]1536Blocking signalling is the reverse, where the waiter is providing the cooperation for the signalling thread;
1537the signaller enters the monitor, detects a waiting thread providing the necessary state, performs a blocking signal to place it on the urgent queue and unblock the waiter.
[e04aec4]1538The waiter changes state and exits the monitor, and the signaller unblocks next from the urgent queue to use/take the state.
[332d3c2]1539
[287da46]1540Figure~\ref{f:DatingService} shows a dating service demonstrating non-blocking and blocking signalling.
[332d3c2]1541The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers.
1542A thread blocks until an appropriate partner arrives.
[287da46]1543The complexity is exchanging phone numbers in the monitor because of the mutual-exclusion property.
[35a9e41]1544For 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.
[287da46]1545For signal-block scheduling, the implicit urgent-queue replaces the explict @exchange@-condition and @signal_block@ puts the finding thread on the urgent condition and unblocks the matcher.
[332d3c2]1546
[e04aec4]1547The dating service is an example of a monitor that cannot be written using external scheduling because it requires knowledge of calling parameters to make scheduling decisions, and parameters of waiting threads are unavailable;
1548as well, an arriving thread may not find a partner and must wait, which requires a condition variable, and condition variables imply internal scheduling.
[332d3c2]1549
1550\begin{figure}
1551\centering
1552\newbox\myboxA
1553\begin{lrbox}{\myboxA}
1554\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1555enum { CCodes = 20 };
1556monitor DS {
1557        int GirlPhNo, BoyPhNo;
1558        condition Girls[CCodes], Boys[CCodes];
1559        condition exchange;
1560};
1561int girl( DS & mutex ds, int phNo, int ccode ) {
1562        if ( is_empty( Boys[ccode] ) ) {
1563                wait( Girls[ccode] );
1564                GirlPhNo = phNo;
[adb60242]1565                `signal( exchange );`
[332d3c2]1566        } else {
1567                GirlPhNo = phNo;
[b199e54]1568                `signal( Boys[ccode] );`
[adb60242]1569                `wait( exchange );`
[332d3c2]1570        } // if
1571        return BoyPhNo;
1572}
1573int boy( DS & mutex ds, int phNo, int ccode ) {
1574        // as above with boy/girl interchanged
1575}
1576\end{cfa}
1577\end{lrbox}
1578
1579\newbox\myboxB
1580\begin{lrbox}{\myboxB}
1581\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1582
1583monitor DS {
1584        int GirlPhNo, BoyPhNo;
1585        condition Girls[CCodes], Boys[CCodes];
1586
1587};
1588int girl( DS & mutex ds, int phNo, int ccode ) {
1589        if ( is_empty( Boys[ccode] ) ) { // no compatible
1590                wait( Girls[ccode] ); // wait for boy
1591                GirlPhNo = phNo; // make phone number available
1592
1593        } else {
1594                GirlPhNo = phNo; // make phone number available
[b199e54]1595                `signal_block( Boys[ccode] );` // restart boy
[332d3c2]1596
1597        } // if
1598        return BoyPhNo;
1599}
1600int boy( DS & mutex ds, int phNo, int ccode ) {
1601        // as above with boy/girl interchanged
1602}
1603\end{cfa}
1604\end{lrbox}
1605
1606\subfloat[\lstinline@signal@]{\label{f:DatingSignal}\usebox\myboxA}
1607\qquad
1608\subfloat[\lstinline@signal_block@]{\label{f:DatingSignalBlock}\usebox\myboxB}
1609\caption{Dating service. }
1610\label{f:DatingService}
1611\end{figure}
1612
[08b5a7e]1613Both internal and external scheduling extend to multiple monitors in a natural way.
[90cedbdd]1614\begin{cquote}
1615\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
[aac7197]1616\begin{cfa}
[08b5a7e]1617monitor M { `condition e`; ... };
1618void foo( M & mutex m1, M & mutex m2 ) {
[90cedbdd]1619        ... wait( `e` ); ...   // wait( e, m1, m2 )
[08b5a7e]1620        ... wait( `e, m1` ); ...
1621        ... wait( `e, m2` ); ...
[604e76d]1622}
[90cedbdd]1623\end{cfa}
1624&
1625\begin{cfa}
[08b5a7e]1626void rtn$\(_1\)$( M & mutex m1, M & mutex m2 );
1627void rtn$\(_2\)$( M & mutex m1 );
1628void bar( M & mutex m1, M & mutex m2 ) {
[90cedbdd]1629        ... waitfor( `rtn` ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\), m1, m2 )}$
1630        ... waitfor( `rtn, m1` ); ... // $\LstCommentStyle{waitfor( rtn\(_2\), m1 )}$
[604e76d]1631}
[aac7197]1632\end{cfa}
[90cedbdd]1633\end{tabular}
1634\end{cquote}
[08b5a7e]1635For @wait( e )@, the default semantics is to atomically block the signaller and release all acquired mutex types in the parameter list, \ie @wait( e, m1, m2 )@.
1636To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
1637Wait statically verifies the released monitors are the acquired mutex-parameters so unconditional release is safe.
[90cedbdd]1638Finally, a signaller,
1639\begin{cfa}
1640void baz( M & mutex m1, M & mutex m2 ) {
1641        ... signal( e ); ...
1642}
1643\end{cfa}
[adb60242]1644must have acquired at least the same locks as the waiting thread signalled from the condition queue.
[90cedbdd]1645
1646Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex types in the parameter list, \ie @waitfor( rtn, m1, m2 )@.
[08b5a7e]1647To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn, m1 )@.
[287da46]1648@waitfor@ statically verifies the released monitors are the same as the acquired mutex-parameters of the given routine or routine pointer.
[08b5a7e]1649To statically verify the released monitors match with the accepted routine's mutex parameters, the routine (pointer) prototype must be accessible.
[9f66811]1650% When an overloaded routine appears in an @waitfor@ statement, calls to any routine with that name are accepted.
1651% The rationale is that members with the same name should perform a similar function, and therefore, all should be eligible to accept a call.
[fe3cd36]1652Overloaded routines can be disambiguated using a cast:
[b199e54]1653\begin{cfa}
1654void rtn( M & mutex m );
1655`int` rtn( M & mutex m );
[9f66811]1656waitfor( (`int` (*)( M & mutex ))rtn, m );
[b199e54]1657\end{cfa}
1658
[adb60242]1659The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock.
[aac7197]1660\begin{cfa}
[08b5a7e]1661void foo( M & mutex m1, M & mutex m2 ) {
1662        ... wait( `e, m1` ); ...                                $\C{// release m1, keeping m2 acquired )}$
[e04aec4]1663void bar( M & mutex m1, M & mutex m2 ) {        $\C{// must acquire m1 and m2 )}$
[08b5a7e]1664        ... signal( `e` ); ...
[aac7197]1665\end{cfa}
[e04aec4]1666The @wait@ only releases @m1@ so the signalling thread cannot acquire both @m1@ and @m2@ to  enter @bar@ to get to the @signal@.
[08b5a7e]1667While deadlock issues can occur with multiple/nesting acquisition, this issue results from the fact that locks, and by extension monitors, are not perfectly composable.
[604e76d]1668
[08b5a7e]1669Finally, an important aspect of monitor implementation is barging, \ie can calling threads barge ahead of signalled threads?
[adb60242]1670If barging is allowed, synchronization between a signaller and signallee is difficult, often requiring multiple unblock/block cycles (looping around a wait rechecking if a condition is met).
1671In fact, signals-as-hints is completely opposite from that proposed by Hoare in the seminal paper on monitors:
[08b5a7e]1672\begin{quote}
1673However, 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.
1674It 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}
1675\end{quote}
1676\CFA scheduling \emph{precludes} barging, which simplifies synchronization among threads in the monitor and increases correctness.
[adb60242]1677Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implict form of barging.
[08b5a7e]1678For example, there are no loops in either bounded buffer solution in Figure~\ref{f:GenericBoundedBuffer}.
1679Supporting barging prevention as well as extending internal scheduling to multiple monitors is the main source of complexity in the design and implementation of \CFA concurrency.
[604e76d]1680
1681
[08b5a7e]1682\subsection{Barging Prevention}
[604e76d]1683
[08b5a7e]1684Figure~\ref{f:BargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signalling semantics.
1685The complexity begins at the end of the inner @mutex@ statement, where the semantics of internal scheduling need to be extended for multiple monitors.
1686The problem is that bulk acquire is used in the inner @mutex@ statement where one of the monitors is already acquired.
[90cedbdd]1687When 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.
1688However, both the signalling and waiting thread W1 still need monitor @m1@.
[604e76d]1689
[08b5a7e]1690\begin{figure}
1691\newbox\myboxA
1692\begin{lrbox}{\myboxA}
1693\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1694monitor M m1, m2;
1695condition c;
[90cedbdd]1696mutex( m1 ) { // $\LstCommentStyle{\color{red}outer}$
[08b5a7e]1697        ...
[90cedbdd]1698        mutex( m1, m2 ) { // $\LstCommentStyle{\color{red}inner}$
1699                ... `signal( c )`; ...
[08b5a7e]1700                // m1, m2 acquired
1701        } // $\LstCommentStyle{\color{red}release m2}$
1702        // m1 acquired
1703} // release m1
[aac7197]1704\end{cfa}
[08b5a7e]1705\end{lrbox}
[604e76d]1706
[08b5a7e]1707\newbox\myboxB
1708\begin{lrbox}{\myboxB}
1709\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[604e76d]1710
1711
[08b5a7e]1712mutex( m1 ) {
1713        ...
1714        mutex( m1, m2 ) {
[90cedbdd]1715                ... `wait( c )`; // block and release m1, m2
[08b5a7e]1716                // m1, m2 acquired
1717        } // $\LstCommentStyle{\color{red}release m2}$
1718        // m1 acquired
1719} // release m1
1720\end{cfa}
1721\end{lrbox}
[604e76d]1722
[08b5a7e]1723\newbox\myboxC
1724\begin{lrbox}{\myboxC}
1725\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[604e76d]1726
1727
[90cedbdd]1728mutex( m2 ) {
[08b5a7e]1729        ... `wait( c )`; ...
[90cedbdd]1730        // m2 acquired
1731} // $\LstCommentStyle{\color{red}release m2}$
[604e76d]1732
1733
1734
1735
[aac7197]1736\end{cfa}
[08b5a7e]1737\end{lrbox}
[604e76d]1738
[08b5a7e]1739\begin{cquote}
[90cedbdd]1740\subfloat[Signalling Thread]{\label{f:SignallingThread}\usebox\myboxA}
[08b5a7e]1741\hspace{2\parindentlnth}
[90cedbdd]1742\subfloat[Waiting Thread (W1)]{\label{f:WaitingThread}\usebox\myboxB}
[08b5a7e]1743\hspace{2\parindentlnth}
[90cedbdd]1744\subfloat[Waiting Thread (W2)]{\label{f:OtherWaitingThread}\usebox\myboxC}
[08b5a7e]1745\end{cquote}
1746\caption{Barging Prevention}
1747\label{f:BargingPrevention}
[604e76d]1748\end{figure}
1749
[90cedbdd]1750One scheduling solution is for the signaller to keep ownership of all locks until the last lock is ready to be transferred, because this semantics fits most closely to the behaviour of single-monitor scheduling.
[9f66811]1751However, Figure~\ref{f:OtherWaitingThread} shows this solution is complex depending on other waiters, resulting in options when the signaller finishes the inner mutex-statement.
1752The signaller can retain @m2@ until completion of the outer mutex statement and pass the locks to waiter W1, or it can pass @m2@ to waiter W2 after completing the inner mutex-statement, while continuing to hold @m1@.
[e04aec4]1753In the latter case, waiter W2 must eventually pass @m2@ to waiter W1, which is complex because W1 may have waited before W2, so W2 is unaware of it.
[90cedbdd]1754Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
[d5ccbe9]1755
[90cedbdd]1756While a number of approaches were examined~\cite[\S~4.3]{Delisle18}, the solution chosen for \CFA is a novel techique called \newterm{partial signalling}.
[287da46]1757Signalled threads are moved to the urgent queue and the waiter at the front defines the set of monitors necessary for it to unblock.
[90cedbdd]1758Partial signalling transfers ownership of monitors to the front waiter.
[fe3cd36]1759When the signaller thread exits or waits in the monitor, the front waiter is unblocked if all its monitors are released.
1760The 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.
[90cedbdd]1761
[604e76d]1762
1763\subsection{Loose Object Definitions}
[6d43cc57]1764\label{s:LooseObjectDefinitions}
[e04aec4]1765
[6d43cc57]1766In an object-oriented programming-language, a class includes an exhaustive list of operations.
[adb60242]1767However, new members can be added via static inheritance or dynamic members, \eg JavaScript~\cite{JavaScript}.
[6d43cc57]1768Similarly, monitor routines can be added at any time in \CFA, making it less clear for programmers and more difficult to implement.
[aac7197]1769\begin{cfa}
[fe3cd36]1770monitor M { ... };
[6d43cc57]1771void `f`( M & mutex m );
1772void g( M & mutex m ) { waitfor( `f` ); }       $\C{// clear which f}$
1773void `f`( M & mutex m, int );                           $\C{// different f}$
1774void h( M & mutex m ) { waitfor( `f` ); }       $\C{// unclear which f}$
[aac7197]1775\end{cfa}
[adb60242]1776Hence, the cfa-code for entering a monitor looks like:
[aac7197]1777\begin{cfa}
[6d43cc57]1778if ( $\textrm{\textit{monitor is free}}$ ) $\LstCommentStyle{// \color{red}enter}$
1779else if ( $\textrm{\textit{already own monitor}}$ ) $\LstCommentStyle{// \color{red}continue}$
1780else if ( $\textrm{\textit{monitor accepts me}}$ ) $\LstCommentStyle{// \color{red}enter}$
1781else $\LstCommentStyle{// \color{red}block}$
[aac7197]1782\end{cfa}
[d5ccbe9]1783For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions.
[6d43cc57]1784However, a fast check for \emph{monitor accepts me} is much harder to implement depending on the constraints put on the monitors.
1785Figure~\ref{fig:ClassicalMonitor} shows monitors are often expressed as an entry (calling) queue, some acceptor queues, and an urgent stack/queue.
[604e76d]1786
1787\begin{figure}
1788\centering
[6d43cc57]1789\subfloat[Classical monitor] {
[604e76d]1790\label{fig:ClassicalMonitor}
[6d43cc57]1791{\resizebox{0.45\textwidth}{!}{\input{monitor.pstex_t}}}
[604e76d]1792}% subfloat
[6d43cc57]1793\quad
1794\subfloat[Bulk acquire monitor] {
[604e76d]1795\label{fig:BulkMonitor}
[6d43cc57]1796{\resizebox{0.45\textwidth}{!}{\input{ext_monitor.pstex_t}}}
[604e76d]1797}% subfloat
[6d43cc57]1798\caption{Monitor Implementation}
1799\label{f:MonitorImplementation}
[604e76d]1800\end{figure}
1801
[6d43cc57]1802For a fixed (small) number of mutex routines (\eg 128), the accept check reduces to a bitmask of allowed callers, which can be checked with a single instruction.
1803This approach requires a unique dense ordering of routines with a small upper-bound and the ordering must be consistent across translation units.
1804For object-oriented languages these constraints are common, but \CFA mutex routines can be added in any scope and are only visible in certain translation unit, precluding program-wide dense-ordering among mutex routines.
[604e76d]1805
[6d43cc57]1806Figure~\ref{fig:BulkMonitor} shows the \CFA monitor implementation.
1807The mutex routine called is associated with each thread on the entry queue, while a list of acceptable routines is kept separately.
[287da46]1808The accepted list is a variable-sized array of accepted routine pointers, so the single instruction bitmask comparison is replaced by dereferencing a pointer followed by a (usually short) linear search.
[604e76d]1809
1810
1811\subsection{Multi-Monitor Scheduling}
[6d43cc57]1812\label{s:Multi-MonitorScheduling}
[604e76d]1813
[287da46]1814External scheduling, like internal scheduling, becomes significantly more complex for multi-monitor semantics.
1815Even in the simplest case, new semantics needs to be established.
[fe3cd36]1816\newpage
[aac7197]1817\begin{cfa}
[fe3cd36]1818monitor M { ... };
[6d43cc57]1819void f( M & mutex m1 );
1820void g( M & mutex m1, M & mutex m2 ) {
[b199e54]1821        waitfor( f );                                                   $\C{\color{red}// pass m1 or m2 to f?}$
[604e76d]1822}
[aac7197]1823\end{cfa}
[6d43cc57]1824The solution is for the programmer to disambiguate:
[aac7197]1825\begin{cfa}
[b199e54]1826        waitfor( f, m2 );                                               $\C{\color{red}// wait for call to f with argument m2}$
[aac7197]1827\end{cfa}
[9f66811]1828Both locks are acquired by routine @g@, so when routine @f@ is called, the lock for monitor @m2@ is passed from @g@ to @f@, while @g@ still holds lock @m1@.
[6d43cc57]1829This behaviour can be extended to the multi-monitor @waitfor@ statement.
[aac7197]1830\begin{cfa}
[fe3cd36]1831monitor M { ... };
[6d43cc57]1832void f( M & mutex m1, M & mutex m2 );
1833void g( M & mutex m1, M & mutex m2 ) {
[b199e54]1834        waitfor( f, m1, m2 );                                   $\C{\color{red}// wait for call to f with arguments m1 and m2}$
[604e76d]1835}
[aac7197]1836\end{cfa}
[287da46]1837Again, the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired by the accepting routine.
[adb60242]1838Also, the order of the monitors in a @waitfor@ statement is unimportant.
[604e76d]1839
[adb60242]1840Figure~\ref{f:UnmatchedMutexSets} shows an example where, for internal and external scheduling with multiple monitors, a signalling or accepting thread must match exactly, \ie partial matching results in waiting.
1841For both examples, the set of monitors is disjoint so unblocking is impossible.
1842
1843\begin{figure}
[b199e54]1844\lstDeleteShortInline@%
1845\begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
[aac7197]1846\begin{cfa}
[b199e54]1847monitor M1 {} m11, m12;
1848monitor M2 {} m2;
1849condition c;
1850void f( M1 & mutex m1, M2 & mutex m2 ) {
1851        signal( c );
[604e76d]1852}
[b199e54]1853void g( M1 & mutex m1, M2 & mutex m2 ) {
1854        wait( c );
[604e76d]1855}
[adb60242]1856g( `m11`, m2 ); // block on wait
[b199e54]1857f( `m12`, m2 ); // cannot fulfil
[aac7197]1858\end{cfa}
[b199e54]1859&
1860\begin{cfa}
1861monitor M1 {} m11, m12;
1862monitor M2 {} m2;
[604e76d]1863
[b199e54]1864void f( M1 & mutex m1, M2 & mutex m2 ) {
[604e76d]1865
[b199e54]1866}
1867void g( M1 & mutex m1, M2 & mutex m2 ) {
1868        waitfor( f, m1, m2 );
1869}
1870g( `m11`, m2 ); // block on accept
1871f( `m12`, m2 ); // cannot fulfil
1872\end{cfa}
1873\end{tabular}
1874\lstMakeShortInline@%
[adb60242]1875\caption{Unmatched \protect\lstinline@mutex@ sets}
1876\label{f:UnmatchedMutexSets}
1877\end{figure}
[604e76d]1878
1879
[b199e54]1880\subsection{Extended \protect\lstinline@waitfor@}
[604e76d]1881
[adb60242]1882Figure~\ref{f:ExtendedWaitfor} show the extended form of the @waitfor@ statement to conditionally accept one of a group of mutex routines, with a specific action to be performed \emph{after} the mutex routine finishes.
1883For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding member(s) must exist.
1884The \emph{conditional-expression} of a @when@ may call a routine, but the routine must not block or context switch.
1885If there are multiple acceptable mutex calls, selection occurs top-to-bottom (prioritized) in the @waitfor@ clauses, whereas some programming languages with similar mechanisms accept non-deterministically for this case, \eg Go \lstinline[morekeywords=select]@select@.
1886If some accept guards are true and there are no outstanding calls to these members, the acceptor is accept-blocked until a call to one of these members is made.
1887If 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.
1888Hence, the terminating @else@ clause allows a conditional attempt to accept a call without blocking.
1889If there is a @timeout@ clause, it provides an upper bound on waiting.
1890If both a @timeout@ clause and an @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered.
1891In all cases, the statement following is executed \emph{after} a clause is executed to know which of the clauses executed.
1892
1893\begin{figure}
[b199e54]1894\begin{cfa}
1895`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
1896        waitfor( $\emph{mutex-member-name}$ )
1897                $\emph{statement}$                                      $\C{// action after call}$
1898`or` `when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
1899        waitfor( $\emph{mutex-member-name}$ )
1900                $\emph{statement}$                                      $\C{// action after call}$
1901`or`    ...                                                                     $\C{// list of waitfor clauses}$
1902`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
1903        `timeout`                                                               $\C{// optional terminating timeout clause}$
1904                $\emph{statement}$                                      $\C{// action after timeout}$
1905`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
1906        `else`                                                                  $\C{// optional terminating clause}$
1907                $\emph{statement}$                                      $\C{// action when no immediate calls}$
[aac7197]1908\end{cfa}
[adb60242]1909\caption{Extended \protect\lstinline@waitfor@}
1910\label{f:ExtendedWaitfor}
1911\end{figure}
[604e76d]1912
[287da46]1913Note, a group of conditional @waitfor@ clauses is \emph{not} the same as a group of @if@ statements, e.g.:
[b199e54]1914\begin{cfa}
1915if ( C1 ) waitfor( mem1 );                       when ( C1 ) waitfor( mem1 );
1916else if ( C2 ) waitfor( mem2 );         or when ( C2 ) waitfor( mem2 );
1917\end{cfa}
1918The left example accepts only @mem1@ if @C1@ is true or only @mem2@ if @C2@ is true.
1919The right example accepts either @mem1@ or @mem2@ if @C1@ and @C2@ are true.
[604e76d]1920
[287da46]1921An interesting use of @waitfor@ is accepting the @mutex@ destructor to know when an object is deallocated.
[766309d]1922\begin{cfa}
[b199e54]1923void insert( Buffer(T) & mutex buffer, T elem ) with( buffer ) {
[adb60242]1924        if ( count == 10 )
[b199e54]1925                waitfor( remove, buffer ) {
[adb60242]1926                        // insert elem into buffer
[b199e54]1927                } or `waitfor( ^?{}, buffer )` throw insertFail;
1928}
1929\end{cfa}
[287da46]1930When the buffer is deallocated, the current waiter is unblocked and informed, so it can perform an appropriate action.
1931However, the basic @waitfor@ semantics do not support this functionality, since using an object after its destructor is called is undefined.
[9f66811]1932Therefore, to make this useful capability work, the semantics for accepting the destructor is the same as @signal@, \ie the call to the destructor is placed on the urgent queue and the acceptor continues execution, which throws an exception to the acceptor and then the caller is unblocked from the urgent queue to deallocate the object.
[b199e54]1933Accepting the destructor is an idiomatic way to terminate a thread in \CFA.
[604e76d]1934
1935
[b199e54]1936\subsection{\protect\lstinline@mutex@ Threads}
[604e76d]1937
[287da46]1938Threads in \CFA are monitors to allow direct communication among threads, \ie threads can have mutex routines that are called by other threads.
1939Hence, all monitor features are available when using threads.
[9f66811]1940The following shows an example of two threads directly calling each other and accepting calls from each other in a cycle.
[b199e54]1941\begin{cfa}
1942thread Ping {} pi;
1943thread Pong {} po;
1944void ping( Ping & mutex ) {}
1945void pong( Pong & mutex ) {}
1946int main() {}
1947\end{cfa}
[9f66811]1948\vspace{-0.8\baselineskip}
1949\begin{cquote}
[b199e54]1950\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
1951\begin{cfa}
1952void main( Ping & pi ) {
1953        for ( int i = 0; i < 10; i += 1 ) {
1954                `waitfor( ping, pi );`
1955                `pong( po );`
[604e76d]1956        }
1957}
[aac7197]1958\end{cfa}
[b199e54]1959&
1960\begin{cfa}
1961void main( Pong & po ) {
1962        for ( int i = 0; i < 10; i += 1 ) {
1963                `ping( pi );`
1964                `waitfor( pong, po );`
[604e76d]1965        }
1966}
[aac7197]1967\end{cfa}
[b199e54]1968\end{tabular}
1969\end{cquote}
[9f66811]1970% \lstMakeShortInline@%
1971% \caption{Threads ping/pong using external scheduling}
1972% \label{f:pingpong}
1973% \end{figure}
1974Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start (and possibly complete) before the program main starts.
1975
1976
1977\subsection{Low-level Locks}
1978
1979For 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.
1980
[604e76d]1981
1982\section{Parallelism}
[6d43cc57]1983
[b199e54]1984Historically, computer performance was about processor speeds.
[9f66811]1985However, with heat dissipation being a direct consequence of speed increase, parallelism is the new source for increased performance~\cite{Sutter05, Sutter05b}.
[b199e54]1986Now, high-performance applications must care about parallelism, which requires concurrency.
1987The lowest-level approach of parallelism is to use \newterm{kernel threads} in combination with semantics like @fork@, @join@, \etc.
[287da46]1988However, kernel threads are better as an implementation tool because of complexity and higher cost.
1989Therefore, different abstractions are often layered onto kernel threads to simplify them, \eg pthreads.
[6d43cc57]1990
1991
[b199e54]1992\subsection{User Threads with Preemption}
[604e76d]1993
[b199e54]1994A direct improvement on kernel threads is user threads, \eg Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
[287da46]1995This approach provides an interface that matches the language paradigms, more control over concurrency by the language runtime, and an abstract (and portable) interface to the underlying kernel threads across operating systems.
[b199e54]1996In many cases, user threads can be used on a much larger scale (100,000 threads).
[287da46]1997Like kernel threads, user threads support preemption, which maximizes nondeterminism, but introduces the same concurrency errors: race, livelock, starvation, and deadlock.
1998\CFA adopts user-threads as they represent the truest realization of concurrency and can build any other concurrency approach, \eg thread pools and actors~\cite{Actors}.
[604e76d]1999
[6d43cc57]2000
[b199e54]2001\subsection{User Threads without Preemption (Fiber)}
2002\label{s:fibers}
[6d43cc57]2003
[adb60242]2004A variant of user thread is \newterm{fibers}, which removes preemption, \eg Go~\cite{Go} @goroutine@s.
2005Like functional programming, which removes mutation and its associated problems, removing preemption from concurrency reduces nondeterminism, making race and deadlock errors more difficult to generate.
[b199e54]2006However, preemption is necessary for concurrency that relies on spinning, so there are a class of problems that cannot be programmed without preemption.
[604e76d]2007
2008
[b199e54]2009\subsection{Thread Pools}
[6d43cc57]2010
[9f66811]2011In contrast to direct threading is indirect \newterm{thread pools}, where small jobs (work units) are inserted into a work pool for execution.
[b199e54]2012If the jobs are dependent, \ie interact, there is an implicit/explicit dependency graph that ties them together.
2013While removing direct concurrency, and hence the amount of context switching, thread pools significantly limit the interaction that can occur among jobs.
[9f66811]2014Indeed, jobs should not block because that also blocks the underlying thread, which effectively means the CPU utilization, and therefore throughput, suffers.
[b199e54]2015While 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.
2016As well, concurrency errors return, which threads pools are suppose to mitigate.
[6d43cc57]2017
[604e76d]2018
[b199e54]2019\section{\protect\CFA Runtime Structure}
[604e76d]2020
[b199e54]2021Figure~\ref{f:RunTimeStructure} illustrates the runtime structure of a \CFA program.
[287da46]2022In 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.
[b199e54]2023An executing thread is illustrated by its containment in a processor.
[6d43cc57]2024
[604e76d]2025\begin{figure}
[b199e54]2026\centering
2027\input{RunTimeStructure}
2028\caption{\CFA Runtime Structure}
2029\label{f:RunTimeStructure}
[604e76d]2030\end{figure}
2031
[6d43cc57]2032
[b199e54]2033\subsection{Cluster}
2034\label{s:RuntimeStructureCluster}
[604e76d]2035
[287da46]2036A \newterm{cluster} is a collection of threads and virtual processors (abstract kernel-thread) that execute the threads (like a virtual machine).
[b199e54]2037The purpose of a cluster is to control the amount of parallelism that is possible among threads, plus scheduling and other execution defaults.
2038The default cluster-scheduler is single-queue multi-server, which provides automatic load-balancing of threads on processors.
2039However, the scheduler is pluggable, supporting alternative schedulers.
2040If several clusters exist, both threads and virtual processors, can be explicitly migrated from one cluster to another.
2041No automatic load balancing among clusters is performed by \CFA.
[604e76d]2042
[287da46]2043When 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.
2044The user cluster is created to contain the application user-threads.
[b199e54]2045Having all threads execute on the one cluster often maximizes utilization of processors, which minimizes runtime.
[9f66811]2046However, because of limitations of the underlying operating system, heterogeneous hardware, or scheduling requirements (real-time), multiple clusters are sometimes necessary.
[6d43cc57]2047
2048
[b199e54]2049\subsection{Virtual Processor}
2050\label{s:RuntimeStructureProcessor}
[604e76d]2051
[b199e54]2052A virtual processor is implemented by a kernel thread (\eg UNIX process), which is subsequently scheduled for execution on a hardware processor by the underlying operating system.
2053Programs may use more virtual processors than hardware processors.
2054On a multiprocessor, kernel threads are distributed across the hardware processors resulting in virtual processors executing in parallel.
[287da46]2055(It is possible to use affinity to lock a virtual processor onto a particular hardware processor~\cite{affinityLinux, affinityWindows, affinityFreebsd, affinityNetbsd, affinityMacosx}, which is used when caching issues occur or for heterogeneous hardware processors.)
[b199e54]2056The \CFA runtime attempts to block unused processors and unblock processors as the system load increases;
2057balancing the workload with processors is difficult.
2058Preemption occurs on virtual processors rather than user threads, via operating-system interrupts.
2059Thus virtual processors execute user threads, where preemption frequency applies to a virtual processor, so preemption occurs randomly across the executed user threads.
2060Turning off preemption transforms user threads into fibers.
[6d43cc57]2061
2062
[b199e54]2063\subsection{Debug Kernel}
[604e76d]2064
[b199e54]2065There are two versions of the \CFA runtime kernel: debug and non-debug.
2066The 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.
2067After a program is debugged, the non-debugging version can be used to decrease space and increase performance.
[6d43cc57]2068
2069
[b199e54]2070\section{Implementation}
[adb60242]2071\label{s:Implementation}
[604e76d]2072
[b199e54]2073Currently, \CFA has fixed-sized stacks, where the stack size can be set at coroutine/thread creation but with no subsequent growth.
2074Schemes exist for dynamic stack-growth, such as stack copying and chained stacks.
[adb60242]2075However, stack copying requires pointer adjustment to items on the stack, which is impossible without some form of garbage collection.
[b199e54]2076As well, chained stacks require all modules be recompiled to use this feature, which breaks backward compatibility with existing C libraries.
2077In the long term, it is likely C libraries will migrate to stack chaining to support concurrency, at only a minimal cost to sequential programs.
[287da46]2078Nevertheless, experience teaching \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue in most concurrent programs.
[6d43cc57]2079
[b199e54]2080A primary implementation challenge is avoiding contention from dynamically allocating memory because of bulk acquire, \eg the internal-scheduling design is (almost) free of allocations.
2081All 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.
2082Furthermore, several bulk-acquire operations need a variable amount of memory.
2083This 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.
[6d43cc57]2084
[9f66811]2085In \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.
[b199e54]2086When a mutex call is made, pointers to the concerned monitors are aggregated into a variable-length array and sorted.
[2ebcb28]2087This array persists for the entire duration of the mutual exclusion and is used extensively for synchronization operations.
[d5ccbe9]2088
[adb60242]2089To improve performance and simplicity, context switching occurs inside a routine call, so only callee-saved registers are copied onto the stack and then the stack register is switched;
[b199e54]2090the corresponding registers are then restored for the other context.
2091Note, the instruction pointer is untouched since the context switch is always inside the same routine.
2092Unlike coroutines, threads do not context switch among each other;
2093they context switch to the cluster scheduler.
2094This method is a 2-step context-switch and provides a clear distinction between user and kernel code, where scheduling and other system operations happen.
2095The alternative 1-step context-switch uses the \emph{from} thread's stack to schedule and then context-switches directly to the \emph{to} thread's stack.
[adb60242]2096Experimental results (not presented) show the performance of these two approaches is virtually equivalent, because both approaches are dominated by locking to prevent a race condition.
[b199e54]2097
2098All kernel threads (@pthreads@) created a stack.
2099Each \CFA virtual processor is implemented as a coroutine and these coroutines run directly on the kernel-thread stack, effectively stealing this stack.
2100The exception to this rule is the program main, \ie the initial kernel thread that is given to any program.
2101In 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.
2102
2103Finally, an important aspect for a complete threading system is preemption, which introduces extra non-determinism via transparent interleaving, rather than cooperation among threads for proper scheduling and processor fairness from long-running threads.
[adb60242]2104Because preemption frequency is usually long (1 millisecond) performance cost is negligible.
[b199e54]2105Preemption is normally handled by setting a count-down timer on each virtual processor.
2106When the timer expires, an interrupt is delivered, and the interrupt handler resets the count-down timer, and if the virtual processor is executing in user code, the signal handler performs a user-level context-switch, or if executing in the language runtime-kernel, the preemption is ignored or rolled forward to the point where the runtime kernel context switches back to user code.
2107Multiple signal handlers may be pending.
[9f66811]2108When 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.
[b199e54]2109The 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;
[9f66811]2110therefore, the same signal mask is required for all virtual processors in a cluster.
[b199e54]2111
[287da46]2112However, on current UNIX systems:
[604e76d]2113\begin{quote}
[d5ccbe9]2114A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
2115If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
[604e76d]2116SIGNAL(7) - Linux Programmer's Manual
2117\end{quote}
[b199e54]2118Hence, the timer-expiry signal, which is generated \emph{externally} by the UNIX kernel to the UNIX process, is delivered to any of its UNIX subprocesses (kernel threads).
[287da46]2119To ensure each virtual processor receives its own preemption signals, a discrete-event simulation is run on a special virtual processor, and only it sets and receives timer events.
[b199e54]2120Virtual processors register an expiration time with the discrete-event simulator, which is inserted in sorted order.
2121The simulation sets the count-down timer to the value at the head of the event list, and when the timer expires, all events less than or equal to the current time are processed.
2122Processing a preemption event sends an \emph{internal} @SIGUSR1@ signal to the registered virtual processor, which is always delivered to that processor.
[6d43cc57]2123
[604e76d]2124
[b199e54]2125\section{Performance}
2126\label{results}
[604e76d]2127
[b199e54]2128To verify the implementation of the \CFA runtime, a series of microbenchmarks are performed comparing \CFA with other widely used programming languages with concurrency.
2129Table~\ref{t:machine} shows the specifications of the computer used to run the benchmarks, and the versions of the software used in the comparison.
[604e76d]2130
[287da46]2131\begin{table}
[b199e54]2132\centering
2133\caption{Experiment environment}
2134\label{t:machine}
[604e76d]2135
[b199e54]2136\begin{tabular}{|l|r||l|r|}
[604e76d]2137\hline
[b199e54]2138Architecture            & x86\_64                               & NUMA node(s)  & 8 \\
[604e76d]2139\hline
[b199e54]2140CPU op-mode(s)          & 32-bit, 64-bit                & Model name    & AMD Opteron\texttrademark\ Processor 6380 \\
[604e76d]2141\hline
[b199e54]2142Byte Order                      & Little Endian                 & CPU Freq              & 2.5 GHz \\
[604e76d]2143\hline
[b199e54]2144CPU(s)                          & 64                                    & L1d cache     & 16 KiB \\
[604e76d]2145\hline
[b199e54]2146Thread(s) per core      & 2                                     & L1i cache     & 64 KiB \\
[604e76d]2147\hline
[b199e54]2148Core(s) per socket      & 8                                     & L2 cache              & 2048 KiB \\
[604e76d]2149\hline
[b199e54]2150Socket(s)                       & 4                                     & L3 cache              & 6144 KiB \\
[604e76d]2151\hline
2152\hline
[b199e54]2153Operating system        & Ubuntu 16.04.3 LTS    & Kernel                & Linux 4.4-97-generic \\
[604e76d]2154\hline
[b199e54]2155gcc                                     & 6.3                                   & \CFA                  & 1.0.0 \\
[604e76d]2156\hline
[b199e54]2157Java                            & OpenJDK-9                     & Go                    & 1.9.2 \\
[604e76d]2158\hline
2159\end{tabular}
2160\end{table}
2161
[b199e54]2162All benchmarks are run using the following harness:
[aac7197]2163\begin{cfa}
[b199e54]2164unsigned int N = 10_000_000;
[64188cc]2165#define BENCH( run ) Time before = getTimeNsec(); run; Duration result = (getTimeNsec() - before) / N;
[b199e54]2166\end{cfa}
2167The method used to get time is @clock_gettime( CLOCK_REALTIME )@.
[2ebcb28]2168Each benchmark is performed @N@ times, where @N@ varies depending on the benchmark;
2169the total time is divided by @N@ to obtain the average time for a benchmark.
[287da46]2170All omitted tests for other languages are functionally identical to the shown \CFA test.
[b199e54]2171
2172
2173\paragraph{Context-Switching}
2174
2175In procedural programming, the cost of a routine call is important as modularization (refactoring) increases.
2176(In many cases, a compiler inlines routine calls to eliminate this cost.)
2177Similarly, when modularization extends to coroutines/tasks, the time for a context switch becomes a relevant factor.
2178The coroutine context-switch is 2-step using resume/suspend, \ie from resumer to suspender and from suspender to resumer.
2179The thread context switch is 2-step using yield, \ie enter and return from the runtime kernel.
2180Figure~\ref{f:ctx-switch} shows the code for coroutines/threads with all results in Table~\ref{tab:ctx-switch}.
2181The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling.
2182
2183\begin{figure}
2184\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2185
2186\newbox\myboxA
2187\begin{lrbox}{\myboxA}
2188\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2189coroutine C {} c;
2190void main( C & ) { for ( ;; ) { @suspend();@ } }
[604e76d]2191int main() {
2192        BENCH(
[64188cc]2193                for ( size_t i = 0; i < N; i += 1 ) { @resume( c );@ } )
[200fcb3]2194        sout | result`ns;
[604e76d]2195}
[aac7197]2196\end{cfa}
[b199e54]2197\end{lrbox}
[604e76d]2198
[b199e54]2199\newbox\myboxB
2200\begin{lrbox}{\myboxB}
2201\begin{cfa}[aboveskip=0pt,belowskip=0pt]
[604e76d]2202
2203
2204int main() {
2205        BENCH(
[64188cc]2206                for ( size_t i = 0; i < N; i += 1 ) { @yield();@ } )
[200fcb3]2207        sout | result`ns;
[604e76d]2208}
[aac7197]2209\end{cfa}
[b199e54]2210\end{lrbox}
2211
[287da46]2212\subfloat[Coroutine]{\usebox\myboxA}
[b199e54]2213\quad
[287da46]2214\subfloat[Thread]{\usebox\myboxB}
[64188cc]2215\captionof{figure}{\CFA context-switch benchmark}
[b199e54]2216\label{f:ctx-switch}
[604e76d]2217
[b199e54]2218\centering
2219
[64188cc]2220\captionof{table}{Context switch comparison (nanoseconds)}
2221\label{tab:ctx-switch}
2222\bigskip
[b199e54]2223\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
[604e76d]2224\cline{2-4}
[b199e54]2225\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
[604e76d]2226\hline
[35a9e41]2227Kernel Thread   & 333.5 & 332.96        & 4.1 \\
2228\CFA Coroutine  & 49            & 48.68 & 0.47    \\
2229\CFA Thread             & 105           & 105.57        & 1.37 \\
2230\uC Coroutine   & 44            & 44            & 0 \\
2231\uC Thread              & 100           & 99.29 & 0.96 \\
2232Goroutine               & 145           & 147.25        & 4.15 \\
2233Java Thread             & 373.5 & 375.14        & 8.72 \\
[604e76d]2234\hline
2235\end{tabular}
[b199e54]2236
[64188cc]2237\bigskip
2238\bigskip
[604e76d]2239
[b199e54]2240\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2241\begin{cfa}
[fe3cd36]2242monitor M { ... } m1/*, m2, m3, m4*/;
[b199e54]2243void __attribute__((noinline)) do_call( M & mutex m/*, m2, m3, m4*/ ) {}
[604e76d]2244int main() {
[64188cc]2245        BENCH( for( size_t i = 0; i < N; i += 1 ) { @do_call( m1/*, m2, m3, m4*/ );@ } )
[200fcb3]2246        sout | result`ns;
[604e76d]2247}
[aac7197]2248\end{cfa}
[64188cc]2249\captionof{figure}{\CFA acquire/release mutex benchmark}
[b199e54]2250\label{f:mutex}
[604e76d]2251
[b199e54]2252\centering
[64188cc]2253
2254\captionof{table}{Mutex comparison (nanoseconds)}
[b199e54]2255\label{tab:mutex}
[64188cc]2256\bigskip
[b199e54]2257
2258\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
[604e76d]2259\cline{2-4}
[b199e54]2260\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
[604e76d]2261\hline
[35a9e41]2262C routine                                       & 2             & 2             & 0    \\
2263FetchAdd + FetchSub                     & 26            & 26            & 0    \\
2264Pthreads Mutex Lock                     & 31            & 31.71 & 0.97 \\
2265\uC @monitor@ member routine            & 31            & 31            & 0    \\
2266\CFA @mutex@ routine, 1 argument        & 46            & 46.68 & 0.93  \\
2267\CFA @mutex@ routine, 2 argument        & 84            & 85.36 & 1.99 \\
2268\CFA @mutex@ routine, 4 argument        & 158           & 161           & 4.22 \\
2269Java synchronized routine               & 27.5  & 29.79 & 2.93  \\
[604e76d]2270\hline
2271\end{tabular}
[64188cc]2272\end{figure}
2273
2274
2275\paragraph{Mutual-Exclusion}
2276
2277Mutual exclusion is measured by entering/leaving a critical section.
2278For monitors, entering and leaving a monitor routine is measured.
2279Figure~\ref{f:mutex} shows the code for \CFA with all results in Table~\ref{tab:mutex}.
2280To put the results in context, the cost of entering a non-inline routine and the cost of acquiring and releasing a @pthread_mutex@ lock is also measured.
2281Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
[604e76d]2282
2283
[b199e54]2284\paragraph{Internal Scheduling}
[604e76d]2285
[b199e54]2286Internal scheduling is measured by waiting on and signalling a condition variable.
2287Figure~\ref{f:int-sched} shows the code for \CFA, with results in Table~\ref{tab:int-sched}.
2288Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
[9f66811]2289Java scheduling is significantly greater because the benchmark explicitly creates multiple thread in order to prevent the JIT from making the program sequential, \ie removing all locking.
[604e76d]2290
[64188cc]2291\begin{figure}
[b199e54]2292\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2293\begin{cfa}
2294volatile int go = 0;
2295condition c;
[fe3cd36]2296monitor M { ... } m;
[b199e54]2297void __attribute__((noinline)) do_call( M & mutex a1 ) { signal( c ); }
[604e76d]2298thread T {};
2299void main( T & this ) {
[b199e54]2300        while ( go == 0 ) { yield(); }  // wait for other thread to start
2301        while ( go == 1 ) { @do_call( m );@ }
[604e76d]2302}
[b199e54]2303int  __attribute__((noinline)) do_wait( M & mutex m ) {
2304        go = 1; // continue other thread
[64188cc]2305        BENCH( for ( size_t i = 0; i < N; i += 1 ) { @wait( c );@ } );
[b199e54]2306        go = 0; // stop other thread
[200fcb3]2307        sout | result`ns;
[604e76d]2308}
2309int main() {
2310        T t;
[b199e54]2311        do_wait( m );
[604e76d]2312}
[aac7197]2313\end{cfa}
[2ebcb28]2314\captionof{figure}{\CFA Internal-scheduling benchmark}
[b199e54]2315\label{f:int-sched}
[604e76d]2316
[b199e54]2317\centering
[2ebcb28]2318\captionof{table}{Internal-scheduling comparison (nanoseconds)}
[b199e54]2319\label{tab:int-sched}
[64188cc]2320\bigskip
2321
[b199e54]2322\begin{tabular}{|r|*{3}{D{.}{.}{5.2}|}}
[604e76d]2323\cline{2-4}
[b199e54]2324\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
[604e76d]2325\hline
[35a9e41]2326Pthreads Condition Variable             & 6005  & 5681.43       & 835.45 \\
2327\uC @signal@                                    & 324           & 325.54        & 3,02   \\
2328\CFA @signal@, 1 @monitor@              & 368.5         & 370.61        & 4.77   \\
2329\CFA @signal@, 2 @monitor@              & 467           & 470.5 & 6.79   \\
2330\CFA @signal@, 4 @monitor@              & 700.5         & 702.46        & 7.23  \\
2331Java @notify@                                   & 15471 & 172511        & 5689 \\
[604e76d]2332\hline
2333\end{tabular}
[64188cc]2334\end{figure}
[b199e54]2335
[604e76d]2336
[b199e54]2337\paragraph{External Scheduling}
[604e76d]2338
[b199e54]2339External scheduling is measured by accepting a call using the @waitfor@ statement (@_Accept@ in \uC).
2340Figure~\ref{f:ext-sched} shows the code for \CFA, with results in Table~\ref{tab:ext-sched}.
2341Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2342
[604e76d]2343\begin{figure}
[b199e54]2344\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2345\begin{cfa}
[604e76d]2346volatile int go = 0;
[fe3cd36]2347monitor M { ... } m;
[604e76d]2348thread T {};
[b199e54]2349void __attribute__((noinline)) do_call( M & mutex ) {}
2350void main( T & ) {
2351        while ( go == 0 ) { yield(); }  // wait for other thread to start
2352        while ( go == 1 ) { @do_call( m );@ }
[604e76d]2353}
[b199e54]2354int __attribute__((noinline)) do_wait( M & mutex m ) {
[64188cc]2355        go = 1; // continue other thread
2356        BENCH( for ( size_t i = 0; i < N; i += 1 ) { @waitfor( do_call, m );@ } )
2357        go = 0; // stop other thread
[200fcb3]2358        sout | result`ns;
[604e76d]2359}
2360int main() {
2361        T t;
[b199e54]2362        do_wait( m );
[604e76d]2363}
[aac7197]2364\end{cfa}
[2ebcb28]2365\captionof{figure}{\CFA external-scheduling benchmark}
[b199e54]2366\label{f:ext-sched}
[604e76d]2367
[b199e54]2368\centering
[64188cc]2369
[2ebcb28]2370\captionof{table}{External-scheduling comparison (nanoseconds)}
[b199e54]2371\label{tab:ext-sched}
[64188cc]2372\bigskip
[b199e54]2373\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
[604e76d]2374\cline{2-4}
[b199e54]2375\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
[604e76d]2376\hline
[35a9e41]2377\uC @_Accept@                           & 358           & 359.11        & 2.53  \\
2378\CFA @waitfor@, 1 @monitor@     & 359           & 360.93        & 4.07  \\
2379\CFA @waitfor@, 2 @monitor@     & 450           & 449.39        & 6.62  \\
2380\CFA @waitfor@, 4 @monitor@     & 652           & 655.64        & 7.73 \\
[604e76d]2381\hline
2382\end{tabular}
2383
[64188cc]2384\bigskip
2385\medskip
[604e76d]2386
[b199e54]2387\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
[aac7197]2388\begin{cfa}
[b199e54]2389thread MyThread {};
2390void main( MyThread & ) {}
[604e76d]2391int main() {
[64188cc]2392        BENCH( for ( size_t i = 0; i < N; i += 1 ) { @MyThread m;@ } )
[200fcb3]2393        sout | result`ns;
[604e76d]2394}
[aac7197]2395\end{cfa}
[2ebcb28]2396\captionof{figure}{\CFA object-creation benchmark}
[0a89a8f]2397\label{f:creation}
[604e76d]2398
[b199e54]2399\centering
[64188cc]2400
2401\captionof{table}{Creation comparison (nanoseconds)}
[b199e54]2402\label{tab:creation}
[64188cc]2403\bigskip
2404
[b199e54]2405\begin{tabular}{|r|*{3}{D{.}{.}{5.2}|}}
[604e76d]2406\cline{2-4}
[b199e54]2407\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} & \multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
[604e76d]2408\hline
[35a9e41]2409Pthreads                                & 28091         & 28073.39      & 163.1  \\
2410\CFA Coroutine Lazy             & 6                     & 6.07          & 0.26   \\
2411\CFA Coroutine Eager    & 520           & 520.61        & 2.04   \\
2412\CFA Thread                             & 2032  & 2016.29       & 112.07  \\
2413\uC Coroutine                   & 106           & 107.36        & 1.47   \\
2414\uC Thread                              & 536.5 & 537.07        & 4.64   \\
2415Goroutine                               & 3103  & 3086.29       & 90.25  \\
2416Java Thread                             & 103416.5      & 103732.29     & 1137 \\
[604e76d]2417\hline
2418\end{tabular}
[64188cc]2419\end{figure}
2420
2421
2422\paragraph{Object Creation}
2423
2424Object creation is measured by creating/deleting the specific kind of concurrent object.
2425Figure~\ref{f:creation} shows the code for \CFA, with results in Table~\ref{tab:creation}.
2426The only note here is that the call stacks of \CFA coroutines are lazily created, therefore without priming the coroutine to force stack creation, the creation cost is artificially low.
[604e76d]2427
2428
2429\section{Conclusion}
[b199e54]2430
[adb60242]2431This paper demonstrates a concurrency API that is simple, efficient, and able to build higher-level concurrency features.
[b199e54]2432The approach provides concurrency based on a preemptive M:N user-level threading-system, executing in clusters, which encapsulate scheduling of work on multiple kernel threads providing parallelism.
2433The M:N model is judged to be efficient and provide greater flexibility than a 1:1 threading model.
2434High-level objects (monitor/task) are the core mechanism for mutual exclusion and synchronization.
2435A novel aspect is allowing multiple mutex-objects to be accessed simultaneously reducing the potential for deadlock for this complex scenario.
2436These concepts and the entire \CFA runtime-system are written in the \CFA language, demonstrating the expressiveness of the \CFA language.
2437Performance comparisons with other concurrent systems/languages show the \CFA approach is competitive across all low-level operations, which translates directly into good performance in well-written concurrent applications.
2438C programmers should feel comfortable using these mechanisms for developing concurrent applications, with the ability to obtain maximum available performance by mechanisms at the appropriate level.
[604e76d]2439
2440
2441\section{Future Work}
[b199e54]2442
2443While concurrency in \CFA has a strong start, development is still underway and there are missing features.
2444
2445\paragraph{Flexible Scheduling}
2446\label{futur:sched}
2447
[d5ccbe9]2448An important part of concurrency is scheduling.
2449Different scheduling algorithms can affect performance (both in terms of average and variation).
2450However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
[b199e54]2451One solution is to offer various tweaking options, allowing the scheduler to be adjusted to the requirements of the workload.
[9f66811]2452However, to be truly flexible, a pluggable scheduler is necessary.
[b199e54]2453Currently, 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.
2454
2455\paragraph{Non-Blocking I/O}
2456\label{futur:nbio}
2457
2458Many modern workloads are not bound by computation but IO operations, a common case being web servers and XaaS~\cite{XaaS} (anything as a service).
2459These types of workloads require significant engineering to amortizing costs of blocking IO-operations.
2460At 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.
2461Current 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.
[9f66811]2462However, these solutions lead to code that is hard to create, read and maintain.
[b199e54]2463A 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.
2464A non-blocking I/O library is currently under development for \CFA.
2465
2466\paragraph{Other Concurrency Tools}
2467\label{futur:tools}
2468
[adb60242]2469While monitors offer flexible and powerful concurrency for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
[b199e54]2470Examples of such tools can include futures and promises~\cite{promises}, executors and actors.
[d5ccbe9]2471These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
[9f66811]2472As well, new \CFA extensions should make it possible to create a uniform interface for virtually all mutual exclusion, including monitors and low-level locks.
[604e76d]2473
[b199e54]2474\paragraph{Implicit Threading}
2475\label{futur:implcit}
[604e76d]2476
[b199e54]2477Basic concurrent (embarrassingly parallel) applications can benefit greatly from implicit concurrency, where sequential programs are converted to concurrent, possibly with some help from pragmas to guide the conversion.
2478This type of concurrency can be achieved both at the language level and at the library level.
2479The canonical example of implicit concurrency is concurrent nested @for@ loops, which are amenable to divide and conquer algorithms~\cite{uC++book}.
2480The \CFA language features should make it possible to develop a reasonable number of implicit concurrency mechanism to solve basic HPC data-concurrency problems.
[9f66811]2481However, implicit concurrency is a restrictive solution with significant limitations, so it can never replace explicit concurrent programming.
[604e76d]2482
2483
2484\section{Acknowledgements}
2485
[b199e54]2486The authors would like to recognize the design assistance of Aaron Moss, Rob Schluntz and Andrew Beach on the features described in this paper.
2487Funding for this project has been provided by Huawei Ltd.\ (\url{http://www.huawei.com}), and Peter Buhr is partially funded by the Natural Sciences and Engineering Research Council of Canada.
[604e76d]2488
[b199e54]2489{%
2490\fontsize{9bp}{12bp}\selectfont%
[604e76d]2491\bibliography{pl,local}
[b199e54]2492}%
[48b9b36]2493
[604e76d]2494\end{document}
[5ff188f]2495
2496% Local Variables: %
2497% tab-width: 4 %
2498% fill-column: 120 %
2499% compile-command: "make" %
2500% End: %
Note: See TracBrowser for help on using the repository browser.