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

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexer
Last change on this file since b199e54 was b199e54, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

first complete draft

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