source: doc/papers/concurrency/Paper.tex @ 6d43cc57

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since 6d43cc57 was 6d43cc57, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

more updates

  • Property mode set to 100644
File size: 154.7 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{siunitx}
24\sisetup{binary-units=true}
25
26\hypersetup{breaklinks=true}
27\definecolor{OliveGreen}{cmyk}{0.64 0 0.95 0.40}
28\definecolor{Mahogany}{cmyk}{0 0.85 0.87 0.35}
29\definecolor{Plum}{cmyk}{0.50 1 0 0}
30
31\usepackage[pagewise]{lineno}
32\renewcommand{\linenumberfont}{\scriptsize\sffamily}
33
34\renewcommand{\textfraction}{0.0}                       % the entire page maybe devoted to floats with no text on the page at all
35
36\lefthyphenmin=3                                                        % hyphen only after 4 characters
37\righthyphenmin=3
38
39%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
41% Names used in the document.
42
43\newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
44\newcommand{\CFA}{\protect\CFAIcon}             % safe for section/caption
45\newcommand{\CFL}{\textrm{Cforall}\xspace}      % Cforall symbolic name
46\newcommand{\Celeven}{\textrm{C11}\xspace}      % C11 symbolic name
47\newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
48\newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
49\newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
50\newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
51\newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name
52\newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name
53
54%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
55
56\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
57\newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}}
58\newcommand{\uC}{$\mu$\CC}
59\newcommand{\TODO}[1]{{\Textbf{#1}}}
60
61%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
62
63% Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
64% removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
65% AFTER HYPERREF.
66%\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}
67\renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}
68
69\renewcommand*{\thefootnote}{\Alph{footnote}} % hack because fnsymbol does not work
70%\renewcommand*{\thefootnote}{\fnsymbol{footnote}}
71
72\makeatletter
73% parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
74% use rather than use \parident directly.
75\newlength{\parindentlnth}
76\setlength{\parindentlnth}{\parindent}
77
78\newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{\lst@basicstyle{#1}}}}
79\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
80\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
81
82\newlength{\gcolumnposn}                                        % temporary hack because lstlisting does not handle tabs correctly
83\newlength{\columnposn}
84\setlength{\gcolumnposn}{3.5in}
85\setlength{\columnposn}{\gcolumnposn}
86
87\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}}}}
88\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
89
90% Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
91% The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
92% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
93\newcommand{\newtermFontInline}{\emph}
94\newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
95\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
96\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
97
98% Latin abbreviation
99\newcommand{\abbrevFont}{\textit}                       % set empty for no italics
100\@ifundefined{eg}{
101\newcommand{\EG}{\abbrevFont{e}\abbrevFont{g}}
102\newcommand*{\eg}{%
103        \@ifnextchar{,}{\EG}%
104                {\@ifnextchar{:}{\EG}%
105                        {\EG,\xspace}}%
106}}{}%
107\@ifundefined{ie}{
108\newcommand{\IE}{\abbrevFont{i}\abbrevFont{e}}
109\newcommand*{\ie}{%
110        \@ifnextchar{,}{\IE}%
111                {\@ifnextchar{:}{\IE}%
112                        {\IE,\xspace}}%
113}}{}%
114\@ifundefined{etc}{
115\newcommand{\ETC}{\abbrevFont{etc}}
116\newcommand*{\etc}{%
117        \@ifnextchar{.}{\ETC}%
118        {\ETC.\xspace}%
119}}{}%
120\@ifundefined{etal}{
121\newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}}
122\newcommand*{\etal}{%
123        \@ifnextchar{.}{\protect\ETAL}%
124                {\protect\ETAL.\xspace}%
125}}{}%
126\@ifundefined{viz}{
127\newcommand{\VIZ}{\abbrevFont{viz}}
128\newcommand*{\viz}{%
129        \@ifnextchar{.}{\VIZ}%
130                {\VIZ.\xspace}%
131}}{}%
132\makeatother
133
134\newenvironment{cquote}{%
135        \list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
136        \item\relax
137}{%
138        \endlist
139}% cquote
140
141% CFA programming language, based on ANSI C (with some gcc additions)
142\lstdefinelanguage{CFA}[ANSI]{C}{
143        morekeywords={
144                _Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, __attribute, __attribute__,
145                auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__, __const, __const__,
146                coroutine, disable, dtype, enable, exception, __extension__, fallthrough, fallthru, finally,
147                __float80, float80, __float128, float128, forall, ftype, _Generic, _Imaginary, __imag, __imag__,
148                inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
149                otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread,
150                _Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
151                virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
152        moredirectives={defined,include_next}%
153}
154
155\lstset{
156language=CFA,
157columns=fullflexible,
158basicstyle=\linespread{0.9}\sf,                                                 % reduce line spacing and use sanserif font
159stringstyle=\tt,                                                                                % use typewriter font
160tabsize=5,                                                                                              % N space tabbing
161xleftmargin=\parindentlnth,                                                             % indent code to paragraph indentation
162%mathescape=true,                                                                               % LaTeX math escape in CFA code $...$
163escapechar=\$,                                                                                  % LaTeX escape in CFA code
164keepspaces=true,                                                                                %
165showstringspaces=false,                                                                 % do not show spaces with cup
166showlines=true,                                                                                 % show blank lines at end of code
167aboveskip=4pt,                                                                                  % spacing above/below code block
168belowskip=3pt,
169% replace/adjust listing characters that look bad in sanserif
170literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
171        {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
172        {<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
173        {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex{\textrm{\textgreater}}}2,
174moredelim=**[is][\color{red}]{`}{`},
175}% lstset
176
177% uC++ programming language, based on ANSI C++
178\lstdefinelanguage{uC++}[ANSI]{C++}{
179        morekeywords={
180                _Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _CatchResume, _Cormonitor, _Coroutine, _Disable,
181                _Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
182                _Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
183}
184\lstdefinelanguage{Golang}{
185        morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
186        morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
187                bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
188        morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
189        morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
190        morekeywords=[5]{Println,Printf,Error,},
191        sensitive=true,
192        morecomment=[l]{//},
193        morecomment=[s]{/*}{*/},
194        morestring=[b]',
195        morestring=[b]",
196        morestring=[s]{`}{`},
197}
198
199\lstnewenvironment{cfa}[1][]
200{\lstset{#1}}
201{}
202\lstnewenvironment{C++}[1][]                            % use C++ style
203{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
204{}
205\lstnewenvironment{uC++}[1][]
206{\lstset{#1}}
207{}
208\lstnewenvironment{Go}[1][]
209{\lstset{#1}}
210{}
211
212% inline code @...@
213\lstMakeShortInline@%
214
215\let\OLDthebibliography\thebibliography
216\renewcommand\thebibliography[1]{
217  \OLDthebibliography{#1}
218  \setlength{\parskip}{0pt}
219  \setlength{\itemsep}{4pt plus 0.3ex}
220}
221
222\title{\texorpdfstring{Concurrency in \protect\CFA}{Concurrency in Cforall}}
223
224\author[1]{Thierry Delisle}
225\author[1]{Peter A. Buhr*}
226\authormark{DELISLE \textsc{et al.}}
227
228\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}
229
230\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}}
231
232\fundingInfo{Natural Sciences and Engineering Research Council of Canada}
233
234\abstract[Summary]{
235\CFA is a modern, polymorphic, \emph{non-object-oriented} extension of the C programming language.
236This paper discusses the design of the concurrency and parallelism features in \CFA, and the concurrent runtime-system.
237These features are created from scratch as ISO C lacks concurrency, relying largely on the pthreads library.
238Coroutines and lightweight (user) threads are introduced into the language.
239In addition, monitors are added as a high-level mechanism for mutual exclusion and synchronization.
240A unique contribution is allowing multiple monitors to be safely acquired simultaneously.
241All features respect the expectations of C programmers, while being fully integrate with the \CFA polymorphic type-system and other language features.
242Finally, experimental results are presented to compare the performance of the new features with similar mechanisms in other concurrent programming-languages.
243}%
244
245\keywords{concurrency, parallelism, coroutines, threads, monitors, runtime, C, Cforall}
246
247
248\begin{document}
249\linenumbers                                            % comment out to turn off line numbering
250
251\maketitle
252
253
254\section{Introduction}
255
256This paper provides a minimal concurrency \newterm{Application Program Interface} (API) that is simple, efficient and can be used to build other concurrency features.
257While the simplest concurrency system is a thread and a lock, this low-level approach is hard to master.
258An easier approach for programmers is to support higher-level constructs as the basis of concurrency.
259Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{Hochstein05}.
260Examples of high-level approaches are task (work) based~\cite{TBB}, implicit threading~\cite{OpenMP}, monitors~\cite{Java}, channels~\cite{CSP,Go}, and message passing~\cite{Erlang,MPI}.
261
262The following terminology is used.
263A \newterm{thread} is a fundamental unit of execution that runs a sequence of code and requires a stack to maintain state.
264Multiple simultaneous threads give rise to \newterm{concurrency}, which requires locking to ensure safe communication and access to shared data.
265% Correspondingly, concurrency is defined as the concepts and challenges that occur when multiple independent (sharing memory, timing dependencies, \etc) concurrent threads are introduced.
266\newterm{Locking}, and by extension \newterm{locks}, are defined as a mechanism to prevent progress of threads to provide safety.
267\newterm{Parallelism} is running multiple threads simultaneously.
268Parallelism implies \emph{actual} simultaneous execution, where concurrency only requires \emph{apparent} simultaneous execution.
269As such, parallelism only affects performance, which is observed through differences in space and/or time at runtime.
270
271Hence, there are two problems to be solved: concurrency and parallelism.
272While these two concepts are often combined, they are distinct, requiring different tools~\cite[\S~2]{Buhr05a}.
273Concurrency tools handle mutual exclusion and synchronization, while parallelism tools handle performance, cost, and resource utilization.
274
275The proposed concurrency API is implemented in a dialect of C, called \CFA.
276The 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.
277
278
279\section{\CFA Overview}
280
281The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency.
282Extended versions and explanation of the following code examples are available at the \CFA website~\cite{Cforall} or in Moss~\etal~\cite{Moss18}.
283
284\CFA is a non-object-oriented extension of ISO-C, and hence, supports all C paradigms.
285%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.
286Like C, the building blocks of \CFA are structures and routines.
287Virtually all of the code generated by the \CFA translator respects C memory layouts and calling conventions.
288While \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}.
289While 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.
290
291
292\subsection{References}
293
294\CFA provides multi-level rebindable references, as an alternative to pointers, which significantly reduces syntactic noise.
295\begin{cfa}
296int x = 1, y = 2, z = 3;
297int * p1 = &x, ** p2 = &p1,  *** p3 = &p2,      $\C{// pointers to x}$
298    `&` r1 = x,   `&&` r2 = r1,   `&&&` r3 = r2;        $\C{// references to x}$
299int * p4 = &z, `&` r4 = z;
300
301*p1 = 3; **p2 = 3; ***p3 = 3;       // change x
302r1 =  3;     r2 = 3;      r3 = 3;        // change x: implicit dereferences *r1, **r2, ***r3
303**p3 = &y; *p3 = &p4;                // change p1, p2
304`&`r3 = &y; `&&`r3 = &`&`r4;             // change r1, r2: cancel implicit dereferences (&*)**r3, (&(&*)*)*r3, &(&*)r4
305\end{cfa}
306A reference is a handle to an object, like a pointer, but is automatically dereferenced the specified number of levels.
307Referencing (address-of @&@) a reference variable cancels one of the implicit dereferences, until there are no more implicit references, after which normal expression behaviour applies.
308
309
310\subsection{\texorpdfstring{\protect\lstinline{with} Statement}{with Statement}}
311\label{s:WithStatement}
312
313Heterogeneous data is aggregated into a structure/union.
314To 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.
315\begin{cquote}
316\vspace*{-\baselineskip}%???
317\lstDeleteShortInline@%
318\begin{cfa}
319struct S { char c; int i; double d; };
320struct T { double m, n; };
321// multiple aggregate parameters
322\end{cfa}
323\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
324\begin{cfa}
325void f( S & s, T & t ) {
326        `s.`c; `s.`i; `s.`d;
327        `t.`m; `t.`n;
328}
329\end{cfa}
330&
331\begin{cfa}
332void f( S & s, T & t ) `with ( s, t )` {
333        c; i; d;                // no qualification
334        m; n;
335}
336\end{cfa}
337\end{tabular}
338\lstMakeShortInline@%
339\end{cquote}
340Object-oriented programming languages only provide implicit qualification for the receiver.
341
342In detail, the @with@ statement has the form:
343\begin{cfa}
344$\emph{with-statement}$:
345        'with' '(' $\emph{expression-list}$ ')' $\emph{compound-statement}$
346\end{cfa}
347and may appear as the body of a routine or nested within a routine body.
348Each expression in the expression-list provides a type and object.
349The type must be an aggregate type.
350(Enumerations are already opened.)
351The object is the implicit qualifier for the open structure-fields.
352All 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.
353
354
355\subsection{Overloading}
356
357\CFA maximizes the ability to reuse names via overloading to aggressively address the naming problem.
358Both variables and routines may be overloaded, where selection is based on types, and number of returns (as in Ada~\cite{Ada}) and arguments.
359\begin{cquote}
360\vspace*{-\baselineskip}%???
361\lstDeleteShortInline@%
362\begin{cfa}
363// selection based on type
364\end{cfa}
365\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
366\begin{cfa}
367const short int `MIN` = -32768;
368const int `MIN` = -2147483648;
369const long int `MIN` = -9223372036854775808L;
370\end{cfa}
371&
372\begin{cfa}
373short int si = `MIN`;
374int i = `MIN`;
375long int li = `MIN`;
376\end{cfa}
377\end{tabular}
378\begin{cfa}
379// selection based on type and number of parameters
380\end{cfa}
381\begin{tabular}{@{}l@{\hspace{2.7\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
382\begin{cfa}
383void `f`( void );
384void `f`( char );
385void `f`( int, double );
386\end{cfa}
387&
388\begin{cfa}
389`f`();
390`f`( 'a' );
391`f`( 3, 5.2 );
392\end{cfa}
393\end{tabular}
394\begin{cfa}
395// selection based on type and number of returns
396\end{cfa}
397\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
398\begin{cfa}
399char `f`( int );
400double `f`( int );
401[char, double] `f`( int );
402\end{cfa}
403&
404\begin{cfa}
405char c = `f`( 3 );
406double d = `f`( 3 );
407[d, c] = `f`( 3 );
408\end{cfa}
409\end{tabular}
410\lstMakeShortInline@%
411\end{cquote}
412Overloading is important for \CFA concurrency since the runtime system relies on creating different types to represent concurrency objects.
413Therefore, overloading eliminates long prefixes and other naming conventions to prevent name clashes.
414As seen in Section~\ref{basics}, routine @main@ is heavily overloaded.
415For example, variable overloading is useful in the parallel semantics of the @with@ statement for fields with the same name:
416\begin{cfa}
417struct S { int `i`; int j; double m; } s;
418struct T { int `i`; int k; int m; } t;
419with ( s, t ) {
420        j + k;                                                                  $\C{// unambiguous, s.j + t.k}$
421        m = 5.0;                                                                $\C{// unambiguous, s.m = 5.0}$
422        m = 1;                                                                  $\C{// unambiguous, t.m = 1}$
423        int a = m;                                                              $\C{// unambiguous, a = t.m }$
424        double b = m;                                                   $\C{// unambiguous, b = s.m}$
425        int c = `s.i` + `t.i`;                                  $\C{// unambiguous, qualification}$
426        (double)m;                                                              $\C{// unambiguous, cast s.m}$
427}
428\end{cfa}
429For parallel semantics, both @s.i@ and @t.i@ are visible with the same type, so only @i@ is ambiguous without qualification.
430
431
432\subsection{Operators}
433
434Overloading also extends to operators.
435Operator-overloading syntax creates a routine name with an operator symbol and question marks for the operands:
436\begin{cquote}
437\lstDeleteShortInline@%
438\begin{tabular}{@{}ll@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
439\begin{cfa}
440int ++? (int op);
441int ?++ (int op);
442int `?+?` (int op1, int op2);
443int ?<=?(int op1, int op2);
444int ?=? (int & op1, int op2);
445int ?+=?(int & op1, int op2);
446\end{cfa}
447&
448\begin{cfa}
449// unary prefix increment
450// unary postfix increment
451// binary plus
452// binary less than
453// binary assignment
454// binary plus-assignment
455\end{cfa}
456&
457\begin{cfa}
458struct S { int i, j; };
459S `?+?`( S op1, S op2) { // add two structures
460        return (S){op1.i + op2.i, op1.j + op2.j};
461}
462S s1 = {1, 2}, s2 = {2, 3}, s3;
463s3 = s1 `+` s2;         // compute sum: s3 == {2, 5}
464\end{cfa}
465\end{tabular}
466\lstMakeShortInline@%
467\end{cquote}
468While concurrency does not use operator overloading directly, it provides an introduction for the syntax of constructors.
469
470
471\subsection{Constructors / Destructors}
472
473Object lifetime is a challenge in non-managed programming languages.
474\CFA responds with \CC-like constructors and destructors:
475\begin{cfa}
476struct VLA { int len, * data; };                        $\C{// variable length array of integers}$
477void ?{}( VLA & vla ) with ( vla ) { len = 10;  data = alloc( len ); }  $\C{// default constructor}$
478void ?{}( VLA & vla, int size, char fill ) with ( vla ) { len = size;  data = alloc( len, fill ); } // initialization
479void ?{}( VLA & vla, VLA other ) { vla.len = other.len;  vla.data = other.data; } $\C{// copy, shallow}$
480void ^?{}( VLA & vla ) with ( vla ) { free( data ); } $\C{// destructor}$
481{
482        VLA  x,            y = { 20, 0x01 },     z = y; $\C{// z points to y}$
483        //    x{};         y{ 20, 0x01 };          z{ z, y };
484        ^x{};                                                                   $\C{// deallocate x}$
485        x{};                                                                    $\C{// reallocate x}$
486        z{ 5, 0xff };                                                   $\C{// reallocate z, not pointing to y}$
487        ^y{};                                                                   $\C{// deallocate y}$
488        y{ x };                                                                 $\C{// reallocate y, points to x}$
489        x{};                                                                    $\C{// reallocate x, not pointing to y}$
490        //  ^z{}^y{}^x{};
491}
492\end{cfa}
493Like \CC, construction is implicit on allocation (stack/heap) and destruction is implicit on deallocation.
494The object and all their fields are constructed/destructed.
495\CFA also provides @new@ and @delete@, which behave like @malloc@ and @free@, in addition to constructing and destructing objects:
496\begin{cfa}
497{
498        ... struct S s = {10}; ...                              $\C{// allocation, call constructor}$
499}                                                                                       $\C{// deallocation, call destructor}$
500struct S * s = new();                                           $\C{// allocation, call constructor}$
501...
502delete( s );                                                            $\C{// deallocation, call destructor}$
503\end{cfa}
504\CFA concurrency uses object lifetime as a means of mutual exclusion and/or synchronization.
505
506
507\subsection{Parametric Polymorphism}
508\label{s:ParametricPolymorphism}
509
510The signature feature of \CFA is parametric-polymorphic routines~\cite{} with routines generalized using a @forall@ clause (giving the language its name), which allow separately compiled routines to support generic usage over multiple types.
511For example, the following sum routine works for any type that supports construction from 0 and addition:
512\begin{cfa}
513forall( otype T | { void `?{}`( T *, zero_t ); T `?+?`( T, T ); } ) // constraint type, 0 and +
514T sum( T a[$\,$], size_t size ) {
515        `T` total = { `0` };                                    $\C{// initialize by 0 constructor}$
516        for ( size_t i = 0; i < size; i += 1 )
517                total = total `+` a[i];                         $\C{// select appropriate +}$
518        return total;
519}
520S sa[5];
521int i = sum( sa, 5 );                                           $\C{// use S's 0 construction and +}$
522\end{cfa}
523The 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.
524
525\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:
526\begin{cfa}
527trait `sumable`( otype T ) {
528        void `?{}`( T &, zero_t );                              $\C{// 0 literal constructor}$
529        T `?+?`( T, T );                                                $\C{// assortment of additions}$
530        T ?+=?( T &, T );
531        T ++?( T & );
532        T ?++( T & );
533};
534forall( otype T `| sumable( T )` )                      $\C{// use trait}$
535T sum( T a[$\,$], size_t size );
536\end{cfa}
537
538Assertions can be @otype@ or @dtype@.
539@otype@ refers to a ``complete'' object, \ie an object has a size, default constructor, copy constructor, destructor and an assignment operator.
540@dtype@ only guarantees an object has a size and alignment.
541
542Using the return type for discrimination, it is possible to write a type-safe @alloc@ based on the C @malloc@:
543\begin{cfa}
544forall( dtype T | sized(T) ) T * alloc( void ) { return (T *)malloc( sizeof(T) ); }
545int * ip = alloc();                                                     $\C{// select type and size from left-hand side}$
546double * dp = alloc();
547struct S {...} * sp = alloc();
548\end{cfa}
549where the return type supplies the type/size of the allocation, which is impossible in most type systems.
550
551
552\section{Concurrency Basics}\label{basics}
553
554At its core, concurrency is based on multiple call-stacks and scheduling threads executing on these stacks.
555Multiple 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}.
556In 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.
557A \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;
558a \newterm{stackfull} coroutine executes on its own stack, allowing full generality.
559Only stackfull coroutines are a stepping-stone to concurrency.
560
561The 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}.
562Therefore, a minimal concurrency system is possible using coroutines (see Section \ref{coroutine}) in conjunction with a scheduler to decide where to context switch next.
563The resulting execution system now follows a cooperative threading-model, called \newterm{non-preemptive scheduling}.
564
565Because the scheduler is special, it can either be a stackless or stackfull coroutine.
566For 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.
567For 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.
568A stackfull scheduler is often used for simplicity and security, even through there is a slightly higher runtime-cost.
569
570Regardless of the approach used, a subset of concurrency related challenges start to appear.
571For 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}.
572While a scheduler introduces uncertainty in the order of execution, preemption introduces uncertainty where context switches occur.
573Interestingly, uncertainty is necessary for the runtime (operating) system to give the illusion of parallelism on a single processor and increase performance on multiple processors.
574The reason is that only the runtime has complete knowledge about resources and how to best utilized them.
575However, the introduction of unrestricted non-determinism results in the need for \newterm{mutual exclusion} and \newterm{synchronization} to restrict non-determinism for correctness;
576otherwise, it is impossible to write meaningful programs.
577Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows.
578
579
580\subsection{\protect\CFA's Thread Building Blocks}
581
582An 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.
583As such, library support for threading is far from widespread.
584At the time of writing the paper, neither \protect\lstinline@gcc@ nor \protect\lstinline@clang@ support \protect\lstinline@threads.h@ in their standard libraries.}.
585In 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.
586As 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.
587Furthermore, because C is a system-level language, programmers expect to choose precisely which features they need and which cost they are willing to pay.
588Hence, concurrent programs should be written using high-level mechanisms, and only step down to lower-level mechanisms when performance bottlenecks are encountered.
589
590
591\subsection{Coroutines: A Stepping Stone}\label{coroutine}
592
593While 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.
594Coroutines are generalized routines allowing execution to be temporarily suspend and later resumed.
595Hence, 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.
596This capability is accomplish via the coroutine's stack, where suspend/resume context switch among stacks.
597Because 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.
598Therefore, the core \CFA coroutine-API for has two fundamental features: independent call-stacks and @suspend@/@resume@ operations.
599
600For 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.
601\begin{displaymath}
602\mathsf{fib}(n) = \left \{
603\begin{array}{ll}
6040                                       & n = 0         \\
6051                                       & n = 1         \\
606\mathsf{fib}(n-1) + \mathsf{fib}(n-2)   & n \ge 2       \\
607\end{array}
608\right.
609\end{displaymath}
610Figure~\ref{f:GlobalVariables} illustrates the following problems:
611unique unencapsulated global variables necessary to retain state between calls;
612only one Fibonacci generator;
613execution state must be explicitly retained via explicit state variables.
614Figure~\ref{f:ExternalState} addresses these issues:
615unencapsulated program global variables become encapsulated structure variables;
616unique global variables are replaced by multiple Fibonacci objects;
617explicit execution state is removed by precomputing the first two Fibonacci numbers and returning $\mathsf{fib}(n-2)$.
618
619\begin{figure}
620\centering
621\newbox\myboxA
622\begin{lrbox}{\myboxA}
623\begin{cfa}[aboveskip=0pt,belowskip=0pt]
624`int f1, f2, state = 1;`   // single global variables
625int fib() {
626        int fn;
627        `switch ( state )` {  // explicit execution state
628          case 1: fn = 0;  f1 = fn;  state = 2;  break;
629          case 2: fn = 1;  f2 = f1;  f1 = fn;  state = 3;  break;
630          case 3: fn = f1 + f2;  f2 = f1;  f1 = fn;  break;
631        }
632        return fn;
633}
634int main() {
635
636        for ( int i = 0; i < 10; i += 1 ) {
637                printf( "%d\n", fib() );
638        }
639}
640\end{cfa}
641\end{lrbox}
642
643\newbox\myboxB
644\begin{lrbox}{\myboxB}
645\begin{cfa}[aboveskip=0pt,belowskip=0pt]
646#define FIB_INIT `{ 0, 1 }`
647typedef struct { int f2, f1; } Fib;
648int fib( Fib * f ) {
649
650        int ret = f->f2;
651        int fn = f->f1 + f->f2;
652        f->f2 = f->f1; f->f1 = fn;
653
654        return ret;
655}
656int main() {
657        Fib f1 = FIB_INIT, f2 = FIB_INIT;
658        for ( int i = 0; i < 10; i += 1 ) {
659                printf( "%d %d\n", fib( &f1 ), fib( &f2 ) );
660        }
661}
662\end{cfa}
663\end{lrbox}
664
665\subfloat[3 States: global variables]{\label{f:GlobalVariables}\usebox\myboxA}
666\qquad
667\subfloat[1 State: external variables]{\label{f:ExternalState}\usebox\myboxB}
668\caption{C Fibonacci Implementations}
669\label{f:C-fibonacci}
670
671\bigskip
672
673\newbox\myboxA
674\begin{lrbox}{\myboxA}
675\begin{cfa}[aboveskip=0pt,belowskip=0pt]
676`coroutine` Fib { int fn; };
677void main( Fib & fib ) with( fib ) {
678        int f1, f2;
679        fn = 0;  f1 = fn;  `suspend()`;
680        fn = 1;  f2 = f1;  f1 = fn;  `suspend()`;
681        for ( ;; ) {
682                fn = f1 + f2;  f2 = f1;  f1 = fn;  `suspend()`;
683        }
684}
685int next( Fib & fib ) with( fib ) {
686        `resume( fib );`
687        return fn;
688}
689int main() {
690        Fib f1, f2;
691        for ( int i = 1; i <= 10; i += 1 ) {
692                sout | next( f1 ) | next( f2 ) | endl;
693        }
694}
695\end{cfa}
696\end{lrbox}
697\newbox\myboxB
698\begin{lrbox}{\myboxB}
699\begin{cfa}[aboveskip=0pt,belowskip=0pt]
700`coroutine` Fib { int ret; };
701void main( Fib & f ) with( fib ) {
702        int fn, f1 = 1, f2 = 0;
703        for ( ;; ) {
704                ret = f2;
705
706                fn = f1 + f2;  f2 = f1;  f1 = fn; `suspend();`
707        }
708}
709int next( Fib & fib ) with( fib ) {
710        `resume( fib );`
711        return ret;
712}
713
714
715
716
717
718
719\end{cfa}
720\end{lrbox}
721\subfloat[3 States, internal variables]{\label{f:Coroutine3States}\usebox\myboxA}
722\qquad\qquad
723\subfloat[1 State, internal variables]{\label{f:Coroutine1State}\usebox\myboxB}
724\caption{\CFA Coroutine Fibonacci Implementations}
725\label{f:fibonacci-cfa}
726\end{figure}
727
728Using a coroutine, it is possible to express the Fibonacci formula directly without any of the C problems.
729Figure~\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@.
730Like 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.
731The 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@.
732The interface routine @next@, takes a Fibonacci instance and context switches to it using @resume@;
733on restart, the Fibonacci field, @fn@, contains the next value in the sequence, which is returned.
734The first @resume@ is special because it cocalls the coroutine at its coroutine main and allocates the stack;
735when the coroutine main returns, its stack is deallocated.
736Hence, @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.
737Figure~\ref{f:Coroutine1State} shows the coroutine version of the C version in Figure~\ref{f:ExternalState}.
738Coroutine generators are called \newterm{output coroutines} because values are only returned.
739
740Figure~\ref{f:CFAFmt} shows an \newterm{input coroutine}, @Format@, for restructuring text into groups of characters of fixed-size blocks.
741For example, the input of the left is reformatted into the output on the right.
742\begin{quote}
743\tt
744\begin{tabular}{@{}l|l@{}}
745\multicolumn{1}{c|}{\textbf{\textrm{input}}} & \multicolumn{1}{c}{\textbf{\textrm{output}}} \\
746abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
747&
748\begin{tabular}[t]{@{}lllll@{}}
749abcd    & efgh  & ijkl  & mnop  & qrst  \\
750uvwx    & yzab  & cdef  & ghij  & klmn  \\
751opqr    & stuv  & wxyz  &               &
752\end{tabular}
753\end{tabular}
754\end{quote}
755The 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.
756The destruction provides a newline if formatted text ends with a full line.
757Figure~\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.
758
759\begin{figure}
760\centering
761\newbox\myboxA
762\begin{lrbox}{\myboxA}
763\begin{cfa}[aboveskip=0pt,belowskip=0pt]
764`coroutine` Format {
765        char ch;   // used for communication
766        int g, b;  // global because used in destructor
767};
768void main( Format & fmt ) with( fmt ) {
769        for ( ;; ) {   
770                for ( g = 0; g < 5; g += 1 ) {      // group
771                        for ( b = 0; b < 4; b += 1 ) { // block
772                                `suspend();`
773                                sout | ch;              // separator
774                        }
775                        sout | "  ";               // separator
776                }
777                sout | endl;
778        }
779}
780void ?{}( Format & fmt ) { `resume( fmt );` }
781void ^?{}( Format & fmt ) with( fmt ) {
782        if ( g != 0 || b != 0 ) sout | endl;
783}
784void format( Format & fmt ) {
785        `resume( fmt );`
786}
787int main() {
788        Format fmt;
789        eof: for ( ;; ) {
790                sin | fmt.ch;
791          if ( eof( sin ) ) break eof;
792                format( fmt );
793        }
794}
795\end{cfa}
796\end{lrbox}
797
798\newbox\myboxB
799\begin{lrbox}{\myboxB}
800\begin{cfa}[aboveskip=0pt,belowskip=0pt]
801struct Format {
802        char ch;
803        int g, b;
804};
805void format( struct Format * fmt ) {
806        if ( fmt->ch != -1 ) {      // not EOF ?
807                printf( "%c", fmt->ch );
808                fmt->b += 1;
809                if ( fmt->b == 4 ) {  // block
810                        printf( "  " );      // separator
811                        fmt->b = 0;
812                        fmt->g += 1;
813                }
814                if ( fmt->g == 5 ) {  // group
815                        printf( "\n" );     // separator
816                        fmt->g = 0;
817                }
818        } else {
819                if ( fmt->g != 0 || fmt->b != 0 ) printf( "\n" );
820        }
821}
822int main() {
823        struct Format fmt = { 0, 0, 0 };
824        for ( ;; ) {
825                scanf( "%c", &fmt.ch );
826          if ( feof( stdin ) ) break;
827                format( &fmt );
828        }
829        fmt.ch = -1;
830        format( &fmt );
831}
832\end{cfa}
833\end{lrbox}
834\subfloat[\CFA Coroutine]{\label{f:CFAFmt}\usebox\myboxA}
835\qquad
836\subfloat[C Linearized]{\label{f:CFmt}\usebox\myboxB}
837\caption{Formatting text into lines of 5 blocks of 4 characters.}
838\label{f:fmt-line}
839\end{figure}
840
841The 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.
842However,@resume@/@suspend@ context switch to existing stack-frames rather than create new ones so there is no stack growth.
843\newterm{Symmetric (full) coroutine}s have a coroutine call a resuming routine for another coroutine, which eventually forms a resuming-call cycle.
844(The trivial cycle is a coroutine resuming itself.)
845This control flow is similar to recursion for normal routines, but again there is no stack growth from the context switch.
846
847\begin{figure}
848\centering
849\lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $
850\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
851\begin{cfa}
852`coroutine` Prod {
853        Cons & c;
854        int N, money, receipt;
855};
856void main( Prod & prod ) with( prod ) {
857        // 1st resume starts here
858        for ( int i = 0; i < N; i += 1 ) {
859                int p1 = random( 100 ), p2 = random( 100 );
860                sout | p1 | " " | p2 | endl;
861                int status = delivery( c, p1, p2 );
862                sout | " $" | money | endl | status | endl;
863                receipt += 1;
864        }
865        stop( c );
866        sout | "prod stops" | endl;
867}
868int payment( Prod & prod, int money ) {
869        prod.money = money;
870        `resume( prod );`
871        return prod.receipt;
872}
873void start( Prod & prod, int N, Cons &c ) {
874        &prod.c = &c;
875        prod.[N, receipt] = [N, 0];
876        `resume( prod );`
877}
878int main() {
879        Prod prod;
880        Cons cons = { prod };
881        start( prod, 5, cons );
882}
883\end{cfa}
884&
885\begin{cfa}
886`coroutine` Cons {
887        Prod & p;
888        int p1, p2, status;
889        _Bool done;
890};
891void ?{}( Cons & cons, Prod & p ) {
892        &cons.p = &p;
893        cons.[status, done ] = [0, false];
894}
895void ^?{}( Cons & cons ) {}
896void main( Cons & cons ) with( cons ) {
897        // 1st resume starts here
898        int money = 1, receipt;
899        for ( ; ! done; ) {
900                sout | p1 | " " | p2 | endl | " $" | money | endl;
901                status += 1;
902                receipt = payment( p, money );
903                sout | " #" | receipt | endl;
904                money += 1;
905        }
906        sout | "cons stops" | endl;
907}
908int delivery( Cons & cons, int p1, int p2 ) {
909        cons.[p1, p2] = [p1, p2];
910        `resume( cons );`
911        return cons.status;
912}
913void stop( Cons & cons ) {
914        cons.done = true;
915        `resume( cons );`
916}
917\end{cfa}
918\end{tabular}
919\caption{Producer / consumer: resume-resume cycle, bi-directional communication}
920\label{f:ProdCons}
921\end{figure}
922
923Figure~\ref{f:ProdCons} shows a producer/consumer symmetric-coroutine performing bi-directional communication.
924Since 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@.
925The @start@ routine communicates both the number of elements to be produced and the consumer into the producer's coroutine structure.
926Then the @resume@ to @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
927@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.
928
929The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
930For the first resume, @cons@'s stack is initialized, creating local variables retained between subsequent activations of the coroutine.
931The 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).
932The call from the consumer to the @payment@ introduces the cycle between producer and consumer.
933When @payment@ is called, the consumer copies values into the producer's communication variable and a resume is executed.
934The context switch restarts the producer at the point where it was last context switched, so it continues in @delivery@ after the resume.
935
936@delivery@ returns the status value in @prod@'s coroutine main, where the status is printed.
937The loop then repeats calling @delivery@, where each call resumes the consumer coroutine.
938The context switch to the consumer continues in @payment@.
939The consumer increments and returns the receipt to the call in @cons@'s coroutine main.
940The loop then repeats calling @payment@, where each call resumes the producer coroutine.
941
942After iterating $N$ times, the producer calls @stop@.
943The @done@ flag is set to stop the consumer's execution and a resume is executed.
944The context switch restarts @cons@ in @payment@ and it returns with the last receipt.
945The 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@.
946@stop@ returns and @prod@'s coroutine main terminates.
947The program main restarts after the resume in @start@.
948@start@ returns and the program main terminates.
949
950
951\subsection{Coroutine Implementation}
952
953A 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.
954There are several solutions to this problem and the chosen option forced the \CFA coroutine design.
955
956Object-oriented inheritance provides extra fields and code in a restricted context, but it requires programmers to explicitly perform the inheritance:
957\begin{cfa}
958struct mycoroutine $\textbf{\textsf{inherits}}$ baseCoroutine { ... }
959\end{cfa}
960and the programming language (and possibly its tool set, \eg debugger) may need to understand @baseCoroutine@ because of the stack.
961Furthermore, the execution of constructs/destructors is in the wrong order for certain operations.
962For 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.
963
964An alternatively is composition:
965\begin{cfa}
966struct mycoroutine {
967        ... // declarations
968        baseCoroutine dummy; // composition, last declaration
969}
970\end{cfa}
971which also requires an explicit declaration that must be the last one to ensure correct initialization order.
972However, there is nothing preventing wrong placement or multiple declarations.
973
974For coroutines as for threads, many implementations are based on routine pointers or routine objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
975For example, Boost implements coroutines in terms of four functor object-types:
976\begin{cfa}
977asymmetric_coroutine<>::pull_type
978asymmetric_coroutine<>::push_type
979symmetric_coroutine<>::call_type
980symmetric_coroutine<>::yield_type
981\end{cfa}
982Similarly, the canonical threading paradigm is often based on routine pointers, \eg @pthreads@~\cite{pthreads}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}.
983However, the generic thread-handle (identifier) is limited (few operations), unless it is wrapped in a custom type.
984\begin{cfa}
985void mycor( coroutine_t cid, void * arg ) {
986        int * value = (int *)arg;                               $\C{// type unsafe, pointer-size only}$
987        // Coroutine body
988}
989int main() {
990        int input = 0, output;
991        coroutine_t cid = coroutine_create( &mycor, (void *)&input ); $\C{// type unsafe, pointer-size only}$
992        coroutine_resume( cid, (void *)input, (void **)&output ); $\C{// type unsafe, pointer-size only}$
993}
994\end{cfa}
995Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda-based coroutines adds very little.
996
997Note, the type @coroutine_t@ must be an abstract handle to the coroutine, because the coroutine descriptor and its stack are non-copyable.
998Copying the coroutine descriptor results in copies being out of date with the current state of the stack.
999Correspondingly, 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.
1000(There is no mechanism in C to find all stack-specific pointers and update them as part of a copy.)
1001
1002The selected approach is to use language support by introducing a new kind of aggregate (structure):
1003\begin{cfa}
1004coroutine Fibonacci {
1005        int fn; // communication variables
1006};
1007\end{cfa}
1008The @coroutine@ keyword means the compiler (and tool set) can find and inject code where needed.
1009The downside of this approach is that it makes coroutine a special case in the language.
1010Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language.
1011Furthermore, implementing coroutines without language supports also displays the power of a programming language.
1012While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can still be constructed without using the language support.
1013The reserved keyword simply eases use for the common cases.
1014
1015Part 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:
1016\begin{cfa}
1017trait is_coroutine( `dtype` T ) {
1018        void main( T & );
1019        coroutine_desc * get_coroutine( T & );
1020};
1021forall( `dtype` T | is_coroutine(T) ) void suspend( T & );
1022forall( `dtype` T | is_coroutine(T) ) void resume( T & );
1023\end{cfa}
1024The @dtype@ property of the trait ensures the coroutine descriptor is non-copyable, so all coroutines must be passed by reference (pointer).
1025The 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.
1026The @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.
1027The 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.
1028The 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@.
1029The \CFA keyword @coroutine@ implicitly implements the getter and forward declarations required for implementing the coroutine main:
1030\begin{cquote}
1031\begin{tabular}{@{}ccc@{}}
1032\begin{cfa}
1033coroutine MyCor {
1034        int value;
1035
1036};
1037\end{cfa}
1038&
1039{\Large $\Rightarrow$}
1040&
1041\begin{tabular}{@{}ccc@{}}
1042\begin{cfa}
1043struct MyCor {
1044        int value;
1045        coroutine_desc cor;
1046};
1047\end{cfa}
1048&
1049\begin{cfa}
1050static inline coroutine_desc *
1051get_coroutine( MyCor & this ) {
1052        return &this.cor;
1053}
1054\end{cfa}
1055&
1056\begin{cfa}
1057void main( MyCor * this );
1058
1059
1060
1061\end{cfa}
1062\end{tabular}
1063\end{tabular}
1064\end{cquote}
1065The 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.
1066
1067
1068\subsection{Thread Interface}
1069\label{threads}
1070
1071Both user and kernel threads are supported, where user threads provide concurrency and kernel threads provide parallelism.
1072Like 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:
1073\begin{cquote}
1074\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
1075\begin{cfa}
1076thread myThread {
1077        // communication variables
1078};
1079
1080
1081\end{cfa}
1082&
1083\begin{cfa}
1084trait is_thread( `dtype` T ) {
1085      void main( T & );
1086      thread_desc * get_thread( T & );
1087      void ^?{}( T & `mutex` );
1088};
1089\end{cfa}
1090\end{tabular}
1091\end{cquote}
1092(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitors}.)
1093Like a coroutine, the statically-typed @main@ routine is the starting point (first stack frame) of a user thread.
1094The difference is that a coroutine borrows a thread from its caller, so the first thread resuming a coroutine creates an instance of @main@;
1095whereas, 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{
1096The \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.}
1097No 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.
1098
1099\begin{comment} % put in appendix with coroutine version ???
1100As such the @main@ routine of a thread can be defined as
1101\begin{cfa}
1102thread foo {};
1103
1104void main(foo & this) {
1105        sout | "Hello World!" | endl;
1106}
1107\end{cfa}
1108
1109In 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.
1110With 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.
1111\begin{cfa}
1112typedef void (*voidRtn)(int);
1113
1114thread RtnRunner {
1115        voidRtn func;
1116        int arg;
1117};
1118
1119void ?{}(RtnRunner & this, voidRtn inRtn, int arg) {
1120        this.func = inRtn;
1121        this.arg  = arg;
1122}
1123
1124void main(RtnRunner & this) {
1125        // thread starts here and runs the routine
1126        this.func( this.arg );
1127}
1128
1129void hello(/*unused*/ int) {
1130        sout | "Hello World!" | endl;
1131}
1132
1133int main() {
1134        RtnRunner f = {hello, 42};
1135        return 0?
1136}
1137\end{cfa}
1138A 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}.
1139\end{comment}
1140
1141For user threads to be useful, it must be possible to start and stop the underlying thread, and wait for it to complete execution.
1142While using an API such as @fork@ and @join@ is relatively common, such an interface is awkward and unnecessary.
1143A simple approach is to use allocation/deallocation principles, and have threads implicitly @fork@ after construction and @join@ before destruction.
1144\begin{cfa}
1145thread World {};
1146void main( World & this ) {
1147        sout | "World!" | endl;
1148}
1149int main() {
1150        World w`[10]`;                                                  $\C{// implicit forks after creation}$
1151        sout | "Hello " | endl;                                 $\C{// "Hello " and 10 "World!" printed concurrently}$
1152}                                                                                       $\C{// implicit joins before destruction}$
1153\end{cfa}
1154This semantics ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
1155This 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.
1156\begin{cfa}
1157int main() {
1158        MyThread * heapLived;
1159        {
1160                MyThread blockLived;                            $\C{// fork block-based thread}$
1161                heapLived = `new`( MyThread );          $\C{// fork heap-based thread}$
1162                ...
1163        }                                                                               $\C{// join block-based thread}$
1164        ...
1165        `delete`( heapLived );                                  $\C{// join heap-based thread}$
1166}
1167\end{cfa}
1168The heap-based approach allows arbitrary thread-creation topologies, with respect to fork/join-style concurrency.
1169
1170Figure~\ref{s:ConcurrentMatrixSummation} shows concurrently adding the rows of a matrix and then totalling the subtotals sequential, after all the row threads have terminated.
1171The program uses heap-based threads because each thread needs different constructor values.
1172(Python provides a simple iteration mechanism to initialize array elements to different values allowing stack allocation.)
1173The allocation/deallocation pattern appears unusual because allocated objects are immediately deleted without any intervening code.
1174However, for threads, the deletion provides implicit synchronization, which is the intervening code.
1175While 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.
1176
1177\begin{figure}
1178\begin{cfa}
1179thread Adder {
1180    int * row, cols, & subtotal;                        $\C{// communication}$
1181};
1182void ?{}( Adder & adder, int row[], int cols, int & subtotal ) {
1183    adder.[ row, cols, &subtotal ] = [ row, cols, &subtotal ];
1184}
1185void main( Adder & adder ) with( adder ) {
1186    subtotal = 0;
1187    for ( int c = 0; c < cols; c += 1 ) { subtotal += row[c]; }
1188}
1189int main() {
1190    const int rows = 10, cols = 1000;
1191    int matrix[rows][cols], subtotals[rows], total = 0;
1192    // read matrix
1193    Adder * adders[rows];
1194    for ( int r = 0; r < rows; r += 1 ) {       $\C{// start threads to sum rows}$
1195                adders[r] = new( matrix[r], cols, &subtotals[r] );
1196    }
1197    for ( int r = 0; r < rows; r += 1 ) {       $\C{// wait for threads to finish}$
1198                delete( adders[r] );                            $\C{// termination join}$
1199                total += subtotals[r];                          $\C{// total subtotal}$
1200    }
1201    sout | total | endl;
1202}
1203\end{cfa}
1204\caption{Concurrent Matrix Summation}
1205\label{s:ConcurrentMatrixSummation}
1206\end{figure}
1207
1208
1209\section{Mutual Exclusion / Synchronization}
1210
1211Uncontrolled non-deterministic execution is meaningless.
1212To 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}.
1213Since 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).
1214In 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}.
1215However, 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.
1216Hence, a programmer must learn and manipulate two sets of design patterns.
1217While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
1218In contrast, approaches based on statefull models more closely resemble the standard call/return programming-model, resulting in a single programming paradigm.
1219
1220At 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}.
1221However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}.
1222A newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
1223While 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.
1224
1225One of the most natural, elegant, and efficient mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor}.
1226First 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}.
1227In 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.
1228For these reasons, \CFA selected monitors as the core high-level concurrency-construct, upon which higher-level approaches can be easily constructed.
1229
1230
1231\subsection{Mutual Exclusion}
1232
1233A group of instructions manipulating a specific instance of shared data that must be performed atomically is called an (individual) \newterm{critical-section}~\cite{Dijkstra65}.
1234The 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.
1235The 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.
1236\newterm{Mutual exclusion} enforces that the correct kind and number of threads are using a critical section.
1237
1238However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
1239Methods 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.
1240Ease 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.
1241For 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.
1242However, a significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock.
1243Easing composability is another feature higher-level mutual-exclusion mechanisms can offer.
1244
1245
1246\subsection{Synchronization}
1247
1248Synchronization enforces relative ordering of execution, and synchronization tools provide numerous mechanisms to establish these timing relationships.
1249Low-level synchronization primitives offer good performance and flexibility at the cost of ease of use;
1250higher-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.
1251Often 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.
1252If a writer thread is scheduled for next access, but another reader thread acquires the critical section first, that reader has \newterm{barged}.
1253Barging 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).
1254Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
1255This challenge is often split into two different approaches: barging avoidance and barging prevention.
1256Algorithms that allow a barger, but divert it until later using current synchronization state (flags), are avoiding the barger;
1257algorithms that preclude a barger from entering during synchronization in the critical section prevent barging completely.
1258Techniques like baton-pass locks~\cite{Andrews89} between threads instead of unconditionally releasing locks is an example of barging prevention.
1259
1260
1261\section{Monitors}
1262\label{s:Monitors}
1263
1264A \textbf{monitor} is a set of routines that ensure mutual exclusion when accessing shared state.
1265More 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).
1266The strong association with the call/return paradigm eases programmability, readability and maintainability, at a slight cost in flexibility and efficiency.
1267
1268Note, 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.
1269Copying 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.
1270Copying 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.
1271As for coroutines/tasks, a non-copyable (@dtype@) trait is used to capture this requirement, so all locks/monitors must be passed by reference (pointer).
1272\begin{cfa}
1273trait is_monitor( `dtype` T ) {
1274        monitor_desc * get_monitor( T & );
1275        void ^?{}( T & mutex );
1276};
1277\end{cfa}
1278
1279
1280\subsection{Mutex Acquisition}
1281\label{s:MutexAcquisition}
1282
1283While correctness implicitly implies a monitor's mutual exclusion is acquired and released, there are implementation options about when and where the locking/unlocking occurs.
1284(Much of this discussion also applies to basic locks.)
1285For example, a monitor may need to be passed through multiple helper routines before it becomes necessary to acquire the monitor mutual-exclusion.
1286\begin{cfa}[morekeywords=nomutex]
1287monitor Aint { int cnt; };                                      $\C{// atomic integer counter}$
1288void ?{}( Aint & `nomutex` this ) with( this ) { cnt = 0; } $\C{// constructor}$
1289int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions}$
1290void ?{}( int & this, Aint & `mutex`$\(_{opt}\)$ v ) { this = v.cnt; }
1291int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; }
1292int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$
1293\end{cfa}
1294The @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.
1295(While a constructor may publish its address into a global variable, doing so generates a race-condition.)
1296The conversion operators for initializing and assigning with a normal integer only need @mutex@, if reading/writing the implementation type is not atomic.
1297Finally, 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.
1298
1299The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics, which is similar to the \CC template @std::atomic@.
1300\begin{cfa}
1301Aint x, y, z;
1302++x; ++y; ++z;                                                          $\C{// safe increment by multiple threads}$
1303x = 2; y = 2; z = 2;                                            $\C{// conversions}$
1304int i = x, j = y, k = z;
1305i = x; j = y; k = z;
1306\end{cfa}
1307
1308For maximum usability, monitors have \newterm{multi-acquire} semantics allowing a thread to acquire it multiple times without deadlock.
1309For example, atomically printing the contents of a binary tree:
1310\begin{cfa}
1311monitor Tree {
1312        Tree * left, right;
1313        // value
1314};
1315void print( Tree & mutex tree ) {                       $\C{// prefix traversal}$
1316        // write value
1317        print( tree->left );                                    $\C{// multiply acquire monitor lock on each recursion}$
1318        print( tree->right );
1319}
1320\end{cfa}
1321
1322Mandatory monitor qualifiers have the benefit of being self-documented, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameter is redundant.
1323Instead, one of qualifier semantics can be the default, and the other required.
1324For example, assume the safe @mutex@ option for a monitor parameter because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
1325On the other hand, assuming \lstinline[morekeywords=nomutex]@nomutex@ is the \emph{normal} parameter behaviour, stating explicitly ``this parameter is not special''.
1326Providing a default qualifier implies knowing whether a parameter is a monitor.
1327Since \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.
1328For 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@.
1329
1330The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@.
1331Given:
1332\begin{cfa}
1333monitor M { ... }
1334int f1( M & mutex m );
1335int f2( M * mutex m );
1336int f3( M * mutex m[] );
1337int f4( stack( M * ) & mutex m );
1338\end{cfa}
1339the issue is that some of these parameter types are composed of multiple objects.
1340For @f1@, there is only a single parameter object.
1341Adding indirection in @f2@ still identifies a single object.
1342However, the matrix in @f3@ introduces multiple objects.
1343While shown shortly, multiple acquisition is possible;
1344however array lengths are often unknown in C.
1345This issue is exacerbated in @f4@, where the data structure must be safely traversed to acquire all of its elements.
1346
1347To make the issue tractable, \CFA only acquires one monitor per parameter with at most one level of indirection.
1348However, the C type-system has an ambiguity with respects to arrays.
1349Is the argument for @f2@ a single object or an array of objects?
1350If it is an array, only the first element of the array is acquired, which seems unsafe;
1351hence, @mutex@ is disallowed for array parameters.
1352\begin{cfa}
1353int f1( M & mutex m );                                          $\C{// allowed: recommended case}$
1354int f2( M * mutex m );                                          $\C{// disallowed: could be an array}$
1355int f3( M mutex m[$\,$] );                                      $\C{// disallowed: array length unknown}$
1356int f4( M ** mutex m );                                         $\C{// disallowed: could be an array}$
1357int f5( M * mutex m[$\,$] );                            $\C{// disallowed: array length unknown}$
1358\end{cfa}
1359% Note, not all array routines have distinct types: @f2@ and @f3@ have the same type, as do @f4@ and @f5@.
1360% However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
1361
1362For object-oriented monitors, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
1363\CFA has no receiver, and hence, must use an explicit mechanism to specify which object has mutual exclusion acquired.
1364A positive consequence of this design decision is the ability to support multi-monitor routines.
1365\begin{cfa}
1366int f( M & mutex x, M & mutex y );              $\C{// multiple monitor parameter of any type}$
1367M m1, m2;
1368f( m1, m2 );
1369\end{cfa}
1370(While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.)
1371In practice, writing multi-locking routines that do not deadlock is tricky.
1372Having language support for such a feature is therefore a significant asset for \CFA.
1373
1374The capability to acquire multiple locks before entering a critical section is called \newterm{bulk acquire}.
1375In the previous example, \CFA guarantees the order of acquisition is consistent across calls to different routines using the same monitors as arguments.
1376This consistent ordering means acquiring multiple monitors is safe from deadlock.
1377However, users can force the acquiring order.
1378For example, notice the use of @mutex@/\lstinline[morekeywords=nomutex]@nomutex@ and how this affects the acquiring order:
1379\begin{cfa}
1380void foo( M & mutex m1, M & mutex m2 );         $\C{// acquire m1 and m2}$
1381void bar( M & mutex m1, M & /* nomutex */ m2 ) { $\C{// acquire m1}$
1382        ... foo( m1, m2 ); ...                                  $\C{// acquire m2}$
1383}
1384void baz( M & /* nomutex */ m1, M & mutex m2 ) { $\C{// acquire m2}$
1385        ... foo( m1, m2 ); ...                                  $\C{// acquire m1}$
1386}
1387\end{cfa}
1388The multi-acquire semantics allows @bar@ or @baz@ to acquire a monitor lock and reacquire it in @foo@.
1389In the calls to @bar@ and @baz@, the monitors are acquired in opposite order.
1390
1391However, 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}.
1392In \CFA, safety is guaranteed by using bulk acquire of all monitors to shared objects, whereas other monitor systems provide no aid.
1393While \CFA provides only a partial solution, the \CFA partial solution handles many useful cases.
1394\begin{cfa}
1395monitor Bank { ... };
1396void deposit( Bank & `mutex` b, int deposit );
1397void transfer( Bank & `mutex` mybank, Bank & `mutex` yourbank, int me2you) {
1398        deposit( mybank, `-`me2you );                   $\C{// debit}$
1399        deposit( yourbank, me2you );                    $\C{// credit}$
1400}
1401\end{cfa}
1402This example shows a trivial solution to the bank-account transfer problem~\cite{BankTransfer}.
1403Without multi- and bulk acquire, the solution to this problem requires careful engineering.
1404
1405
1406\subsection{\protect\lstinline|mutex| statement} \label{mutex-stmt}
1407
1408The monitor call-semantics associate all locking semantics to routines.
1409Like Java, \CFA offers an alternative @mutex@ statement to reduce refactoring and naming.
1410\begin{cquote}
1411\begin{tabular}{@{}c|@{\hspace{\parindentlnth}}c@{}}
1412routine call & @mutex@ statement \\
1413\begin{cfa}
1414monitor M {};
1415void foo( M & mutex m1, M & mutex m2 ) {
1416        // critical section
1417}
1418void bar( M & m1, M & m2 ) {
1419        foo( m1, m2 );
1420}
1421\end{cfa}
1422&
1423\begin{cfa}
1424
1425void bar( M & m1, M & m2 ) {
1426        mutex( m1, m2 ) {       // remove refactoring and naming
1427                // critical section
1428        }
1429}
1430
1431\end{cfa}
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
1660Given the ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock.
1661\begin{cfa}
1662void foo( M & mutex m1, M & mutex m2 ) {
1663        ... wait( `e, m1` ); ...                                $\C{// release m1, keeping m2 acquired )}$
1664void bar( M & mutex m1, M & mutex m2 ) {        $\C{// must acquire m1 and m2 )}$
1665        ... signal( `e` ); ...
1666\end{cfa}
1667The @wait@ only releases @m1@ so the signalling thread cannot acquire both @m1@ and @m2@ to  enter @bar@ to get to the @signal@.
1668While deadlock issues can occur with multiple/nesting acquisition, this issue results from the fact that locks, and by extension monitors, are not perfectly composable.
1669
1670Finally, an important aspect of monitor implementation is barging, \ie can calling threads barge ahead of signalled threads?
1671If 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).
1672\begin{quote}
1673However, we decree that a signal operation be followed immediately by resumption of a waiting program, without possibility of an intervening procedure call from yet a third program.
1674It is only in this way that a waiting program has an absolute guarantee that it can acquire the resource just released by the signalling program without any danger that a third program will interpose a monitor entry and seize the resource instead.~\cite[p.~550]{Hoare74}
1675\end{quote}
1676\CFA scheduling \emph{precludes} barging, which simplifies synchronization among threads in the monitor and increases correctness.
1677For example, there are no loops in either bounded buffer solution in Figure~\ref{f:GenericBoundedBuffer}.
1678Supporting 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.
1679
1680
1681\subsection{Barging Prevention}
1682
1683Figure~\ref{f:BargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signalling semantics.
1684The complexity begins at the end of the inner @mutex@ statement, where the semantics of internal scheduling need to be extended for multiple monitors.
1685The problem is that bulk acquire is used in the inner @mutex@ statement where one of the monitors is already acquired.
1686When 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.
1687However, both the signalling and waiting thread W1 still need monitor @m1@.
1688
1689\begin{figure}
1690\newbox\myboxA
1691\begin{lrbox}{\myboxA}
1692\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1693monitor M m1, m2;
1694condition c;
1695mutex( m1 ) { // $\LstCommentStyle{\color{red}outer}$
1696        ...
1697        mutex( m1, m2 ) { // $\LstCommentStyle{\color{red}inner}$
1698                ... `signal( c )`; ...
1699                // m1, m2 acquired
1700        } // $\LstCommentStyle{\color{red}release m2}$
1701        // m1 acquired
1702} // release m1
1703\end{cfa}
1704\end{lrbox}
1705
1706\newbox\myboxB
1707\begin{lrbox}{\myboxB}
1708\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1709
1710
1711mutex( m1 ) {
1712        ...
1713        mutex( m1, m2 ) {
1714                ... `wait( c )`; // block and release m1, m2
1715                // m1, m2 acquired
1716        } // $\LstCommentStyle{\color{red}release m2}$
1717        // m1 acquired
1718} // release m1
1719\end{cfa}
1720\end{lrbox}
1721
1722\newbox\myboxC
1723\begin{lrbox}{\myboxC}
1724\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1725
1726
1727mutex( m2 ) {
1728        ... `wait( c )`; ...
1729        // m2 acquired
1730} // $\LstCommentStyle{\color{red}release m2}$
1731
1732
1733
1734
1735\end{cfa}
1736\end{lrbox}
1737
1738\begin{cquote}
1739\subfloat[Signalling Thread]{\label{f:SignallingThread}\usebox\myboxA}
1740\hspace{2\parindentlnth}
1741\subfloat[Waiting Thread (W1)]{\label{f:WaitingThread}\usebox\myboxB}
1742\hspace{2\parindentlnth}
1743\subfloat[Waiting Thread (W2)]{\label{f:OtherWaitingThread}\usebox\myboxC}
1744\end{cquote}
1745\caption{Barging Prevention}
1746\label{f:BargingPrevention}
1747\end{figure}
1748
1749One 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.
1750However, Figure~\ref{f:OtherWaitingThread} shows this solution is complex depending on other waiters, resulting is choices when the signaller finishes the inner mutex-statement.
1751The 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@.
1752In 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.
1753Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
1754
1755While a number of approaches were examined~\cite[\S~4.3]{Delisle18}, the solution chosen for \CFA is a novel techique called \newterm{partial signalling}.
1756Signalled threads are moved to an urgent queue and the waiter at the front defines the set of monitors necessary for it to unblock.
1757Partial signalling transfers ownership of monitors to the front waiter.
1758When the signaller thread exits or waits in the monitor the front waiter is unblocked if all its monitors are released.
1759This 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.
1760
1761\begin{comment}
1762Figure~\ref{f:dependency} shows a slightly different example where a third thread is waiting on monitor @A@, using a different condition variable.
1763Because the third thread is signalled when secretly holding @B@, the goal  becomes unreachable.
1764Depending on the order of signals (listing \ref{f:dependency} line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen:
1765
1766\paragraph{Case 1: thread $\alpha$ goes first.} In this case, the problem is that monitor @A@ needs to be passed to thread $\beta$ when thread $\alpha$ is done with it.
1767\paragraph{Case 2: thread $\beta$ goes first.} In this case, the problem is that monitor @B@ needs to be retained and passed to thread $\alpha$ along with monitor @A@, which can be done directly or possibly using thread $\beta$ as an intermediate.
1768\\
1769
1770Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order.
1771However, regardless of the answer, users can move line \ref{line:signal-a} before line \ref{line:signal-ab} and get the reverse effect for listing \ref{f:dependency}.
1772
1773In both cases, the threads need to be able to distinguish, on a per monitor basis, which ones need to be released and which ones need to be transferred, which means knowing when to release a group becomes complex and inefficient (see next section) and therefore effectively precludes this approach.
1774
1775
1776\subsubsection{Dependency graphs}
1777
1778\begin{figure}
1779\begin{multicols}{3}
1780Thread $\alpha$
1781\begin{cfa}[numbers=left, firstnumber=1]
1782acquire A
1783        acquire A & B
1784                wait A & B
1785        release A & B
1786release A
1787\end{cfa}
1788\columnbreak
1789Thread $\gamma$
1790\begin{cfa}[numbers=left, firstnumber=6, escapechar=|]
1791acquire A
1792        acquire A & B
1793                |\label{line:signal-ab}|signal A & B
1794        |\label{line:release-ab}|release A & B
1795        |\label{line:signal-a}|signal A
1796|\label{line:release-a}|release A
1797\end{cfa}
1798\columnbreak
1799Thread $\beta$
1800\begin{cfa}[numbers=left, firstnumber=12, escapechar=|]
1801acquire A
1802        wait A
1803|\label{line:release-aa}|release A
1804\end{cfa}
1805\end{multicols}
1806\begin{cfa}[caption={Pseudo-code for the three thread example.},label={f:dependency}]
1807\end{cfa}
1808\begin{center}
1809\input{dependency}
1810\end{center}
1811\caption{Dependency graph of the statements in listing \ref{f:dependency}}
1812\label{fig:dependency}
1813\end{figure}
1814
1815In listing \ref{f:int-bulk-cfa}, there is a solution that satisfies both barging prevention and mutual exclusion.
1816If ownership of both monitors is transferred to the waiter when the signaller releases @A & B@ and then the waiter transfers back ownership of @A@ back to the signaller when it releases it, then the problem is solved (@B@ is no longer in use at this point).
1817Dynamically finding the correct order is therefore the second possible solution.
1818The problem is effectively resolving a dependency graph of ownership requirements.
1819Here even the simplest of code snippets requires two transfers and has a super-linear complexity.
1820This complexity can be seen in listing \ref{f:explosion}, which is just a direct extension to three monitors, requires at least three ownership transfer and has multiple solutions.
1821Furthermore, the presence of multiple solutions for ownership transfer can cause deadlock problems if a specific solution is not consistently picked; In the same way that multiple lock acquiring order can cause deadlocks.
1822\begin{figure}
1823\begin{multicols}{2}
1824\begin{cfa}
1825acquire A
1826        acquire B
1827                acquire C
1828                        wait A & B & C
1829                release C
1830        release B
1831release A
1832\end{cfa}
1833
1834\columnbreak
1835
1836\begin{cfa}
1837acquire A
1838        acquire B
1839                acquire C
1840                        signal A & B & C
1841                release C
1842        release B
1843release A
1844\end{cfa}
1845\end{multicols}
1846\begin{cfa}[caption={Extension to three monitors of listing \ref{f:int-bulk-cfa}},label={f:explosion}]
1847\end{cfa}
1848\end{figure}
1849
1850Given the three threads example in listing \ref{f:dependency}, figure \ref{fig:dependency} shows the corresponding dependency graph that results, where every node is a statement of one of the three threads, and the arrows the dependency of that statement (\eg $\alpha1$ must happen before $\alpha2$).
1851The extra challenge is that this dependency graph is effectively post-mortem, but the runtime system needs to be able to build and solve these graphs as the dependencies unfold.
1852Resolving dependency graphs being a complex and expensive endeavour, this solution is not the preferred one.
1853\end{comment}
1854
1855
1856\begin{comment}
1857\section{External scheduling} \label{extsched}
1858
1859\begin{table}
1860\begin{tabular}{|c|c|c|}
1861Internal Scheduling & External Scheduling & Go\\
1862\hline
1863\begin{uC++}[tabsize=3]
1864_Monitor Semaphore {
1865        condition c;
1866        bool inUse;
1867public:
1868        void P() {
1869                if(inUse)
1870                        wait(c);
1871                inUse = true;
1872        }
1873        void V() {
1874                inUse = false;
1875                signal(c);
1876        }
1877}
1878\end{uC++}&\begin{uC++}[tabsize=3]
1879_Monitor Semaphore {
1880
1881        bool inUse;
1882public:
1883        void P() {
1884                if(inUse)
1885                        _Accept(V);
1886                inUse = true;
1887        }
1888        void V() {
1889                inUse = false;
1890
1891        }
1892}
1893\end{uC++}&\begin{Go}[tabsize=3]
1894type MySem struct {
1895        inUse bool
1896        c     chan bool
1897}
1898
1899// acquire
1900func (s MySem) P() {
1901        if s.inUse {
1902                select {
1903                case <-s.c:
1904                }
1905        }
1906        s.inUse = true
1907}
1908
1909// release
1910func (s MySem) V() {
1911        s.inUse = false
1912
1913        // This actually deadlocks
1914        // when single thread
1915        s.c <- false
1916}
1917\end{Go}
1918\end{tabular}
1919\caption{Different forms of scheduling.}
1920\label{tbl:sched}
1921\end{table}
1922
1923For the @P@ member above using internal scheduling, the call to @wait@ only guarantees that @V@ is the last routine to access the monitor, allowing a third routine, say @isInUse()@, acquire mutual exclusion several times while routine @P@ is waiting.
1924On the other hand, external scheduling guarantees that while routine @P@ is waiting, no other routine than @V@ can acquire the monitor.
1925\end{comment}
1926
1927
1928\subsection{Loose Object Definitions}
1929\label{s:LooseObjectDefinitions}
1930
1931In an object-oriented programming-language, a class includes an exhaustive list of operations.
1932However, new members can be added via static inheritance or dynaic members, \eg JavaScript~\cite{JavaScript}.
1933Similarly, monitor routines can be added at any time in \CFA, making it less clear for programmers and more difficult to implement.
1934\begin{cfa}
1935monitor M {};
1936void `f`( M & mutex m );
1937void g( M & mutex m ) { waitfor( `f` ); }       $\C{// clear which f}$
1938void `f`( M & mutex m, int );                           $\C{// different f}$
1939void h( M & mutex m ) { waitfor( `f` ); }       $\C{// unclear which f}$
1940\end{cfa}
1941Hence, the cfa-code for the entering a monitor looks like:
1942\begin{cfa}
1943if ( $\textrm{\textit{monitor is free}}$ ) $\LstCommentStyle{// \color{red}enter}$
1944else if ( $\textrm{\textit{already own monitor}}$ ) $\LstCommentStyle{// \color{red}continue}$
1945else if ( $\textrm{\textit{monitor accepts me}}$ ) $\LstCommentStyle{// \color{red}enter}$
1946else $\LstCommentStyle{// \color{red}block}$
1947\end{cfa}
1948For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions.
1949However, a fast check for \emph{monitor accepts me} is much harder to implement depending on the constraints put on the monitors.
1950Figure~\ref{fig:ClassicalMonitor} shows monitors are often expressed as an entry (calling) queue, some acceptor queues, and an urgent stack/queue.
1951
1952\begin{figure}
1953\centering
1954\subfloat[Classical monitor] {
1955\label{fig:ClassicalMonitor}
1956{\resizebox{0.45\textwidth}{!}{\input{monitor.pstex_t}}}
1957}% subfloat
1958\quad
1959\subfloat[Bulk acquire monitor] {
1960\label{fig:BulkMonitor}
1961{\resizebox{0.45\textwidth}{!}{\input{ext_monitor.pstex_t}}}
1962}% subfloat
1963\caption{Monitor Implementation}
1964\label{f:MonitorImplementation}
1965\end{figure}
1966
1967For 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.
1968This approach requires a unique dense ordering of routines with a small upper-bound and the ordering must be consistent across translation units.
1969For 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.
1970
1971Figure~\ref{fig:BulkMonitor} shows the \CFA monitor implementation.
1972The mutex routine called is associated with each thread on the entry queue, while a list of acceptable routines is kept separately.
1973The 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.
1974
1975\begin{comment}
1976\begin{figure}
1977\begin{cfa}[caption={Example of nested external scheduling},label={f:nest-ext}]
1978monitor M {};
1979void foo( M & mutex a ) {}
1980void bar( M & mutex b ) {
1981        // Nested in the waitfor(bar, c) call
1982        waitfor(foo, b);
1983}
1984void baz( M & mutex c ) {
1985        waitfor(bar, c);
1986}
1987
1988\end{cfa}
1989\end{figure}
1990
1991Note that in the right picture, tasks need to always keep track of the monitors associated with mutex routines, and the routine mask needs to have both a routine pointer and a set of monitors, as is discussed in the next section.
1992These details are omitted from the picture for the sake of simplicity.
1993
1994At this point, a decision must be made between flexibility and performance.
1995Many design decisions in \CFA achieve both flexibility and performance, for example polymorphic routines add significant flexibility but inlining them means the optimizer can easily remove any runtime cost.
1996Here, however, the cost of flexibility cannot be trivially removed.
1997In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be  hard to write.
1998This decision is based on the assumption that writing fast but inflexible locks is closer to a solved problem than writing locks that are as flexible as external scheduling in \CFA.
1999\end{comment}
2000
2001
2002\subsection{Multi-Monitor Scheduling}
2003\label{s:Multi-MonitorScheduling}
2004
2005External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax.
2006Even in the simplest possible case, new semantics needs to be established:
2007\begin{cfa}
2008monitor M {};
2009void f( M & mutex m1 );
2010void g( M & mutex m1, M & mutex m2 ) {
2011        waitfor( f );                                                   $\C{// pass m1 or m2 to f?}$
2012}
2013\end{cfa}
2014The solution is for the programmer to disambiguate:
2015\begin{cfa}
2016        waitfor( f, m2 );                                               $\C{// wait for call to f with argument m2}$
2017\end{cfa}
2018Routine @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@).
2019This behaviour can be extended to the multi-monitor @waitfor@ statement.
2020\begin{cfa}
2021monitor M {};
2022void f( M & mutex m1, M & mutex m2 );
2023void g( M & mutex m1, M & mutex m2 ) {
2024        waitfor( f, m1, m2 );                                   $\C{// wait for call to f with arguments m1 and m2}$
2025}
2026\end{cfa}
2027Again, the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired by accepting routine.
2028
2029An important behaviour to note is when a set of monitors only match partially:
2030\begin{cfa}
2031mutex struct A {};
2032mutex struct B {};
2033void g( A & mutex m1, B & mutex m2 ) {
2034        waitfor( f, m1, m2 );
2035}
2036A a1, a2;
2037B b;
2038void foo() {
2039        g( a1, b ); // block on accept
2040}
2041void bar() {
2042        f( a2, b ); // fulfill cooperation
2043}
2044\end{cfa}
2045While the equivalent can happen when using internal scheduling, the fact that conditions are specific to a set of monitors means that users have to use two different condition variables.
2046In both cases, partially matching monitor sets does not wakeup the waiting thread.
2047It is also important to note that in the case of external scheduling the order of parameters is irrelevant; @waitfor(f,a,b)@ and @waitfor(f,b,a)@ are indistinguishable waiting condition.
2048
2049
2050\subsection{\protect\lstinline|waitfor| Semantics}
2051
2052Syntactically, the @waitfor@ statement takes a routine identifier and a set of monitors.
2053While the set of monitors can be any list of expressions, the routine name is more restricted because the compiler validates at compile time the validity of the routine type and the parameters used with the @waitfor@ statement.
2054It checks that the set of monitors passed in matches the requirements for a routine call.
2055Figure~\ref{f:waitfor} shows various usages of the waitfor statement and which are acceptable.
2056The choice of the routine type is made ignoring any non-@mutex@ parameter.
2057One limitation of the current implementation is that it does not handle overloading, but overloading is possible.
2058\begin{figure}
2059\begin{cfa}[caption={Various correct and incorrect uses of the waitfor statement},label={f:waitfor}]
2060monitor A{};
2061monitor B{};
2062
2063void f1( A & mutex );
2064void f2( A & mutex, B & mutex );
2065void f3( A & mutex, int );
2066void f4( A & mutex, int );
2067void f4( A & mutex, double );
2068
2069void foo( A & mutex a1, A & mutex a2, B & mutex b1, B & b2 ) {
2070        A * ap = & a1;
2071        void (*fp)( A & mutex ) = f1;
2072
2073        waitfor(f1, a1);     // Correct : 1 monitor case
2074        waitfor(f2, a1, b1); // Correct : 2 monitor case
2075        waitfor(f3, a1);     // Correct : non-mutex arguments are ignored
2076        waitfor(f1, *ap);    // Correct : expression as argument
2077
2078        waitfor(f1, a1, b1); // Incorrect : Too many mutex arguments
2079        waitfor(f2, a1);     // Incorrect : Too few mutex arguments
2080        waitfor(f2, a1, a2); // Incorrect : Mutex arguments don't match
2081        waitfor(f1, 1);      // Incorrect : 1 not a mutex argument
2082        waitfor(f9, a1);     // Incorrect : f9 routine does not exist
2083        waitfor(*fp, a1 );   // Incorrect : fp not an identifier
2084        waitfor(f4, a1);     // Incorrect : f4 ambiguous
2085
2086        waitfor(f2, a1, b2); // Undefined behaviour : b2 not mutex
2087}
2088\end{cfa}
2089\end{figure}
2090
2091Finally, for added flexibility, \CFA supports constructing a complex @waitfor@ statement using the @or@, @timeout@ and @else@.
2092Indeed, multiple @waitfor@ clauses can be chained together using @or@; this chain forms a single statement that uses baton pass to any routine that fits one of the routine+monitor set passed in.
2093To enable users to tell which accepted routine executed, @waitfor@s are followed by a statement (including the null statement @;@) or a compound statement, which is executed after the clause is triggered.
2094A @waitfor@ chain can also be followed by a @timeout@, to signify an upper bound on the wait, or an @else@, to signify that the call should be non-blocking, which checks for a matching routine call already arrived and otherwise continues.
2095Any and all of these clauses can be preceded by a @when@ condition to dynamically toggle the accept clauses on or off based on some current state.
2096Figure~\ref{f:waitfor2} demonstrates several complex masks and some incorrect ones.
2097
2098\begin{figure}
2099\lstset{language=CFA,deletedelim=**[is][]{`}{`}}
2100\begin{cfa}
2101monitor A{};
2102
2103void f1( A & mutex );
2104void f2( A & mutex );
2105
2106void foo( A & mutex a, bool b, int t ) {
2107        waitfor(f1, a);                                                 $\C{// Correct : blocking case}$
2108
2109        waitfor(f1, a) {                                                $\C{// Correct : block with statement}$
2110                sout | "f1" | endl;
2111        }
2112        waitfor(f1, a) {                                                $\C{// Correct : block waiting for f1 or f2}$
2113                sout | "f1" | endl;
2114        } or waitfor(f2, a) {
2115                sout | "f2" | endl;
2116        }
2117        waitfor(f1, a); or else;                                $\C{// Correct : non-blocking case}$
2118
2119        waitfor(f1, a) {                                                $\C{// Correct : non-blocking case}$
2120                sout | "blocked" | endl;
2121        } or else {
2122                sout | "didn't block" | endl;
2123        }
2124        waitfor(f1, a) {                                                $\C{// Correct : block at most 10 seconds}$
2125                sout | "blocked" | endl;
2126        } or timeout( 10`s) {
2127                sout | "didn't block" | endl;
2128        }
2129        // Correct : block only if b == true if b == false, don't even make the call
2130        when(b) waitfor(f1, a);
2131
2132        // Correct : block only if b == true if b == false, make non-blocking call
2133        waitfor(f1, a); or when(!b) else;
2134
2135        // Correct : block only of t > 1
2136        waitfor(f1, a); or when(t > 1) timeout(t); or else;
2137
2138        // Incorrect : timeout clause is dead code
2139        waitfor(f1, a); or timeout(t); or else;
2140
2141        // Incorrect : order must be waitfor [or waitfor... [or timeout] [or else]]
2142        timeout(t); or waitfor(f1, a); or else;
2143}
2144\end{cfa}
2145\caption{Correct and incorrect uses of the or, else, and timeout clause around a waitfor statement}
2146\label{f:waitfor2}
2147\end{figure}
2148
2149
2150\subsection{Waiting For The Destructor}
2151
2152An interesting use for the @waitfor@ statement is destructor semantics.
2153Indeed, the @waitfor@ statement can accept any @mutex@ routine, which includes the destructor (see section \ref{data}).
2154However, with the semantics discussed until now, waiting for the destructor does not make any sense, since using an object after its destructor is called is undefined behaviour.
2155The simplest approach is to disallow @waitfor@ on a destructor.
2156However, a more expressive approach is to flip ordering of execution when waiting for the destructor, meaning that waiting for the destructor allows the destructor to run after the current @mutex@ routine, similarly to how a condition is signalled.
2157\begin{figure}
2158\begin{cfa}[caption={Example of an executor which executes action in series until the destructor is called.},label={f:dtor-order}]
2159monitor Executer {};
2160struct  Action;
2161
2162void ^?{}   (Executer & mutex this);
2163void execute(Executer & mutex this, const Action & );
2164void run    (Executer & mutex this) {
2165        while(true) {
2166                   waitfor(execute, this);
2167                or waitfor(^?{}   , this) {
2168                        break;
2169                }
2170        }
2171}
2172\end{cfa}
2173\end{figure}
2174For example, listing \ref{f:dtor-order} shows an example of an executor with an infinite loop, which waits for the destructor to break out of this loop.
2175Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction.
2176
2177
2178\section{Parallelism}
2179
2180Historically, computer performance was about processor speeds and instruction counts.
2181However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}.
2182In this decade, it is no longer reasonable to create a high-performance application without caring about parallelism.
2183Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization.
2184The lowest-level approach of parallelism is to use \textbf{kthread} in combination with semantics like @fork@, @join@, \etc.
2185However, since these have significant costs and limitations, \textbf{kthread} are now mostly used as an implementation tool rather than a user oriented one.
2186There are several alternatives to solve these issues that all have strengths and weaknesses.
2187While there are many variations of the presented paradigms, most of these variations do not actually change the guarantees or the semantics, they simply move costs in order to achieve better performance for certain workloads.
2188
2189
2190\section{Paradigms}
2191
2192
2193\subsection{User-Level Threads}
2194
2195A direct improvement on the \textbf{kthread} approach is to use \textbf{uthread}.
2196These threads offer most of the same features that the operating system already provides but can be used on a much larger scale.
2197This approach is the most powerful solution as it allows all the features of multithreading, while removing several of the more expensive costs of kernel threads.
2198The downside is that almost none of the low-level threading problems are hidden; users still have to think about data races, deadlocks and synchronization issues.
2199These issues can be somewhat alleviated by a concurrency toolkit with strong guarantees, but the parallelism toolkit offers very little to reduce complexity in itself.
2200
2201Examples of languages that support \textbf{uthread} are Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
2202
2203
2204\subsection{Fibers : User-Level Threads Without Preemption} \label{fibers}
2205
2206A popular variant of \textbf{uthread} is what is often referred to as \textbf{fiber}.
2207However, \textbf{fiber} do not present meaningful semantic differences with \textbf{uthread}.
2208The significant difference between \textbf{uthread} and \textbf{fiber} is the lack of \textbf{preemption} in the latter.
2209Advocates of \textbf{fiber} list their high performance and ease of implementation as major strengths, but the performance difference between \textbf{uthread} and \textbf{fiber} is controversial, and the ease of implementation, while true, is a weak argument in the context of language design.
2210Therefore this proposal largely ignores fibers.
2211
2212An example of a language that uses fibers is Go~\cite{Go}
2213
2214
2215\subsection{Jobs and Thread Pools}
2216
2217An approach on the opposite end of the spectrum is to base parallelism on \textbf{pool}.
2218Indeed, \textbf{pool} offer limited flexibility but at the benefit of a simpler user interface.
2219In \textbf{pool} based systems, users express parallelism as units of work, called jobs, and a dependency graph (either explicit or implicit) that ties them together.
2220This approach means users need not worry about concurrency but significantly limit the interaction that can occur among jobs.
2221Indeed, any \textbf{job} that blocks also block the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably.
2222It can be argued that a solution to this problem is to use more workers than available cores.
2223However, unless the number of jobs and the number of workers are comparable, having a significant number of blocked jobs always results in idles cores.
2224
2225The gold standard of this implementation is Intel's TBB library~\cite{TBB}.
2226
2227
2228\subsection{Paradigm Performance}
2229
2230While the choice between the three paradigms listed above may have significant performance implications, it is difficult to pin down the performance implications of choosing a model at the language level.
2231Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload.
2232Having a large amount of mostly independent units of work to execute almost guarantees equivalent performance across paradigms and that the \textbf{pool}-based system has the best efficiency thanks to the lower memory overhead (\ie no thread stack per job).
2233However, interactions among jobs can easily exacerbate contention.
2234User-level threads allow fine-grain context switching, which results in better resource utilization, but a context switch is more expensive and the extra control means users need to tweak more variables to get the desired performance.
2235Finally, if the units of uninterrupted work are large, enough the paradigm choice is largely amortized by the actual work done.
2236
2237
2238\section{The \protect\CFA\ Kernel : Processors, Clusters and Threads}\label{kernel}
2239
2240A \textbf{cfacluster} is a group of \textbf{kthread} executed in isolation. \textbf{uthread} are scheduled on the \textbf{kthread} of a given \textbf{cfacluster}, allowing organization between \textbf{uthread} and \textbf{kthread}.
2241It is important that \textbf{kthread} belonging to a same \textbf{cfacluster} have homogeneous settings, otherwise migrating a \textbf{uthread} from one \textbf{kthread} to the other can cause issues.
2242A \textbf{cfacluster} also offers a pluggable scheduler that can optimize the workload generated by the \textbf{uthread}.
2243
2244\textbf{cfacluster} have not been fully implemented in the context of this paper.
2245Currently \CFA only supports one \textbf{cfacluster}, the initial one.
2246
2247
2248\subsection{Future Work: Machine Setup}\label{machine}
2249
2250While this was not done in the context of this paper, another important aspect of clusters is affinity.
2251While many common desktop and laptop PCs have homogeneous CPUs, other devices often have more heterogeneous setups.
2252For example, a system using \textbf{numa} configurations may benefit from users being able to tie clusters and/or kernel threads to certain CPU cores.
2253OS support for CPU affinity is now common~\cite{affinityLinux, affinityWindows, affinityFreebsd, affinityNetbsd, affinityMacosx}, which means it is both possible and desirable for \CFA to offer an abstraction mechanism for portable CPU affinity.
2254
2255
2256\subsection{Paradigms}\label{cfaparadigms}
2257
2258Given these building blocks, it is possible to reproduce all three of the popular paradigms.
2259Indeed, \textbf{uthread} is the default paradigm in \CFA.
2260However, disabling \textbf{preemption} on a cluster means threads effectively become fibers.
2261Since several \textbf{cfacluster} with different scheduling policy can coexist in the same application, this allows \textbf{fiber} and \textbf{uthread} to coexist in the runtime of an application.
2262Finally, it is possible to build executors for thread pools from \textbf{uthread} or \textbf{fiber}, which includes specialized jobs like actors~\cite{Actors}.
2263
2264
2265\section{Behind the Scenes}
2266
2267There are several challenges specific to \CFA when implementing concurrency.
2268These challenges are a direct result of bulk acquire and loose object definitions.
2269These two constraints are the root cause of most design decisions in the implementation.
2270Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs.
2271This approach avoids the chicken and egg problem~\cite{Chicken} of having a memory allocator that relies on the threading system and a threading system that relies on the runtime.
2272This extra goal means that memory management is a constant concern in the design of the system.
2273
2274The main memory concern for concurrency is queues.
2275All blocking operations are made by parking threads onto queues and all queues are designed with intrusive nodes, where each node has pre-allocated link fields for chaining, to avoid the need for memory allocation.
2276Since several concurrency operations can use an unbound amount of memory (depending on bulk acquire), statically defining information in the intrusive fields of threads is insufficient.The only way to use a variable amount of memory without requiring memory allocation is to pre-allocate large buffers of memory eagerly and store the information in these buffers.
2277Conveniently, the call stack fits that description and is easy to use, which is why it is used heavily in the implementation of internal scheduling, particularly variable-length arrays.
2278Since stack allocation is based on scopes, the first step of the implementation is to identify the scopes that are available to store the information, and which of these can have a variable-length array.
2279The threads and the condition both have a fixed amount of memory, while @mutex@ routines and blocking calls allow for an unbound amount, within the stack size.
2280
2281Note that since the major contributions of this paper are extending monitor semantics to bulk acquire and loose object definitions, any challenges that are not resulting of these characteristics of \CFA are considered as solved problems and therefore not discussed.
2282
2283
2284\section{Mutex Routines}
2285
2286The first step towards the monitor implementation is simple @mutex@ routines.
2287In the single monitor case, mutual-exclusion is done using the entry/exit procedure in listing \ref{f:entry1}.
2288The entry/exit procedures do not have to be extended to support multiple monitors.
2289Indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlock~\cite{Havender68}.
2290In \CFA, ordering of monitor acquisition relies on memory ordering.
2291This approach is sufficient because all objects are guaranteed to have distinct non-overlapping memory layouts and mutual-exclusion for a monitor is only defined for its lifetime, meaning that destroying a monitor while it is acquired is undefined behaviour.
2292When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer array and sorted based on pointer values.
2293This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively.
2294\begin{figure}
2295\begin{multicols}{2}
2296Entry
2297\begin{cfa}
2298if monitor is free
2299        enter
2300elif already own the monitor
2301        continue
2302else
2303        block
2304increment recursions
2305\end{cfa}
2306\columnbreak
2307Exit
2308\begin{cfa}
2309decrement recursion
2310if recursion == 0
2311        if entry queue not empty
2312                wake-up thread
2313\end{cfa}
2314\end{multicols}
2315\begin{cfa}[caption={Initial entry and exit routine for monitors},label={f:entry1}]
2316\end{cfa}
2317\end{figure}
2318
2319
2320\subsection{Details: Interaction with polymorphism}
2321
2322Depending on the choice of semantics for when monitor locks are acquired, interaction between monitors and \CFA's concept of polymorphism can be more complex to support.
2323However, it is shown that entry-point locking solves most of the issues.
2324
2325First of all, interaction between @otype@ polymorphism (see Section~\ref{s:ParametricPolymorphism}) and monitors is impossible since monitors do not support copying.
2326Therefore, the main question is how to support @dtype@ polymorphism.
2327It is important to present the difference between the two acquiring options: \textbf{callsite-locking} and entry-point locking, \ie acquiring the monitors before making a mutex routine-call or as the first operation of the mutex routine-call.
2328For example:
2329\begin{table}
2330\begin{center}
2331\begin{tabular}{|c|c|c|}
2332Mutex & \textbf{callsite-locking} & \textbf{entry-point-locking} \\
2333call & cfa-code & cfa-code \\
2334\hline
2335\begin{cfa}[tabsize=3]
2336void foo(monitor& mutex a){
2337
2338        // Do Work
2339        //...
2340
2341}
2342
2343void main() {
2344        monitor a;
2345
2346        foo(a);
2347
2348}
2349\end{cfa} & \begin{cfa}[tabsize=3]
2350foo(& a) {
2351
2352        // Do Work
2353        //...
2354
2355}
2356
2357main() {
2358        monitor a;
2359        acquire(a);
2360        foo(a);
2361        release(a);
2362}
2363\end{cfa} & \begin{cfa}[tabsize=3]
2364foo(& a) {
2365        acquire(a);
2366        // Do Work
2367        //...
2368        release(a);
2369}
2370
2371main() {
2372        monitor a;
2373
2374        foo(a);
2375
2376}
2377\end{cfa}
2378\end{tabular}
2379\end{center}
2380\caption{Call-site vs entry-point locking for mutex calls}
2381\label{tbl:locking-site}
2382\end{table}
2383
2384Note the @mutex@ keyword relies on the type system, which means that in cases where a generic monitor-routine is desired, writing the mutex routine is possible with the proper trait, \eg:
2385\begin{cfa}
2386// Incorrect: T may not be monitor
2387forall(dtype T)
2388void foo(T * mutex t);
2389
2390// Correct: this routine only works on monitors (any monitor)
2391forall(dtype T | is_monitor(T))
2392void bar(T * mutex t));
2393\end{cfa}
2394
2395Both entry point and \textbf{callsite-locking} are feasible implementations.
2396The current \CFA implementation uses entry-point locking because it requires less work when using \textbf{raii}, effectively transferring the burden of implementation to object construction/destruction.
2397It is harder to use \textbf{raii} for call-site locking, as it does not necessarily have an existing scope that matches exactly the scope of the mutual exclusion, \ie the routine body.
2398For example, the monitor call can appear in the middle of an expression.
2399Furthermore, entry-point locking requires less code generation since any useful routine is called multiple times but there is only one entry point for many call sites.
2400
2401
2402\section{Threading} \label{impl:thread}
2403
2404Figure \ref{fig:system1} shows a high-level picture if the \CFA runtime system in regards to concurrency.
2405Each component of the picture is explained in detail in the flowing sections.
2406
2407\begin{figure}
2408\begin{center}
2409{\resizebox{\textwidth}{!}{\input{system.pstex_t}}}
2410\end{center}
2411\caption{Overview of the entire system}
2412\label{fig:system1}
2413\end{figure}
2414
2415
2416\subsection{Processors}
2417
2418Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically @pthread@s in the current implementation of \CFA.
2419Indeed, any parallelism must go through operating-system libraries.
2420However, \textbf{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism.
2421Indeed, processor \textbf{kthread} simply fetch a \textbf{uthread} from the scheduler and run it; they are effectively executers for user-threads.
2422The main benefit of this approach is that it offers a well-defined boundary between kernel code and user code, for example, kernel thread quiescing, scheduling and interrupt handling.
2423Processors internally use coroutines to take advantage of the existing context-switching semantics.
2424
2425
2426\subsection{Stack Management}
2427
2428One of the challenges of this system is to reduce the footprint as much as possible.
2429Specifically, all @pthread@s created also have a stack created with them, which should be used as much as possible.
2430Normally, coroutines also create their own stack to run on, however, in the case of the coroutines used for processors, these coroutines run directly on the \textbf{kthread} stack, effectively stealing the processor stack.
2431The exception to this rule is the Main Processor, \ie the initial \textbf{kthread} that is given to any program.
2432In order to respect C user expectations, the stack of the initial kernel thread, the main stack of the program, is used by the main user thread rather than the main processor, which can grow very large.
2433
2434
2435\subsection{Context Switching}
2436
2437As mentioned in section \ref{coroutine}, coroutines are a stepping stone for implementing threading, because they share the same mechanism for context-switching between different stacks.
2438To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific routine call.
2439This assumption means that the context-switch only has to copy the callee-saved registers onto the stack and then switch the stack registers with the ones of the target coroutine/thread.
2440Note that the instruction pointer can be left untouched since the context-switch is always inside the same routine
2441Threads, however, do not context-switch between each other directly.
2442They context-switch to the scheduler.
2443This method is called a 2-step context-switch and has the advantage of having a clear distinction between user code and the kernel where scheduling and other system operations happen.
2444Obviously, this doubles the context-switch cost because threads must context-switch to an intermediate stack.
2445The alternative 1-step context-switch uses the stack of the ``from'' thread to schedule and then context-switches directly to the ``to'' thread.
2446However, the performance of the 2-step context-switch is still superior to a @pthread_yield@ (see section \ref{results}).
2447Additionally, for users in need for optimal performance, it is important to note that having a 2-step context-switch as the default does not prevent \CFA from offering a 1-step context-switch (akin to the Microsoft @SwitchToFiber@~\cite{switchToWindows} routine).
2448This option is not currently present in \CFA, but the changes required to add it are strictly additive.
2449
2450
2451\subsection{Preemption} \label{preemption}
2452
2453Finally, an important aspect for any complete threading system is preemption.
2454As mentioned in section \ref{basics}, preemption introduces an extra degree of uncertainty, which enables users to have multiple threads interleave transparently, rather than having to cooperate among threads for proper scheduling and CPU distribution.
2455Indeed, preemption is desirable because it adds a degree of isolation among threads.
2456In a fully cooperative system, any thread that runs a long loop can starve other threads, while in a preemptive system, starvation can still occur but it does not rely on every thread having to yield or block on a regular basis, which reduces significantly a programmer burden.
2457Obviously, preemption is not optimal for every workload.
2458However any preemptive system can become a cooperative system by making the time slices extremely large.
2459Therefore, \CFA uses a preemptive threading system.
2460
2461Preemption in \CFA\footnote{Note that the implementation of preemption is strongly tied with the underlying threading system.
2462For this reason, only the Linux implementation is cover, \CFA does not run on Windows at the time of writting} is based on kernel timers, which are used to run a discrete-event simulation.
2463Every processor keeps track of the current time and registers an expiration time with the preemption system.
2464When the preemption system receives a change in preemption, it inserts the time in a sorted order and sets a kernel timer for the closest one, effectively stepping through preemption events on each signal sent by the timer.
2465These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread.
2466This results in an implementation problem, because when delivering signals to a process, the kernel can deliver the signal to any kernel thread for which the signal is not blocked, \ie:
2467\begin{quote}
2468A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
2469If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
2470SIGNAL(7) - Linux Programmer's Manual
2471\end{quote}
2472For the sake of simplicity, and in order to prevent the case of having two threads receiving alarms simultaneously, \CFA programs block the {\tt SIGALRM} signal on every kernel thread except one.
2473
2474Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread.
2475Hence, involuntary context-switching is done by sending signal {\tt SIGUSR1} to the corresponding proces\-sor and having the thread yield from inside the signal handler.
2476This approach effectively context-switches away from the signal handler back to the kernel and the signal handler frame is eventually unwound when the thread is scheduled again.
2477As a result, a signal handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread).
2478It is important to note that signal handlers save and restore signal masks because user-thread migration can cause a signal mask to migrate from one kernel thread to another.
2479This behaviour is only a problem if all kernel threads, among which a user thread can migrate, differ in terms of signal masks\footnote{Sadly, official POSIX documentation is silent on what distinguishes ``async-signal-safe'' routines from other routines}.
2480However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel-alarm thread can cause deadlocks.
2481For this reason, the alarm thread is in a tight loop around a system call to @sigwaitinfo@, requiring very little CPU time for preemption.
2482One final detail about the alarm thread is how to wake it when additional communication is required (\eg on thread termination).
2483This unblocking is also done using {\tt SIGALRM}, but sent through the @pthread_sigqueue@.
2484Indeed, @sigwait@ can differentiate signals sent from @pthread_sigqueue@ from signals sent from alarms or the kernel.
2485
2486
2487\subsection{Scheduler}
2488Finally, an aspect that was not mentioned yet is the scheduling algorithm.
2489Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling.
2490Further discussion on scheduling is present in section \ref{futur:sched}.
2491
2492
2493\section{Internal Scheduling} \label{impl:intsched}
2494
2495The following figure is the traditional illustration of a monitor (repeated from page~\pageref{fig:ClassicalMonitor} for convenience):
2496
2497\begin{figure}
2498\begin{center}
2499{\resizebox{0.4\textwidth}{!}{\input{monitor.pstex_t}}}
2500\end{center}
2501\caption{Traditional illustration of a monitor}
2502\end{figure}
2503
2504This picture has several components, the two most important being the entry queue and the AS-stack.
2505The entry queue is an (almost) FIFO list where threads waiting to enter are parked, while the acceptor/signaller (AS) stack is a FILO list used for threads that have been signalled or otherwise marked as running next.
2506
2507For \CFA, this picture does not have support for blocking multiple monitors on a single condition.
2508To support bulk acquire two changes to this picture are required.
2509First, it is no longer helpful to attach the condition to \emph{a single} monitor.
2510Secondly, the thread waiting on the condition has to be separated across multiple monitors, seen in figure \ref{fig:monitor_cfa}.
2511
2512\begin{figure}
2513\begin{center}
2514{\resizebox{0.8\textwidth}{!}{\input{int_monitor}}}
2515\end{center}
2516\caption{Illustration of \CFA Monitor}
2517\label{fig:monitor_cfa}
2518\end{figure}
2519
2520This picture and the proper entry and leave algorithms (see listing \ref{f:entry2}) is the fundamental implementation of internal scheduling.
2521Note that when a thread is moved from the condition to the AS-stack, it is conceptually split into N pieces, where N is the number of monitors specified in the parameter list.
2522The thread is woken up when all the pieces have popped from the AS-stacks and made active.
2523In this picture, the threads are split into halves but this is only because there are two monitors.
2524For a specific signalling operation every monitor needs a piece of thread on its AS-stack.
2525
2526\begin{figure}
2527\begin{multicols}{2}
2528Entry
2529\begin{cfa}
2530if monitor is free
2531        enter
2532elif already own the monitor
2533        continue
2534else
2535        block
2536increment recursion
2537
2538\end{cfa}
2539\columnbreak
2540Exit
2541\begin{cfa}
2542decrement recursion
2543if recursion == 0
2544        if signal_stack not empty
2545                set_owner to thread
2546                if all monitors ready
2547                        wake-up thread
2548
2549        if entry queue not empty
2550                wake-up thread
2551\end{cfa}
2552\end{multicols}
2553\begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling},label={f:entry2}]
2554\end{cfa}
2555\end{figure}
2556
2557The solution discussed in \ref{s:InternalScheduling} can be seen in the exit routine of listing \ref{f:entry2}.
2558Basically, the solution boils down to having a separate data structure for the condition queue and the AS-stack, and unconditionally transferring ownership of the monitors but only unblocking the thread when the last monitor has transferred ownership.
2559This solution is deadlock safe as well as preventing any potential barging.
2560The data structures used for the AS-stack are reused extensively for external scheduling, but in the case of internal scheduling, the data is allocated using variable-length arrays on the call stack of the @wait@ and @signal_block@ routines.
2561
2562\begin{figure}
2563\begin{center}
2564{\resizebox{0.8\textwidth}{!}{\input{monitor_structs.pstex_t}}}
2565\end{center}
2566\caption{Data structures involved in internal/external scheduling}
2567\label{fig:structs}
2568\end{figure}
2569
2570Figure \ref{fig:structs} shows a high-level representation of these data structures.
2571The main idea behind them is that, a thread cannot contain an arbitrary number of intrusive ``next'' pointers for linking onto monitors.
2572The @condition node@ is the data structure that is queued onto a condition variable and, when signalled, the condition queue is popped and each @condition criterion@ is moved to the AS-stack.
2573Once all the criteria have been popped from their respective AS-stacks, the thread is woken up, which is what is shown in listing \ref{f:entry2}.
2574
2575% ======================================================================
2576% ======================================================================
2577\section{External Scheduling}
2578% ======================================================================
2579% ======================================================================
2580Similarly to internal scheduling, external scheduling for multiple monitors relies on the idea that waiting-thread queues are no longer specific to a single monitor, as mentioned in section \ref{extsched}.
2581For internal scheduling, these queues are part of condition variables, which are still unique for a given scheduling operation (\ie no signal statement uses multiple conditions).
2582However, in the case of external scheduling, there is no equivalent object which is associated with @waitfor@ statements.
2583This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired.
2584These monitors being the only objects that have sufficient lifetime and are available on both sides of the @waitfor@ statement.
2585This requires an algorithm to choose which monitor holds the relevant queue.
2586It is also important that said algorithm be independent of the order in which users list parameters.
2587The proposed algorithm is to fall back on monitor lock ordering (sorting by address) and specify that the monitor that is acquired first is the one with the relevant waiting queue.
2588This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint.
2589
2590This algorithm choice has two consequences:
2591\begin{itemize}
2592        \item The queue of the monitor with the lowest address is no longer a true FIFO queue because threads can be moved to the front of the queue.
2593These queues need to contain a set of monitors for each of the waiting threads.
2594Therefore, another thread whose set contains the same lowest address monitor but different lower priority monitors may arrive first but enter the critical section after a thread with the correct pairing.
2595        \item The queue of the lowest priority monitor is both required and potentially unused.
2596Indeed, since it is not known at compile time which monitor is the monitor which has the lowest address, every monitor needs to have the correct queues even though it is possible that some queues go unused for the entire duration of the program, for example if a monitor is only used in a specific pair.
2597\end{itemize}
2598Therefore, the following modifications need to be made to support external scheduling:
2599\begin{itemize}
2600        \item The threads waiting on the entry queue need to keep track of which routine they are trying to enter, and using which set of monitors.
2601The @mutex@ routine already has all the required information on its stack, so the thread only needs to keep a pointer to that information.
2602        \item The monitors need to keep a mask of acceptable routines.
2603This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it.
2604It also needs storage to keep track of which routine was accepted.
2605Since this information is not specific to any monitor, the monitors actually contain a pointer to an integer on the stack of the waiting thread.
2606Note that if a thread has acquired two monitors but executes a @waitfor@ with only one monitor as a parameter, setting the mask of acceptable routines to both monitors will not cause any problems since the extra monitor will not change ownership regardless.
2607This becomes relevant when @when@ clauses affect the number of monitors passed to a @waitfor@ statement.
2608        \item The entry/exit routines need to be updated as shown in listing \ref{f:entry3}.
2609\end{itemize}
2610
2611\subsection{External Scheduling - Destructors}
2612Finally, to support the ordering inversion of destructors, the code generation needs to be modified to use a special entry routine.
2613This routine is needed because of the storage requirements of the call order inversion.
2614Indeed, when waiting for the destructors, storage is needed for the waiting context and the lifetime of said storage needs to outlive the waiting operation it is needed for.
2615For regular @waitfor@ statements, the call stack of the routine itself matches this requirement but it is no longer the case when waiting for the destructor since it is pushed on to the AS-stack for later.
2616The @waitfor@ semantics can then be adjusted correspondingly, as seen in listing \ref{f:entry-dtor}
2617
2618\begin{figure}
2619\begin{multicols}{2}
2620Entry
2621\begin{cfa}
2622if monitor is free
2623        enter
2624elif already own the monitor
2625        continue
2626elif matches waitfor mask
2627        push criteria to AS-stack
2628        continue
2629else
2630        block
2631increment recursion
2632\end{cfa}
2633\columnbreak
2634Exit
2635\begin{cfa}
2636decrement recursion
2637if recursion == 0
2638        if signal_stack not empty
2639                set_owner to thread
2640                if all monitors ready
2641                        wake-up thread
2642                endif
2643        endif
2644
2645        if entry queue not empty
2646                wake-up thread
2647        endif
2648\end{cfa}
2649\end{multicols}
2650\begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling and external scheduling},label={f:entry3}]
2651\end{cfa}
2652\end{figure}
2653
2654\begin{figure}
2655\begin{multicols}{2}
2656Destructor Entry
2657\begin{cfa}
2658if monitor is free
2659        enter
2660elif already own the monitor
2661        increment recursion
2662        return
2663create wait context
2664if matches waitfor mask
2665        reset mask
2666        push self to AS-stack
2667        baton pass
2668else
2669        wait
2670increment recursion
2671\end{cfa}
2672\columnbreak
2673Waitfor
2674\begin{cfa}
2675if matching thread is already there
2676        if found destructor
2677                push destructor to AS-stack
2678                unlock all monitors
2679        else
2680                push self to AS-stack
2681                baton pass
2682        endif
2683        return
2684endif
2685if non-blocking
2686        Unlock all monitors
2687        Return
2688endif
2689
2690push self to AS-stack
2691set waitfor mask
2692block
2693return
2694\end{cfa}
2695\end{multicols}
2696\begin{cfa}[caption={Pseudo code for the \protect\lstinline|waitfor| routine and the \protect\lstinline|mutex| entry routine for destructors},label={f:entry-dtor}]
2697\end{cfa}
2698\end{figure}
2699
2700
2701% ======================================================================
2702% ======================================================================
2703\section{Putting It All Together}
2704% ======================================================================
2705% ======================================================================
2706
2707
2708\section{Threads As Monitors}
2709As it was subtly alluded in section \ref{threads}, @thread@s in \CFA are in fact monitors, which means that all monitor features are available when using threads.
2710For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine:
2711\begin{figure}
2712\begin{cfa}[caption={Toy simulator using \protect\lstinline|thread|s and \protect\lstinline|monitor|s.},label={f:engine-v1}]
2713// Visualization declaration
2714thread Renderer {} renderer;
2715Frame * simulate( Simulator & this );
2716
2717// Simulation declaration
2718thread Simulator{} simulator;
2719void render( Renderer & this );
2720
2721// Blocking call used as communication
2722void draw( Renderer & mutex this, Frame * frame );
2723
2724// Simulation loop
2725void main( Simulator & this ) {
2726        while( true ) {
2727                Frame * frame = simulate( this );
2728                draw( renderer, frame );
2729        }
2730}
2731
2732// Rendering loop
2733void main( Renderer & this ) {
2734        while( true ) {
2735                waitfor( draw, this );
2736                render( this );
2737        }
2738}
2739\end{cfa}
2740\end{figure}
2741One of the obvious complaints of the previous code snippet (other than its toy-like simplicity) is that it does not handle exit conditions and just goes on forever.
2742Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner:
2743\begin{figure}
2744\begin{cfa}[caption={Same toy simulator with proper termination condition.},label={f:engine-v2}]
2745// Visualization declaration
2746thread Renderer {} renderer;
2747Frame * simulate( Simulator & this );
2748
2749// Simulation declaration
2750thread Simulator{} simulator;
2751void render( Renderer & this );
2752
2753// Blocking call used as communication
2754void draw( Renderer & mutex this, Frame * frame );
2755
2756// Simulation loop
2757void main( Simulator & this ) {
2758        while( true ) {
2759                Frame * frame = simulate( this );
2760                draw( renderer, frame );
2761
2762                // Exit main loop after the last frame
2763                if( frame->is_last ) break;
2764        }
2765}
2766
2767// Rendering loop
2768void main( Renderer & this ) {
2769        while( true ) {
2770                   waitfor( draw, this );
2771                or waitfor( ^?{}, this ) {
2772                        // Add an exit condition
2773                        break;
2774                }
2775
2776                render( this );
2777        }
2778}
2779
2780// Call destructor for simulator once simulator finishes
2781// Call destructor for renderer to signify shutdown
2782\end{cfa}
2783\end{figure}
2784
2785\section{Fibers \& Threads}
2786As mentioned in section \ref{preemption}, \CFA uses preemptive threads by default but can use fibers on demand.
2787Currently, using fibers is done by adding the following line of code to the program~:
2788\begin{cfa}
2789unsigned int default_preemption() {
2790        return 0;
2791}
2792\end{cfa}
2793This routine is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice, \ie no preemption.
2794However, once clusters are fully implemented, it will be possible to create fibers and \textbf{uthread} in the same system, as in listing \ref{f:fiber-uthread}
2795\begin{figure}
2796\lstset{language=CFA,deletedelim=**[is][]{`}{`}}
2797\begin{cfa}[caption={Using fibers and \textbf{uthread} side-by-side in \CFA},label={f:fiber-uthread}]
2798// Cluster forward declaration
2799struct cluster;
2800
2801// Processor forward declaration
2802struct processor;
2803
2804// Construct clusters with a preemption rate
2805void ?{}(cluster& this, unsigned int rate);
2806// Construct processor and add it to cluster
2807void ?{}(processor& this, cluster& cluster);
2808// Construct thread and schedule it on cluster
2809void ?{}(thread& this, cluster& cluster);
2810
2811// Declare two clusters
2812cluster thread_cluster = { 10`ms };                     // Preempt every 10 ms
2813cluster fibers_cluster = { 0 };                         // Never preempt
2814
2815// Construct 4 processors
2816processor processors[4] = {
2817        //2 for the thread cluster
2818        thread_cluster;
2819        thread_cluster;
2820        //2 for the fibers cluster
2821        fibers_cluster;
2822        fibers_cluster;
2823};
2824
2825// Declares thread
2826thread UThread {};
2827void ?{}(UThread& this) {
2828        // Construct underlying thread to automatically
2829        // be scheduled on the thread cluster
2830        (this){ thread_cluster }
2831}
2832
2833void main(UThread & this);
2834
2835// Declares fibers
2836thread Fiber {};
2837void ?{}(Fiber& this) {
2838        // Construct underlying thread to automatically
2839        // be scheduled on the fiber cluster
2840        (this.__thread){ fibers_cluster }
2841}
2842
2843void main(Fiber & this);
2844\end{cfa}
2845\end{figure}
2846
2847
2848% ======================================================================
2849% ======================================================================
2850\section{Performance Results} \label{results}
2851% ======================================================================
2852% ======================================================================
2853\section{Machine Setup}
2854Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks.
2855All tests were made on this machine.
2856\begin{table}
2857\begin{center}
2858\begin{tabular}{| l | r | l | r |}
2859\hline
2860Architecture            & x86\_64                       & NUMA node(s)  & 8 \\
2861\hline
2862CPU op-mode(s)          & 32-bit, 64-bit                & Model name    & AMD Opteron\texttrademark  Processor 6380 \\
2863\hline
2864Byte Order                      & Little Endian                 & CPU Freq              & 2.5\si{\giga\hertz} \\
2865\hline
2866CPU(s)                  & 64                            & L1d cache     & \SI{16}{\kibi\byte} \\
2867\hline
2868Thread(s) per core      & 2                             & L1i cache     & \SI{64}{\kibi\byte} \\
2869\hline
2870Core(s) per socket      & 8                             & L2 cache              & \SI{2048}{\kibi\byte} \\
2871\hline
2872Socket(s)                       & 4                             & L3 cache              & \SI{6144}{\kibi\byte} \\
2873\hline
2874\hline
2875Operating system                & Ubuntu 16.04.3 LTS    & Kernel                & Linux 4.4-97-generic \\
2876\hline
2877Compiler                        & GCC 6.3               & Translator    & CFA 1 \\
2878\hline
2879Java version            & OpenJDK-9             & Go version    & 1.9.2 \\
2880\hline
2881\end{tabular}
2882\end{center}
2883\caption{Machine setup used for the tests}
2884\label{tab:machine}
2885\end{table}
2886
2887\section{Micro Benchmarks}
2888All benchmarks are run using the same harness to produce the results, seen as the @BENCH()@ macro in the following examples.
2889This macro uses the following logic to benchmark the code:
2890\begin{cfa}
2891#define BENCH(run, result) \
2892        before = gettime(); \
2893        run; \
2894        after  = gettime(); \
2895        result = (after - before) / N;
2896\end{cfa}
2897The method used to get time is @clock_gettime(CLOCK_THREAD_CPUTIME_ID);@.
2898Each benchmark is using many iterations of a simple call to measure the cost of the call.
2899The specific number of iterations depends on the specific benchmark.
2900
2901\subsection{Context-Switching}
2902The first interesting benchmark is to measure how long context-switches take.
2903The simplest approach to do this is to yield on a thread, which executes a 2-step context switch.
2904Yielding causes the thread to context-switch to the scheduler and back, more precisely: from the \textbf{uthread} to the \textbf{kthread} then from the \textbf{kthread} back to the same \textbf{uthread} (or a different one in the general case).
2905In order to make the comparison fair, coroutines also execute a 2-step context-switch by resuming another coroutine which does nothing but suspending in a tight loop, which is a resume/suspend cycle instead of a yield.
2906Figure~\ref{f:ctx-switch} shows the code for coroutines and threads with the results in table \ref{tab:ctx-switch}.
2907All omitted tests are functionally identical to one of these tests.
2908The difference between coroutines and threads can be attributed to the cost of scheduling.
2909\begin{figure}
2910\begin{multicols}{2}
2911\CFA Coroutines
2912\begin{cfa}
2913coroutine GreatSuspender {};
2914void main(GreatSuspender& this) {
2915        while(true) { suspend(); }
2916}
2917int main() {
2918        GreatSuspender s;
2919        resume(s);
2920        BENCH(
2921                for(size_t i=0; i<n; i++) {
2922                        resume(s);
2923                },
2924                result
2925        )
2926        printf("%llu\n", result);
2927}
2928\end{cfa}
2929\columnbreak
2930\CFA Threads
2931\begin{cfa}
2932
2933
2934
2935
2936int main() {
2937
2938
2939        BENCH(
2940                for(size_t i=0; i<n; i++) {
2941                        yield();
2942                },
2943                result
2944        )
2945        printf("%llu\n", result);
2946}
2947\end{cfa}
2948\end{multicols}
2949\begin{cfa}[caption={\CFA benchmark code used to measure context-switches for coroutines and threads.},label={f:ctx-switch}]
2950\end{cfa}
2951\end{figure}
2952
2953\begin{table}
2954\begin{center}
2955\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
2956\cline{2-4}
2957\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
2958\hline
2959Kernel Thread   & 241.5 & 243.86        & 5.08 \\
2960\CFA Coroutine  & 38            & 38            & 0    \\
2961\CFA Thread             & 103           & 102.96        & 2.96 \\
2962\uC Coroutine   & 46            & 45.86 & 0.35 \\
2963\uC Thread              & 98            & 99.11 & 1.42 \\
2964Goroutine               & 150           & 149.96        & 3.16 \\
2965Java Thread             & 289           & 290.68        & 8.72 \\
2966\hline
2967\end{tabular}
2968\end{center}
2969\caption{Context Switch comparison.
2970All numbers are in nanoseconds(\si{\nano\second})}
2971\label{tab:ctx-switch}
2972\end{table}
2973
2974\subsection{Mutual-Exclusion}
2975The next interesting benchmark is to measure the overhead to enter/leave a critical-section.
2976For monitors, the simplest approach is to measure how long it takes to enter and leave a monitor routine.
2977Figure~\ref{f:mutex} shows the code for \CFA.
2978To 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.
2979The results can be shown in table \ref{tab:mutex}.
2980
2981\begin{figure}
2982\begin{cfa}[caption={\CFA benchmark code used to measure mutex routines.},label={f:mutex}]
2983monitor M {};
2984void __attribute__((noinline)) call( M & mutex m /*, m2, m3, m4*/ ) {}
2985
2986int main() {
2987        M m/*, m2, m3, m4*/;
2988        BENCH(
2989                for(size_t i=0; i<n; i++) {
2990                        call(m/*, m2, m3, m4*/);
2991                },
2992                result
2993        )
2994        printf("%llu\n", result);
2995}
2996\end{cfa}
2997\end{figure}
2998
2999\begin{table}
3000\begin{center}
3001\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
3002\cline{2-4}
3003\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3004\hline
3005C routine                                               & 2             & 2             & 0    \\
3006FetchAdd + FetchSub                             & 26            & 26            & 0    \\
3007Pthreads Mutex Lock                             & 31            & 31.86 & 0.99 \\
3008\uC @monitor@ member routine            & 30            & 30            & 0    \\
3009\CFA @mutex@ routine, 1 argument        & 41            & 41.57 & 0.9  \\
3010\CFA @mutex@ routine, 2 argument        & 76            & 76.96 & 1.57 \\
3011\CFA @mutex@ routine, 4 argument        & 145           & 146.68        & 3.85 \\
3012Java synchronized routine                       & 27            & 28.57 & 2.6  \\
3013\hline
3014\end{tabular}
3015\end{center}
3016\caption{Mutex routine comparison.
3017All numbers are in nanoseconds(\si{\nano\second})}
3018\label{tab:mutex}
3019\end{table}
3020
3021\subsection{Internal Scheduling}
3022The internal-scheduling benchmark measures the cost of waiting on and signalling a condition variable.
3023Figure~\ref{f:int-sched} shows the code for \CFA, with results table \ref{tab:int-sched}.
3024As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
3025
3026\begin{figure}
3027\begin{cfa}[caption={Benchmark code for internal scheduling},label={f:int-sched}]
3028volatile int go = 0;
3029condition c;
3030monitor M {};
3031M m1;
3032
3033void __attribute__((noinline)) do_call( M & mutex a1 ) { signal(c); }
3034
3035thread T {};
3036void ^?{}( T & mutex this ) {}
3037void main( T & this ) {
3038        while(go == 0) { yield(); }
3039        while(go == 1) { do_call(m1); }
3040}
3041int  __attribute__((noinline)) do_wait( M & mutex a1 ) {
3042        go = 1;
3043        BENCH(
3044                for(size_t i=0; i<n; i++) {
3045                        wait(c);
3046                },
3047                result
3048        )
3049        printf("%llu\n", result);
3050        go = 0;
3051        return 0;
3052}
3053int main() {
3054        T t;
3055        return do_wait(m1);
3056}
3057\end{cfa}
3058\end{figure}
3059
3060\begin{table}
3061\begin{center}
3062\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
3063\cline{2-4}
3064\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3065\hline
3066Pthreads Condition Variable                     & 5902.5        & 6093.29       & 714.78 \\
3067\uC @signal@                                    & 322           & 323   & 3.36   \\
3068\CFA @signal@, 1 @monitor@      & 352.5 & 353.11        & 3.66   \\
3069\CFA @signal@, 2 @monitor@      & 430           & 430.29        & 8.97   \\
3070\CFA @signal@, 4 @monitor@      & 594.5 & 606.57        & 18.33  \\
3071Java @notify@                           & 13831.5       & 15698.21      & 4782.3 \\
3072\hline
3073\end{tabular}
3074\end{center}
3075\caption{Internal scheduling comparison.
3076All numbers are in nanoseconds(\si{\nano\second})}
3077\label{tab:int-sched}
3078\end{table}
3079
3080\subsection{External Scheduling}
3081The Internal scheduling benchmark measures the cost of the @waitfor@ statement (@_Accept@ in \uC).
3082Figure~\ref{f:ext-sched} shows the code for \CFA, with results in table \ref{tab:ext-sched}.
3083As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
3084
3085\begin{figure}
3086\begin{cfa}[caption={Benchmark code for external scheduling},label={f:ext-sched}]
3087volatile int go = 0;
3088monitor M {};
3089M m1;
3090thread T {};
3091
3092void __attribute__((noinline)) do_call( M & mutex a1 ) {}
3093
3094void ^?{}( T & mutex this ) {}
3095void main( T & this ) {
3096        while(go == 0) { yield(); }
3097        while(go == 1) { do_call(m1); }
3098}
3099int  __attribute__((noinline)) do_wait( M & mutex a1 ) {
3100        go = 1;
3101        BENCH(
3102                for(size_t i=0; i<n; i++) {
3103                        waitfor(call, a1);
3104                },
3105                result
3106        )
3107        printf("%llu\n", result);
3108        go = 0;
3109        return 0;
3110}
3111int main() {
3112        T t;
3113        return do_wait(m1);
3114}
3115\end{cfa}
3116\end{figure}
3117
3118\begin{table}
3119\begin{center}
3120\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
3121\cline{2-4}
3122\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3123\hline
3124\uC @Accept@                                    & 350           & 350.61        & 3.11  \\
3125\CFA @waitfor@, 1 @monitor@     & 358.5 & 358.36        & 3.82  \\
3126\CFA @waitfor@, 2 @monitor@     & 422           & 426.79        & 7.95  \\
3127\CFA @waitfor@, 4 @monitor@     & 579.5 & 585.46        & 11.25 \\
3128\hline
3129\end{tabular}
3130\end{center}
3131\caption{External scheduling comparison.
3132All numbers are in nanoseconds(\si{\nano\second})}
3133\label{tab:ext-sched}
3134\end{table}
3135
3136
3137\subsection{Object Creation}
3138Finally, the last benchmark measures the cost of creation for concurrent objects.
3139Figure~\ref{f:creation} shows the code for @pthread@s and \CFA threads, with results shown in table \ref{tab:creation}.
3140As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
3141The only note here is that the call stacks of \CFA coroutines are lazily created, therefore without priming the coroutine, the creation cost is very low.
3142
3143\begin{figure}
3144\begin{center}
3145@pthread@
3146\begin{cfa}
3147int main() {
3148        BENCH(
3149                for(size_t i=0; i<n; i++) {
3150                        pthread_t thread;
3151                        if(pthread_create(&thread,NULL,foo,NULL)<0) {
3152                                perror( "failure" );
3153                                return 1;
3154                        }
3155
3156                        if(pthread_join(thread, NULL)<0) {
3157                                perror( "failure" );
3158                                return 1;
3159                        }
3160                },
3161                result
3162        )
3163        printf("%llu\n", result);
3164}
3165\end{cfa}
3166
3167
3168
3169\CFA Threads
3170\begin{cfa}
3171int main() {
3172        BENCH(
3173                for(size_t i=0; i<n; i++) {
3174                        MyThread m;
3175                },
3176                result
3177        )
3178        printf("%llu\n", result);
3179}
3180\end{cfa}
3181\end{center}
3182\caption{Benchmark code for \protect\lstinline|pthread|s and \CFA to measure object creation}
3183\label{f:creation}
3184\end{figure}
3185
3186\begin{table}
3187\begin{center}
3188\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
3189\cline{2-4}
3190\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3191\hline
3192Pthreads                        & 26996 & 26984.71      & 156.6  \\
3193\CFA Coroutine Lazy     & 6             & 5.71  & 0.45   \\
3194\CFA Coroutine Eager    & 708           & 706.68        & 4.82   \\
3195\CFA Thread                     & 1173.5        & 1176.18       & 15.18  \\
3196\uC Coroutine           & 109           & 107.46        & 1.74   \\
3197\uC Thread                      & 526           & 530.89        & 9.73   \\
3198Goroutine                       & 2520.5        & 2530.93       & 61,56  \\
3199Java Thread                     & 91114.5       & 92272.79      & 961.58 \\
3200\hline
3201\end{tabular}
3202\end{center}
3203\caption{Creation comparison.
3204All numbers are in nanoseconds(\si{\nano\second}).}
3205\label{tab:creation}
3206\end{table}
3207
3208
3209
3210\section{Conclusion}
3211This paper has achieved a minimal concurrency \textbf{api} that is simple, efficient and usable as the basis for higher-level features.
3212The approach presented is based on a lightweight thread-system for parallelism, which sits on top of clusters of processors.
3213This M:N model is judged to be both more efficient and allow more flexibility for users.
3214Furthermore, this document introduces monitors as the main concurrency tool for users.
3215This paper also offers a novel approach allowing multiple monitors to be accessed simultaneously without running into the Nested Monitor Problem~\cite{Lister77}.
3216It also offers a full implementation of the concurrency runtime written entirely in \CFA, effectively the largest \CFA code base to date.
3217
3218
3219% ======================================================================
3220% ======================================================================
3221\section{Future Work}
3222% ======================================================================
3223% ======================================================================
3224
3225\subsection{Performance} \label{futur:perf}
3226This paper presents a first implementation of the \CFA concurrency runtime.
3227Therefore, there is still significant work to improve performance.
3228Many of the data structures and algorithms may change in the future to more efficient versions.
3229For example, the number of monitors in a single bulk acquire is only bound by the stack size, this is probably unnecessarily generous.
3230It may be possible that limiting the number helps increase performance.
3231However, it is not obvious that the benefit would be significant.
3232
3233\subsection{Flexible Scheduling} \label{futur:sched}
3234An important part of concurrency is scheduling.
3235Different scheduling algorithms can affect performance (both in terms of average and variation).
3236However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
3237One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted to the requirements of the workload.
3238However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms.
3239For example, a web server could attach Type-of-Service information to threads and have a ``ToS aware'' scheduling algorithm tailored to this specific web server.
3240This path of flexible schedulers will be explored for \CFA.
3241
3242\subsection{Non-Blocking I/O} \label{futur:nbio}
3243While most of the parallelism tools are aimed at data parallelism and control-flow parallelism, many modern workloads are not bound on computation but on IO operations, a common case being web servers and XaaS (anything as a service).
3244These types of workloads often require significant engineering around amortizing costs of blocking IO operations.
3245At its core, non-blocking I/O is an operating system level feature that allows queuing IO operations (\eg network operations) and registering for notifications instead of waiting for requests to complete.
3246In this context, the role of the language makes Non-Blocking IO easily available and with low overhead.
3247The current trend is to use asynchronous programming using tools like callbacks and/or futures and promises, which can be seen in frameworks like Node.js~\cite{NodeJs} for JavaScript, Spring MVC~\cite{SpringMVC} for Java and Django~\cite{Django} for Python.
3248However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear.
3249
3250\subsection{Other Concurrency Tools} \label{futur:tools}
3251While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
3252Examples of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, executors and actors.
3253These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
3254
3255\subsection{Implicit Threading} \label{futur:implcit}
3256Simpler applications can benefit greatly from having implicit parallelism.
3257That is, parallelism that does not rely on the user to write concurrency.
3258This type of parallelism can be achieved both at the language level and at the library level.
3259The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithms~\cite{uC++book}.
3260Table \ref{f:parfor} shows three different code examples that accomplish point-wise sums of large arrays.
3261Note that none of these examples explicitly declare any concurrency or parallelism objects.
3262
3263\begin{table}
3264\begin{center}
3265\begin{tabular}[t]{|c|c|c|}
3266Sequential & Library Parallel & Language Parallel \\
3267\begin{cfa}[tabsize=3]
3268void big_sum(
3269        int* a, int* b,
3270        int* o,
3271        size_t len)
3272{
3273        for(
3274                int i = 0;
3275                i < len;
3276                ++i )
3277        {
3278                o[i]=a[i]+b[i];
3279        }
3280}
3281
3282
3283
3284
3285
3286int* a[10000];
3287int* b[10000];
3288int* c[10000];
3289//... fill in a & b
3290big_sum(a,b,c,10000);
3291\end{cfa} &\begin{cfa}[tabsize=3]
3292void big_sum(
3293        int* a, int* b,
3294        int* o,
3295        size_t len)
3296{
3297        range ar(a, a+len);
3298        range br(b, b+len);
3299        range or(o, o+len);
3300        parfor( ai, bi, oi,
3301        [](     int* ai,
3302                int* bi,
3303                int* oi)
3304        {
3305                oi=ai+bi;
3306        });
3307}
3308
3309
3310int* a[10000];
3311int* b[10000];
3312int* c[10000];
3313//... fill in a & b
3314big_sum(a,b,c,10000);
3315\end{cfa}&\begin{cfa}[tabsize=3]
3316void big_sum(
3317        int* a, int* b,
3318        int* o,
3319        size_t len)
3320{
3321        parfor (ai,bi,oi)
3322            in (a, b, o )
3323        {
3324                oi = ai + bi;
3325        }
3326}
3327
3328
3329
3330
3331
3332
3333
3334int* a[10000];
3335int* b[10000];
3336int* c[10000];
3337//... fill in a & b
3338big_sum(a,b,c,10000);
3339\end{cfa}
3340\end{tabular}
3341\end{center}
3342\caption{For loop to sum numbers: Sequential, using library parallelism and language parallelism.}
3343\label{f:parfor}
3344\end{table}
3345
3346Implicit parallelism is a restrictive solution and therefore has its limitations.
3347However, it is a quick and simple approach to parallelism, which may very well be sufficient for smaller applications and reduces the amount of boilerplate needed to start benefiting from parallelism in modern CPUs.
3348
3349
3350% A C K N O W L E D G E M E N T S
3351% -------------------------------
3352\section{Acknowledgements}
3353
3354Thanks to Aaron Moss, Rob Schluntz and Andrew Beach for their work on the \CFA project as well as all the discussions which helped concretize the ideas in this paper.
3355Partial funding was supplied by the Natural Sciences and Engineering Research Council of Canada and a corporate partnership with Huawei Ltd.
3356
3357
3358% B I B L I O G R A P H Y
3359% -----------------------------
3360%\bibliographystyle{plain}
3361\bibliography{pl,local}
3362
3363
3364\end{document}
3365
3366% Local Variables: %
3367% tab-width: 4 %
3368% fill-column: 120 %
3369% compile-command: "make" %
3370% End: %
Note: See TracBrowser for help on using the repository browser.