source: doc/papers/concurrency/Paper.tex @ 90cedbdd

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerwith_gc
Last change on this file since 90cedbdd was 90cedbdd, checked in by Peter A. Buhr <pabuhr@…>, 4 years ago

more updates

  • Property mode set to 100644
File size: 157.9 KB
Line 
1\documentclass[AMA,STIX1COL]{WileyNJD-v2}
2
3\articletype{RESEARCH ARTICLE}%
4
5\received{26 April 2016}
6\revised{6 June 2016}
7\accepted{6 June 2016}
8
9\raggedbottom
10
11%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
12
13% Latex packages used in the document.
14
15\usepackage{epic,eepic}
16\usepackage{xspace}
17\usepackage{comment}
18\usepackage{upquote}                                            % switch curled `'" to straight
19\usepackage{listings}                                           % format program code
20\usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig}
21\renewcommand{\thesubfigure}{(\Alph{subfigure})}
22\captionsetup{justification=raggedright,singlelinecheck=false}
23\usepackage{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 synchronization and mutual exclusion, 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 an 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 basics of \CFA revolve around 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 is necessary to prevent the need for long prefixes and other naming conventions to prevent name clashes.
414As seen in Section~\ref{basics}, routine @main@ is heavily overloaded.
415
416Variable overloading is useful in the parallel semantics of the @with@ statement for fields with the same name:
417\begin{cfa}
418struct S { int `i`; int j; double m; } s;
419struct T { int `i`; int k; int m; } t;
420with ( s, t ) {
421        j + k;                                                                  $\C{// unambiguous, s.j + t.k}$
422        m = 5.0;                                                                $\C{// unambiguous, s.m = 5.0}$
423        m = 1;                                                                  $\C{// unambiguous, t.m = 1}$
424        int a = m;                                                              $\C{// unambiguous, a = t.m }$
425        double b = m;                                                   $\C{// unambiguous, b = s.m}$
426        int c = `s.i` + `t.i`;                                  $\C{// unambiguous, qualification}$
427        (double)m;                                                              $\C{// unambiguous, cast s.m}$
428}
429\end{cfa}
430For parallel semantics, both @s.i@ and @t.i@ are visible the same type, so only @i@ is ambiguous without qualification.
431
432
433\subsection{Operators}
434
435Overloading also extends to operators.
436Operator-overloading syntax creates a routine name with an operator symbol and question marks for the operands:
437\begin{cquote}
438\lstDeleteShortInline@%
439\begin{tabular}{@{}ll@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
440\begin{cfa}
441int ++? (int op);
442int ?++ (int op);
443int `?+?` (int op1, int op2);
444int ?<=?(int op1, int op2);
445int ?=? (int & op1, int op2);
446int ?+=?(int & op1, int op2);
447\end{cfa}
448&
449\begin{cfa}
450// unary prefix increment
451// unary postfix increment
452// binary plus
453// binary less than
454// binary assignment
455// binary plus-assignment
456\end{cfa}
457&
458\begin{cfa}
459struct S { int i, j; };
460S `?+?`( S op1, S op2) { // add two structures
461        return (S){op1.i + op2.i, op1.j + op2.j};
462}
463S s1 = {1, 2}, s2 = {2, 3}, s3;
464s3 = s1 `+` s2;         // compute sum: s3 == {2, 5}
465\end{cfa}
466\end{tabular}
467\lstMakeShortInline@%
468\end{cquote}
469While concurrency does not use operator overloading directly, it provides an introduction for the syntax of constructors.
470
471
472\subsection{Parametric Polymorphism}
473\label{s:ParametricPolymorphism}
474
475The 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.
476For example, the following sum routine works for any type that supports construction from 0 and addition:
477\begin{cfa}
478forall( otype T | { void `?{}`( T *, zero_t ); T `?+?`( T, T ); } ) // constraint type, 0 and +
479T sum( T a[$\,$], size_t size ) {
480        `T` total = { `0` };                                    $\C{// initialize by 0 constructor}$
481        for ( size_t i = 0; i < size; i += 1 )
482                total = total `+` a[i];                         $\C{// select appropriate +}$
483        return total;
484}
485S sa[5];
486int i = sum( sa, 5 );                                           $\C{// use S's 0 construction and +}$
487\end{cfa}
488
489\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:
490\begin{cfa}
491trait `sumable`( otype T ) {
492        void `?{}`( T &, zero_t );                              $\C{// 0 literal constructor}$
493        T `?+?`( T, T );                                                $\C{// assortment of additions}$
494        T ?+=?( T &, T );
495        T ++?( T & );
496        T ?++( T & );
497};
498forall( otype T `| sumable( T )` )                      $\C{// use trait}$
499T sum( T a[$\,$], size_t size );
500\end{cfa}
501
502Assertions can be @otype@ or @dtype@.
503@otype@ refers to a ``complete'' object, \ie an object has a size, default constructor, copy constructor, destructor and an assignment operator.
504@dtype@ only guarantees an object has a size and alignment.
505
506Using the return type for discrimination, it is possible to write a type-safe @alloc@ based on the C @malloc@:
507\begin{cfa}
508forall( dtype T | sized(T) ) T * alloc( void ) { return (T *)malloc( sizeof(T) ); }
509int * ip = alloc();                                                     $\C{// select type and size from left-hand side}$
510double * dp = alloc();
511struct S {...} * sp = alloc();
512\end{cfa}
513where the return type supplies the type/size of the allocation, which is impossible in most type systems.
514
515
516\subsection{Constructors / Destructors}
517
518Object lifetime is a challenge in non-managed programming languages.
519\CFA responds with \CC-like constructors and destructors:
520\begin{cfa}
521struct VLA { int len, * data; };                        $\C{// variable length array of integers}$
522void ?{}( VLA & vla ) with ( vla ) { len = 10;  data = alloc( len ); }  $\C{// default constructor}$
523void ?{}( VLA & vla, int size, char fill ) with ( vla ) { len = size;  data = alloc( len, fill ); } // initialization
524void ?{}( VLA & vla, VLA other ) { vla.len = other.len;  vla.data = other.data; } $\C{// copy, shallow}$
525void ^?{}( VLA & vla ) with ( vla ) { free( data ); } $\C{// destructor}$
526{
527        VLA  x,            y = { 20, 0x01 },     z = y; $\C{// z points to y}$
528        //    x{};         y{ 20, 0x01 };          z{ z, y };
529        ^x{};                                                                   $\C{// deallocate x}$
530        x{};                                                                    $\C{// reallocate x}$
531        z{ 5, 0xff };                                                   $\C{// reallocate z, not pointing to y}$
532        ^y{};                                                                   $\C{// deallocate y}$
533        y{ x };                                                                 $\C{// reallocate y, points to x}$
534        x{};                                                                    $\C{// reallocate x, not pointing to y}$
535        //  ^z{}^y{}^x{};
536}
537\end{cfa}
538Like \CC, construction is implicit on allocation (stack/heap) and destruction is implicit on deallocation.
539The object and all their fields are constructed/destructed.
540\CFA also provides @new@ and @delete@, which behave like @malloc@ and @free@, in addition to constructing and destructing objects:
541\begin{cfa}
542{       struct S s = {10};                                              $\C{// allocation, call constructor}$
543        ...
544}                                                                                       $\C{// deallocation, call destructor}$
545struct S * s = new();                                           $\C{// allocation, call constructor}$
546...
547delete( s );                                                            $\C{// deallocation, call destructor}$
548\end{cfa}
549\CFA concurrency uses object lifetime as a means of synchronization and/or mutual exclusion.
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:
730\begin{cfa}
731`coroutine` Fib { int fn; };
732\end{cfa}
733which provides communication, @fn@, for the \newterm{coroutine main}, @main@, which runs on the coroutine stack, and possibly multiple interface routines @next@.
734Like 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.
735The 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.
736The interface routine @next@, takes a Fibonacci instance and context switches to it using @resume@;
737on restart, the Fibonacci field, @fn@, contains the next value in the sequence, which is returned.
738The first @resume@ is special because it cocalls the coroutine at its coroutine main and allocates the stack;
739when the coroutine main returns, its stack is deallocated.
740Hence, @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.
741Figure~\ref{f:Coroutine1State} shows the coroutine version of the C version in Figure~\ref{f:ExternalState}.
742Coroutine generators are called \newterm{output coroutines} because values are only returned.
743
744Figure~\ref{f:CFAFmt} shows an \newterm{input coroutine}, @Format@, for restructuring text into groups of characters of fixed-size blocks.
745For example, the input of the left is reformatted into the output on the right.
746\begin{quote}
747\tt
748\begin{tabular}{@{}l|l@{}}
749\multicolumn{1}{c|}{\textbf{\textrm{input}}} & \multicolumn{1}{c}{\textbf{\textrm{output}}} \\
750abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
751&
752\begin{tabular}[t]{@{}lllll@{}}
753abcd    & efgh  & ijkl  & mnop  & qrst  \\
754uvwx    & yzab  & cdef  & ghij  & klmn  \\
755opqr    & stuv  & wxyz  &               &
756\end{tabular}
757\end{tabular}
758\end{quote}
759The 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.
760The destruction provides a newline if formatted text ends with a full line.
761Figure~\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.
762
763\begin{figure}
764\centering
765\newbox\myboxA
766\begin{lrbox}{\myboxA}
767\begin{cfa}[aboveskip=0pt,belowskip=0pt]
768`coroutine` Format {
769        char ch;   // used for communication
770        int g, b;  // global because used in destructor
771};
772void main( Format & fmt ) with( fmt ) {
773        for ( ;; ) {   
774                for ( g = 0; g < 5; g += 1 ) {      // group
775                        for ( b = 0; b < 4; b += 1 ) { // block
776                                `suspend();`
777                                sout | ch;              // separator
778                        }
779                        sout | "  ";               // separator
780                }
781                sout | endl;
782        }
783}
784void ?{}( Format & fmt ) { `resume( fmt );` }
785void ^?{}( Format & fmt ) with( fmt ) {
786        if ( g != 0 || b != 0 ) sout | endl;
787}
788void format( Format & fmt ) {
789        `resume( fmt );`
790}
791int main() {
792        Format fmt;
793        eof: for ( ;; ) {
794                sin | fmt.ch;
795          if ( eof( sin ) ) break eof;
796                format( fmt );
797        }
798}
799\end{cfa}
800\end{lrbox}
801
802\newbox\myboxB
803\begin{lrbox}{\myboxB}
804\begin{cfa}[aboveskip=0pt,belowskip=0pt]
805struct Format {
806        char ch;
807        int g, b;
808};
809void format( struct Format * fmt ) {
810        if ( fmt->ch != -1 ) {      // not EOF ?
811                printf( "%c", fmt->ch );
812                fmt->b += 1;
813                if ( fmt->b == 4 ) {  // block
814                        printf( "  " );      // separator
815                        fmt->b = 0;
816                        fmt->g += 1;
817                }
818                if ( fmt->g == 5 ) {  // group
819                        printf( "\n" );     // separator
820                        fmt->g = 0;
821                }
822        } else {
823                if ( fmt->g != 0 || fmt->b != 0 ) printf( "\n" );
824        }
825}
826int main() {
827        struct Format fmt = { 0, 0, 0 };
828        for ( ;; ) {
829                scanf( "%c", &fmt.ch );
830          if ( feof( stdin ) ) break;
831                format( &fmt );
832        }
833        fmt.ch = -1;
834        format( &fmt );
835}
836\end{cfa}
837\end{lrbox}
838\subfloat[\CFA Coroutine]{\label{f:CFAFmt}\usebox\myboxA}
839\qquad
840\subfloat[C Linearized]{\label{f:CFmt}\usebox\myboxB}
841\caption{Formatting text into lines of 5 blocks of 4 characters.}
842\label{f:fmt-line}
843\end{figure}
844
845The 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
846However, there is no stack growth because @resume@/@suspend@ context switch to existing stack-frames rather than create new ones.
847\newterm{Symmetric (full) coroutine}s have a coroutine call a resuming routine for another coroutine, which eventually forms a resuming-call cycle.
848(The trivial cycle is a coroutine resuming itself.)
849This control flow is similar to recursion for normal routines, but again there is no stack growth from the context switch.
850
851\begin{figure}
852\centering
853\lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $
854\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
855\begin{cfa}
856`coroutine` Prod {
857        Cons & c;
858        int N, money, receipt;
859};
860void main( Prod & prod ) with( prod ) {
861        // 1st resume starts here
862        for ( int i = 0; i < N; i += 1 ) {
863                int p1 = random( 100 ), p2 = random( 100 );
864                sout | p1 | " " | p2 | endl;
865                int status = delivery( c, p1, p2 );
866                sout | " $" | money | endl | status | endl;
867                receipt += 1;
868        }
869        stop( c );
870        sout | "prod stops" | endl;
871}
872int payment( Prod & prod, int money ) {
873        prod.money = money;
874        `resume( prod );`
875        return prod.receipt;
876}
877void start( Prod & prod, int N, Cons &c ) {
878        &prod.c = &c;
879        prod.[N, receipt] = [N, 0];
880        `resume( prod );`
881}
882int main() {
883        Prod prod;
884        Cons cons = { prod };
885        start( prod, 5, cons );
886}
887\end{cfa}
888&
889\begin{cfa}
890`coroutine` Cons {
891        Prod & p;
892        int p1, p2, status;
893        _Bool done;
894};
895void ?{}( Cons & cons, Prod & p ) {
896        &cons.p = &p;
897        cons.[status, done ] = [0, false];
898}
899void ^?{}( Cons & cons ) {}
900void main( Cons & cons ) with( cons ) {
901        // 1st resume starts here
902        int money = 1, receipt;
903        for ( ; ! done; ) {
904                sout | p1 | " " | p2 | endl | " $" | money | endl;
905                status += 1;
906                receipt = payment( p, money );
907                sout | " #" | receipt | endl;
908                money += 1;
909        }
910        sout | "cons stops" | endl;
911}
912int delivery( Cons & cons, int p1, int p2 ) {
913        cons.[p1, p2] = [p1, p2];
914        `resume( cons );`
915        return cons.status;
916}
917void stop( Cons & cons ) {
918        cons.done = true;
919        `resume( cons );`
920}
921\end{cfa}
922\end{tabular}
923\caption{Producer / consumer: resume-resume cycle, bi-directional communication}
924\label{f:ProdCons}
925\end{figure}
926
927Figure~\ref{f:ProdCons} shows a producer/consumer symmetric-coroutine performing bi-directional communication.
928Since 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@.
929The @start@ routine communicates both the number of elements to be produced and the consumer into the producer's coroutine structure.
930Then the @resume@ to @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
931@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.
932
933The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
934For the first resume, @cons@'s stack is initialized, creating local variables retained between subsequent activations of the coroutine.
935The consumer iterates until the @done@ flag is set, prints, 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).
936The call from the consumer to the @payment@ introduces the cycle between producer and consumer.
937When @payment@ is called, the consumer copies values into the producer's communication variable and a resume is executed.
938The context switch restarts the producer at the point where it was last context switched, so it continues in @delivery@ after the resume.
939
940@delivery@ returns the status value in @prod@'s coroutine main, where the status is printed.
941The loop then repeats calling @delivery@, where each call resumes the consumer coroutine.
942The context switch to the consumer continues in @payment@.
943The consumer increments and returns the receipt to the call in @cons@'s coroutine main.
944The loop then repeats calling @payment@, where each call resumes the producer coroutine.
945
946After iterating $N$ times, the producer calls @stop@.
947The @done@ flag is set to stop the consumer's execution and a resume is executed.
948The context switch restarts @cons@ in @payment@ and it returns with the last receipt.
949The 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@.
950@stop@ returns and @prod@'s coroutine main terminates.
951The program main restarts after the resume in @start@.
952@start@ returns and the program main terminates.
953
954
955\subsection{Coroutine Implementation}
956
957A 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.
958There are several solutions to this problem and the chosen option forced the \CFA coroutine design.
959
960Object-oriented inheritance provides extra fields and code in a restricted context, but it requires programmers to explicitly perform the inheritance:
961\begin{cfa}
962struct mycoroutine $\textbf{\textsf{inherits}}$ baseCoroutine { ... }
963\end{cfa}
964and the programming language (and possibly its tool set, \eg debugger) may need to understand @baseCoroutine@ because of the stack.
965Furthermore, the execution of constructs/destructors is in the wrong order for certain operations, \eg for threads;
966\eg, 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.
967
968An alternatively is composition:
969\begin{cfa}
970struct mycoroutine {
971        ... // declarations
972        baseCoroutine dummy; // composition, last declaration
973}
974\end{cfa}
975which also requires an explicit declaration that must be the last one to ensure correct initialization order.
976However, there is nothing preventing wrong placement or multiple declarations.
977
978For coroutines as for threads, many implementations are based on routine pointers or routine objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
979For example, Boost implements coroutines in terms of four functor object-types:
980\begin{cfa}
981asymmetric_coroutine<>::pull_type
982asymmetric_coroutine<>::push_type
983symmetric_coroutine<>::call_type
984symmetric_coroutine<>::yield_type
985\end{cfa}
986Similarly, the canonical threading paradigm is often based on routine pointers, \eg @pthread@~\cite{pthreads}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}.
987However, the generic thread-handle (identifier) is limited (few operations), unless it is wrapped in a custom type.
988\begin{cfa}
989void mycor( coroutine_t cid, void * arg ) {
990        int * value = (int *)arg;                               $\C{// type unsafe, pointer-size only}$
991        // Coroutine body
992}
993int main() {
994        int input = 0, output;
995        coroutine_t cid = coroutine_create( &mycor, (void *)&input ); $\C{// type unsafe, pointer-size only}$
996        coroutine_resume( cid, (void *)input, (void **)&output ); $\C{// type unsafe, pointer-size only}$
997}
998\end{cfa}
999Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda-based coroutines adds very little.
1000
1001Note, the type @coroutine_t@ must be an abstract handle to the coroutine, because the coroutine descriptor and its stack are non-copyable.
1002Copying the coroutine descriptor results in copies being out of date with the current state of the stack.
1003Correspondingly, copying the stack results is copies being out of date with coroutine descriptor, and pointers in the stack being out of date to data on the stack.
1004(There is no mechanism in C to find all stack-specific pointers and update them as part of a copy.)
1005
1006The selected approach is to use language support by introducing a new kind of aggregate (structure):
1007\begin{cfa}
1008coroutine Fibonacci {
1009        int fn; // communication variables
1010};
1011\end{cfa}
1012The @coroutine@ keyword means the compiler (and tool set) can find and inject code where needed.
1013The downside of this approach is that it makes coroutine a special case in the language.
1014Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language.
1015Furthermore, implementing coroutines without language supports also displays the power of a programming language.
1016While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can still be constructed without using the language support.
1017The reserved keyword eases use for the common cases.
1018
1019Part 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:
1020\begin{cfa}
1021trait is_coroutine( `dtype` T ) {
1022        void main( T & );
1023        coroutine_desc * get_coroutine( T & );
1024};
1025forall( `dtype` T | is_coroutine(T) ) void suspend( T & );
1026forall( `dtype` T | is_coroutine(T) ) void resume( T & );
1027\end{cfa}
1028The @dtype@ property of the trait ensures the coroutine descriptor is non-copyable, so all coroutines must be passed by reference (pointer).
1029The 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.
1030The @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.
1031The 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.
1032The advantage of this approach is that users can easily create different types of coroutines, for example, changing the memory layout of a coroutine is trivial when implementing the @get_coroutine@ routine, and possibly redefining @suspend@ and @resume@.
1033The \CFA keyword @coroutine@ implicitly implements the getter and forward declarations required for implementing the coroutine main:
1034\begin{cquote}
1035\begin{tabular}{@{}ccc@{}}
1036\begin{cfa}
1037coroutine MyCor {
1038        int value;
1039
1040};
1041\end{cfa}
1042&
1043{\Large $\Rightarrow$}
1044&
1045\begin{tabular}{@{}ccc@{}}
1046\begin{cfa}
1047struct MyCor {
1048        int value;
1049        coroutine_desc cor;
1050};
1051\end{cfa}
1052&
1053\begin{cfa}
1054static inline coroutine_desc *
1055get_coroutine( MyCor & this ) {
1056        return &this.cor;
1057}
1058\end{cfa}
1059&
1060\begin{cfa}
1061void main( MyCor * this );
1062
1063
1064
1065\end{cfa}
1066\end{tabular}
1067\end{tabular}
1068\end{cquote}
1069The 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.
1070
1071
1072\subsection{Thread Interface}
1073\label{threads}
1074
1075Both user and kernel threads are supported, where user threads provide concurrency and kernel threads provide parallelism.
1076Like 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:
1077\begin{cquote}
1078\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
1079\begin{cfa}
1080thread myThread {
1081        // communication variables
1082};
1083
1084
1085\end{cfa}
1086&
1087\begin{cfa}
1088trait is_thread( `dtype` T ) {
1089      void main( T & );
1090      thread_desc * get_thread( T & );
1091      void ^?{}( T & `mutex` );
1092};
1093\end{cfa}
1094\end{tabular}
1095\end{cquote}
1096(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitors}.)
1097Like a coroutine, the statically-typed @main@ routine is the starting point (first stack frame) of a user thread.
1098The difference is that a coroutine borrows a thread from its caller, so the first thread resuming a coroutine creates an instance of @main@;
1099whereas, 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{
1100The \lstinline@main@ routine is already a special routine in C (where the program begins), so it is a natural extension of the semantics to use overloading to declare mains for different coroutines/threads (the normal main being the main of the initial thread).}
1101No 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.
1102
1103\begin{comment} % put in appendix with coroutine version ???
1104As such the @main@ routine of a thread can be defined as
1105\begin{cfa}
1106thread foo {};
1107
1108void main(foo & this) {
1109        sout | "Hello World!" | endl;
1110}
1111\end{cfa}
1112
1113In 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.
1114With 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.
1115\begin{cfa}
1116typedef void (*voidRtn)(int);
1117
1118thread RtnRunner {
1119        voidRtn func;
1120        int arg;
1121};
1122
1123void ?{}(RtnRunner & this, voidRtn inRtn, int arg) {
1124        this.func = inRtn;
1125        this.arg  = arg;
1126}
1127
1128void main(RtnRunner & this) {
1129        // thread starts here and runs the routine
1130        this.func( this.arg );
1131}
1132
1133void hello(/*unused*/ int) {
1134        sout | "Hello World!" | endl;
1135}
1136
1137int main() {
1138        RtnRunner f = {hello, 42};
1139        return 0?
1140}
1141\end{cfa}
1142A 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}.
1143\end{comment}
1144
1145For user threads to be useful, it must be possible to start and stop the underlying thread, and wait for it to complete execution.
1146While using an API such as @fork@ and @join@ is relatively common, such an interface is awkward and unnecessary.
1147A simple approach is to use allocation/deallocation principles, and have threads implicitly @fork@ after construction and @join@ before destruction.
1148\begin{cfa}
1149thread World {};
1150void main( World & this ) {
1151        sout | "World!" | endl;
1152}
1153int main() {
1154        World w`[10]`;                                                  $\C{// implicit forks after creation}$
1155        sout | "Hello " | endl;                                 $\C{// "Hello " and 10 "World!" printed concurrently}$
1156}                                                                                       $\C{// implicit joins before destruction}$
1157\end{cfa}
1158This semantics ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
1159This 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.
1160\begin{cfa}
1161int main() {
1162        MyThread * heapLived;
1163        {
1164                MyThread blockLived;                            $\C{// fork block-based thread}$
1165                heapLived = `new`( MyThread );          $\C{// fork heap-based thread}$
1166                ...
1167        }                                                                               $\C{// join block-based thread}$
1168        ...
1169        `delete`( heapLived );                                  $\C{// join heap-based thread}$
1170}
1171\end{cfa}
1172The heap-based approach allows arbitrary thread-creation topologies, with respect to fork/join-style concurrency.
1173
1174Figure~\ref{s:ConcurrentMatrixSummation} shows concurrently adding the rows of a matrix and then totalling the subtotals sequential, after all the row threads have terminated.
1175The program uses heap-based threads because each thread needs different constructor values.
1176(Python provides a simple iteration mechanism to initialize array elements to different values allowing stack allocation.)
1177The allocation/deallocation pattern appears unusual because allocated objects are immediately deleted without any intervening code.
1178However, for threads, the deletion provides implicit synchronization, which is the intervening code.
1179While 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.
1180
1181\begin{figure}
1182\begin{cfa}
1183thread Adder {
1184    int * row, cols, & subtotal;                        $\C{// communication}$
1185};
1186void ?{}( Adder & adder, int row[], int cols, int & subtotal ) {
1187    adder.[ row, cols, &subtotal ] = [ row, cols, &subtotal ];
1188}
1189void main( Adder & adder ) with( adder ) {
1190    subtotal = 0;
1191    for ( int c = 0; c < cols; c += 1 ) {
1192                subtotal += row[c];
1193    }
1194}
1195int main() {
1196    const int rows = 10, cols = 1000;
1197    int matrix[rows][cols], subtotals[rows], total = 0;
1198    // read matrix
1199    Adder * adders[rows];
1200    for ( int r = 0; r < rows; r += 1 ) {       $\C{// start threads to sum rows}$
1201                adders[r] = new( matrix[r], cols, &subtotals[r] );
1202    }
1203    for ( int r = 0; r < rows; r += 1 ) {       $\C{// wait for threads to finish}$
1204                delete( adders[r] );                            $\C{// termination join}$
1205                total += subtotals[r];                          $\C{// total subtotal}$
1206    }
1207    sout | total | endl;
1208}
1209\end{cfa}
1210\caption{Concurrent Matrix Summation}
1211\label{s:ConcurrentMatrixSummation}
1212\end{figure}
1213
1214
1215\section{Mutual Exclusion / Synchronization}
1216
1217Uncontrolled non-deterministic execution is meaningless.
1218To 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}.
1219Since 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).
1220In 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}).
1221However, in call/return-based languages, these approaches force a clear distinction (\ie introduce a new programming paradigm) between regular and concurrent computation (\ie routine call versus message passing).
1222Hence, a programmer must learn and manipulate two sets of design patterns.
1223While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
1224In contrast, approaches based on statefull models more closely resemble the standard call/return programming-model, resulting in a single programming paradigm.
1225
1226At 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}.
1227However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}.
1228A newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
1229While 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.
1230
1231One of the most natural, elegant, and efficient mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor}.
1232First 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}.
1233In 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.
1234For these reasons, \CFA selected monitors as the core high-level concurrency-construct, upon which higher-level approaches can be easily constructed.
1235
1236
1237\subsection{Mutual Exclusion}
1238
1239A group of instructions manipulating a specific instance of shared data that must be performed atomically is called an (individual) \newterm{critical-section}~\cite{Dijkstra65}.
1240The 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.
1241The 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.
1242\newterm{Mutual exclusion} enforces that the correct kind and number of threads are using a critical section.
1243
1244However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
1245Methods 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.
1246Ease 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.
1247For 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.
1248However, a significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock.
1249Easing composability is another feature higher-level mutual-exclusion mechanisms can offer.
1250
1251
1252\subsection{Synchronization}
1253
1254Synchronization enforces relative ordering of execution, and synchronization tools provide numerous mechanisms to establish these timing relationships.
1255Low-level synchronization primitives offer good performance and flexibility at the cost of ease of use;
1256higher-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.
1257Often 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.
1258If a writer thread is scheduled for next access, but another reader thread acquires the critical section first, that reader has \newterm{barged}.
1259Barging 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).
1260Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
1261This challenge is often split into two different approaches: barging avoidance and barging prevention.
1262Algorithms that allow a barger, but divert it until later using current synchronization state (flags), are avoiding the barger;
1263algorithms that preclude a barger from entering during synchronization in the critical section prevent barging completely.
1264Techniques like baton-pass locks~\cite{Andrews89} between threads instead of unconditionally releasing locks is an example of barging prevention.
1265
1266
1267\section{Monitors}
1268\label{s:Monitors}
1269
1270A \textbf{monitor} is a set of routines that ensure mutual exclusion when accessing shared state.
1271More 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).
1272The strong association with the call/return paradigm eases programmability, readability and maintainability, at a slight cost in flexibility and efficiency.
1273
1274Note, 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.
1275Copying 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.
1276Copying 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.
1277As for coroutines/tasks, a non-copyable (@dtype@) trait is used to capture this requirement, so all locks/monitors must be passed by reference (pointer).
1278\begin{cfa}
1279trait is_monitor( `dtype` T ) {
1280        monitor_desc * get_monitor( T & );
1281        void ^?{}( T & mutex );
1282};
1283\end{cfa}
1284
1285
1286\subsection{Mutex Acquisition}
1287\label{s:MutexAcquisition}
1288
1289While correctness implicitly implies a monitor's mutual exclusion is acquired and released, there are implementation options about when and where the locking/unlocking occurs.
1290(Much of this discussion also applies to basic locks.)
1291For example, a monitor may need to be passed through multiple helper routines before it becomes necessary to acquire the monitor mutual-exclusion.
1292\begin{cfa}[morekeywords=nomutex]
1293monitor Aint { int cnt; };                                      $\C{// atomic integer counter}$
1294void ?{}( Aint & `nomutex` this ) with( this ) { cnt = 0; } $\C{// constructor}$
1295int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions}$
1296void ?{}( int & this, Aint & `mutex`$\(_{opt}\)$ v ) { this = v.cnt; }
1297int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; }
1298int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$
1299\end{cfa}
1300The @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.
1301(While a constructor may publish its address into a global variable, doing so generates a race-condition.)
1302The conversion operators for initializing and assigning with a normal integer only need @mutex@, if reading/writing the implementation type is not atomic.
1303Finally, 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.
1304
1305The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics, which is similar to the \CC template @std::atomic@.
1306\begin{cfa}
1307Aint x, y, z;
1308++x; ++y; ++z;                                                          $\C{// safe increment by multiple threads}$
1309x = 2; y = 2; z = 2;                                            $\C{// conversions}$
1310int i = x, j = y, k = z;
1311i = x; j = y; k = z;
1312\end{cfa}
1313
1314For maximum usability, monitors have \newterm{multi-acquire} semantics allowing a thread to acquire it multiple times without deadlock.
1315For example, atomically printing the contents of a binary tree:
1316\begin{cfa}
1317monitor Tree {
1318        Tree * left, right;
1319        // value
1320};
1321void print( Tree & mutex tree ) {                       $\C{// prefix traversal}$
1322        // write value
1323        print( tree->left );                                    $\C{// multiply acquire monitor lock on each recursion}$
1324        print( tree->right );
1325}
1326\end{cfa}
1327
1328Mandatory monitor qualifiers have the benefit of being self-documented, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameter is redundant.
1329Instead, one of qualifier semantics can be the default, and the other required.
1330For example, assume the safe @mutex@ option for a monitor parameter because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
1331On the other hand, assuming \lstinline[morekeywords=nomutex]@nomutex@ is the \emph{normal} parameter behaviour, stating explicitly ``this parameter is not special''.
1332Providing a default qualifier implies knowing whether a parameter is a monitor.
1333Since \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.
1334For 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@.
1335
1336The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@.
1337Given:
1338\begin{cfa}
1339monitor M { ... }
1340int f1( M & mutex m );
1341int f2( M * mutex m );
1342int f3( M * mutex m[] );
1343int f4( stack( M * ) & mutex m );
1344\end{cfa}
1345the issue is that some of these parameter types are composed of multiple objects.
1346For @f1@, there is only a single parameter object.
1347Adding indirection in @f2@ still identifies a single object.
1348However, the matrix in @f3@ introduces multiple objects.
1349While shown shortly, multiple acquisition is possible;
1350however array lengths are often unknown in C.
1351This issue is exacerbated in @f4@, where the data structure must be safely traversed to acquire all of its elements.
1352
1353To make the issue tractable, \CFA only acquires one monitor per parameter with at most one level of indirection.
1354However, the C type-system has an ambiguity with respects to arrays.
1355Is the argument for @f2@ a single object or an array of objects?
1356If it is an array, only the first element of the array is acquired, which seems unsafe;
1357hence, @mutex@ is disallowed for array parameters.
1358\begin{cfa}
1359int f1( M & mutex m );                                          $\C{// allowed: recommended case}$
1360int f2( M * mutex m );                                          $\C{// disallowed: could be an array}$
1361int f3( M mutex m[$\,$] );                                      $\C{// disallowed: array length unknown}$
1362int f4( M ** mutex m );                                         $\C{// disallowed: could be an array}$
1363int f5( M * mutex m[$\,$] );                            $\C{// disallowed: array length unknown}$
1364\end{cfa}
1365% Note, not all array routines have distinct types: @f2@ and @f3@ have the same type, as do @f4@ and @f5@.
1366% However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
1367
1368For object-oriented monitors, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
1369\CFA has no receiver, and hence, must use an explicit mechanism to specify which object has mutual exclusion acquired.
1370A positive consequence of this design decision is the ability to support multi-monitor routines.
1371\begin{cfa}
1372int f( M & mutex x, M & mutex y );              $\C{// multiple monitor parameter of any type}$
1373M m1, m2;
1374f( m1, m2 );
1375\end{cfa}
1376(While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.)
1377In practice, writing multi-locking routines that do not deadlocks is tricky.
1378Having language support for such a feature is therefore a significant asset for \CFA.
1379
1380The capability to acquire multiple locks before entering a critical section is called \newterm{bulk acquire}.
1381In previous example, \CFA guarantees the order of acquisition is consistent across calls to different routines using the same monitors as arguments.
1382This consistent ordering means acquiring multiple monitors is safe from deadlock.
1383However, users can force the acquiring order.
1384For example, notice the use of @mutex@/\lstinline[morekeywords=nomutex]@nomutex@ and how this affects the acquiring order:
1385\begin{cfa}
1386void foo( M & mutex m1, M & mutex m2 );         $\C{// acquire m1 and m2}$
1387void bar( M & mutex m1, M & /* nomutex */ m2 ) { $\C{// acquire m1}$
1388        ... foo( m1, m2 ); ...                                  $\C{// acquire m2}$
1389}
1390void baz( M & /* nomutex */ m1, M & mutex m2 ) { $\C{// acquire m2}$
1391        ... foo( m1, m2 ); ...                                  $\C{// acquire m1}$
1392}
1393\end{cfa}
1394The multi-acquire semantics allows @bar@ or @baz@ to acquire a monitor lock and reacquire it in @foo@.
1395In the calls to @bar@ and @baz@, the monitors are acquired in opposite order.
1396
1397However, 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 implement rollback semantics~\cite{Dice10}.
1398In \CFA, safety is guaranteed by using bulk acquire of all monitors to shared objects, whereas other monitor systems provide no aid.
1399While \CFA provides only a partial solution, the \CFA partial solution handles many useful cases.
1400\begin{cfa}
1401monitor Bank { ... };
1402void deposit( Bank & `mutex` b, int deposit );
1403void transfer( Bank & `mutex` mybank, Bank & `mutex` yourbank, int me2you) {
1404        deposit( mybank, `-`me2you );                   $\C{// debit}$
1405        deposit( yourbank, me2you );                    $\C{// credit}$
1406}
1407\end{cfa}
1408This example shows a trivial solution to the bank-account transfer problem~\cite{BankTransfer}.
1409Without multi- and bulk acquire, the solution to this problem requires careful engineering.
1410
1411
1412\subsection{\protect\lstinline|mutex| statement} \label{mutex-stmt}
1413
1414The monitor call-semantics associate all locking semantics to routines.
1415Like Java, \CFA offers an alternative @mutex@ statement to reduce refactoring and naming.
1416\begin{cquote}
1417\begin{tabular}{@{}c|@{\hspace{\parindentlnth}}c@{}}
1418routine call & @mutex@ statement \\
1419\begin{cfa}
1420monitor M {};
1421void foo( M & mutex m1, M & mutex m2 ) {
1422        // critical section
1423}
1424void bar( M & m1, M & m2 ) {
1425        foo( m1, m2 );
1426}
1427\end{cfa}
1428&
1429\begin{cfa}
1430
1431void bar( M & m1, M & m2 ) {
1432        mutex( m1, m2 ) {       // remove refactoring and naming
1433                // critical section
1434        }
1435}
1436
1437\end{cfa}
1438\end{tabular}
1439\end{cquote}
1440
1441
1442\section{Internal Scheduling}
1443\label{s:InternalScheduling}
1444
1445While monitor mutual-exclusion provides safe access to shared data, the monitor data may indicate that a thread accessing it cannot proceed.
1446For example, Figure~\ref{f:GenericBoundedBuffer} shows a bounded buffer that may be full/empty so produce/consumer threads must block.
1447Leaving the monitor and trying again (busy waiting) is impractical for high-level programming.
1448Monitors 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.
1449Synchronization 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.
1450\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.
1451
1452Figure~\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@.
1453The @wait@ routine atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the routine's parameter list.
1454The appropriate condition lock is signalled to unblock an opposite kind of thread after an element is inserted/removed from the buffer.
1455Signalling is unconditional, because signalling an empty condition lock does nothing.
1456Signalling semantics cannot have the signaller and signalled thread in the monitor simultaneously, which means:
1457\begin{enumerate}
1458\item
1459The signalling thread returns immediately, and the signalled thread continues.
1460\item
1461The signalling thread continues and the signalled thread is marked for urgent unblocking at the next scheduling point (exit/wait).
1462\item
1463The signalling thread blocks but is marked for urgrent unblocking at the next scheduling point and the signalled thread continues.
1464\end{enumerate}
1465The first approach is too restrictive, as it precludes solving a reasonable class of problems (\eg dating service).
1466\CFA supports the next two semantics as both are useful.
1467Finally, while it is common to store a @condition@ as a field of the monitor, in \CFA, a @condition@ variable can be created/stored independently.
1468Furthermore, 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.
1469
1470\begin{figure}
1471\centering
1472\newbox\myboxA
1473\begin{lrbox}{\myboxA}
1474\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1475forall( otype T ) { // distribute forall
1476        monitor Buffer {
1477                `condition` full, empty;
1478                int front, back, count;
1479                T elements[10];
1480        };
1481        void ?{}( Buffer(T) & buffer ) with(buffer) {
1482                [front, back, count] = 0;
1483        }
1484
1485        void insert( Buffer(T) & mutex buffer, T elem )
1486                                with(buffer) {
1487                if ( count == 10 ) `wait( empty )`;
1488                // insert elem into buffer
1489                `signal( full )`;
1490        }
1491        T remove( Buffer(T) & mutex buffer ) with(buffer) {
1492                if ( count == 0 ) `wait( full )`;
1493                // remove elem from buffer
1494                `signal( empty )`;
1495                return elem;
1496        }
1497}
1498\end{cfa}
1499\end{lrbox}
1500
1501\newbox\myboxB
1502\begin{lrbox}{\myboxB}
1503\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1504forall( otype T ) { // distribute forall
1505        monitor Buffer {
1506
1507                int front, back, count;
1508                T elements[10];
1509        };
1510        void ?{}( Buffer(T) & buffer ) with(buffer) {
1511                [front, back, count] = 0;
1512        }
1513        T remove( Buffer(T) & mutex buffer ); // forward
1514        void insert( Buffer(T) & mutex buffer, T elem )
1515                                with(buffer) {
1516                if ( count == 10 ) `waitfor( remove, buffer )`;
1517                // insert elem into buffer
1518
1519        }
1520        T remove( Buffer(T) & mutex buffer ) with(buffer) {
1521                if ( count == 0 ) `waitfor( insert, buffer )`;
1522                // remove elem from buffer
1523
1524                return elem;
1525        }
1526}
1527\end{cfa}
1528\end{lrbox}
1529
1530\subfloat[Internal Scheduling]{\label{f:BBInt}\usebox\myboxA}
1531%\qquad
1532\subfloat[External Scheduling]{\label{f:BBExt}\usebox\myboxB}
1533\caption{Generic Bounded-Buffer}
1534\label{f:GenericBoundedBuffer}
1535\end{figure}
1536
1537Figure~\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.
1538External 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.
1539If 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.
1540Threads 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.
1541
1542Both internal and external scheduling extend to multiple monitors in a natural way.
1543\begin{cquote}
1544\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
1545\begin{cfa}
1546monitor M { `condition e`; ... };
1547void foo( M & mutex m1, M & mutex m2 ) {
1548        ... wait( `e` ); ...   // wait( e, m1, m2 )
1549        ... wait( `e, m1` ); ...
1550        ... wait( `e, m2` ); ...
1551}
1552\end{cfa}
1553&
1554\begin{cfa}
1555void rtn$\(_1\)$( M & mutex m1, M & mutex m2 );
1556void rtn$\(_2\)$( M & mutex m1 );
1557void bar( M & mutex m1, M & mutex m2 ) {
1558        ... waitfor( `rtn` ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\), m1, m2 )}$
1559        ... waitfor( `rtn, m1` ); ... // $\LstCommentStyle{waitfor( rtn\(_2\), m1 )}$
1560}
1561\end{cfa}
1562\end{tabular}
1563\end{cquote}
1564For @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 )@.
1565To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
1566Wait statically verifies the released monitors are the acquired mutex-parameters so unconditional release is safe.
1567Finally, a signaller,
1568\begin{cfa}
1569void baz( M & mutex m1, M & mutex m2 ) {
1570        ... signal( e ); ...
1571}
1572\end{cfa}
1573must have acquired monitor locks that are greater than or equal to the number of locks for the waiting thread signalled from the front of the condition queue.
1574In general, the signaller does not know the order of waiting threads, so in general, it must acquire the maximum number of mutex locks for the worst-case waiting thread.
1575
1576Similarly, 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 )@.
1577To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn, m1 )@.
1578Waitfor statically verifies the released monitors are the same as the acquired mutex-parameters of the given routine or routine pointer.
1579To statically verify the released monitors match with the accepted routine's mutex parameters, the routine (pointer) prototype must be accessible.
1580
1581Given the ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock.
1582\begin{cfa}
1583void foo( M & mutex m1, M & mutex m2 ) {
1584        ... wait( `e, m1` ); ...                                $\C{// release m1, keeping m2 acquired )}$
1585void baz( M & mutex m1, M & mutex m2 ) {        $\C{// must acquire m1 and m2 )}$
1586        ... signal( `e` ); ...
1587\end{cfa}
1588The @wait@ only releases @m1@ so the signalling thread cannot acquire both @m1@ and @m2@ to  enter @baz@ to get to the @signal@.
1589While deadlock issues can occur with multiple/nesting acquisition, this issue results from the fact that locks, and by extension monitors, are not perfectly composable.
1590
1591Finally, an important aspect of monitor implementation is barging, \ie can calling threads barge ahead of signalled threads?
1592If 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).
1593\begin{quote}
1594However, 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.
1595It 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}
1596\end{quote}
1597\CFA scheduling \emph{precludes} barging, which simplifies synchronization among threads in the monitor and increases correctness.
1598For example, there are no loops in either bounded buffer solution in Figure~\ref{f:GenericBoundedBuffer}.
1599Supporting 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.
1600
1601
1602\subsection{Barging Prevention}
1603
1604Figure~\ref{f:BargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signalling semantics.
1605The complexity begins at the end of the inner @mutex@ statement, where the semantics of internal scheduling need to be extended for multiple monitors.
1606The problem is that bulk acquire is used in the inner @mutex@ statement where one of the monitors is already acquired.
1607When 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.
1608However, both the signalling and waiting thread W1 still need monitor @m1@.
1609
1610\begin{figure}
1611\newbox\myboxA
1612\begin{lrbox}{\myboxA}
1613\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1614monitor M m1, m2;
1615condition c;
1616mutex( m1 ) { // $\LstCommentStyle{\color{red}outer}$
1617        ...
1618        mutex( m1, m2 ) { // $\LstCommentStyle{\color{red}inner}$
1619                ... `signal( c )`; ...
1620                // m1, m2 acquired
1621        } // $\LstCommentStyle{\color{red}release m2}$
1622        // m1 acquired
1623} // release m1
1624\end{cfa}
1625\end{lrbox}
1626
1627\newbox\myboxB
1628\begin{lrbox}{\myboxB}
1629\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1630
1631
1632mutex( m1 ) {
1633        ...
1634        mutex( m1, m2 ) {
1635                ... `wait( c )`; // block and release m1, m2
1636                // m1, m2 acquired
1637        } // $\LstCommentStyle{\color{red}release m2}$
1638        // m1 acquired
1639} // release m1
1640\end{cfa}
1641\end{lrbox}
1642
1643\newbox\myboxC
1644\begin{lrbox}{\myboxC}
1645\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1646
1647
1648mutex( m2 ) {
1649        ... `wait( c )`; ...
1650        // m2 acquired
1651} // $\LstCommentStyle{\color{red}release m2}$
1652
1653
1654
1655
1656\end{cfa}
1657\end{lrbox}
1658
1659\begin{cquote}
1660\subfloat[Signalling Thread]{\label{f:SignallingThread}\usebox\myboxA}
1661\hspace{2\parindentlnth}
1662\subfloat[Waiting Thread (W1)]{\label{f:WaitingThread}\usebox\myboxB}
1663\hspace{2\parindentlnth}
1664\subfloat[Waiting Thread (W2)]{\label{f:OtherWaitingThread}\usebox\myboxC}
1665\end{cquote}
1666\caption{Barging Prevention}
1667\label{f:BargingPrevention}
1668\end{figure}
1669
1670One 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.
1671However, Figure~\ref{f:OtherWaitingThread} shows this solution is complex depending on other waiters, resulting is choices when the signaller finishes the inner mutex-statement.
1672The 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@.
1673In the latter case, waiter W2 must eventually pass @m2@ to waiter W1, which is complex because W2 may have waited before W1 so it is unaware of W1.
1674Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
1675
1676While a number of approaches were examined~\cite[\S~4.3]{Delisle18}, the solution chosen for \CFA is a novel techique called \newterm{partial signalling}.
1677Signalled threads are moved to an urgent queue and the waiter at the front defines the set of monitors necessary for it to unblock.
1678Partial signalling transfers ownership of monitors to the front waiter.
1679When the signaller thread exits or waits in the monitor the front waiter is unblocked if all its monitors are released.
1680This 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.
1681
1682\begin{comment}
1683Figure~\ref{f:dependency} shows a slightly different example where a third thread is waiting on monitor @A@, using a different condition variable.
1684Because the third thread is signalled when secretly holding @B@, the goal  becomes unreachable.
1685Depending on the order of signals (listing \ref{f:dependency} line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen:
1686
1687\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.
1688\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.
1689\\
1690
1691Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order.
1692However, 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}.
1693
1694In 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.
1695
1696
1697\subsubsection{Dependency graphs}
1698
1699\begin{figure}
1700\begin{multicols}{3}
1701Thread $\alpha$
1702\begin{cfa}[numbers=left, firstnumber=1]
1703acquire A
1704        acquire A & B
1705                wait A & B
1706        release A & B
1707release A
1708\end{cfa}
1709\columnbreak
1710Thread $\gamma$
1711\begin{cfa}[numbers=left, firstnumber=6, escapechar=|]
1712acquire A
1713        acquire A & B
1714                |\label{line:signal-ab}|signal A & B
1715        |\label{line:release-ab}|release A & B
1716        |\label{line:signal-a}|signal A
1717|\label{line:release-a}|release A
1718\end{cfa}
1719\columnbreak
1720Thread $\beta$
1721\begin{cfa}[numbers=left, firstnumber=12, escapechar=|]
1722acquire A
1723        wait A
1724|\label{line:release-aa}|release A
1725\end{cfa}
1726\end{multicols}
1727\begin{cfa}[caption={Pseudo-code for the three thread example.},label={f:dependency}]
1728\end{cfa}
1729\begin{center}
1730\input{dependency}
1731\end{center}
1732\caption{Dependency graph of the statements in listing \ref{f:dependency}}
1733\label{fig:dependency}
1734\end{figure}
1735
1736In listing \ref{f:int-bulk-cfa}, there is a solution that satisfies both barging prevention and mutual exclusion.
1737If 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).
1738Dynamically finding the correct order is therefore the second possible solution.
1739The problem is effectively resolving a dependency graph of ownership requirements.
1740Here even the simplest of code snippets requires two transfers and has a super-linear complexity.
1741This 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.
1742Furthermore, 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.
1743\begin{figure}
1744\begin{multicols}{2}
1745\begin{cfa}
1746acquire A
1747        acquire B
1748                acquire C
1749                        wait A & B & C
1750                release C
1751        release B
1752release A
1753\end{cfa}
1754
1755\columnbreak
1756
1757\begin{cfa}
1758acquire A
1759        acquire B
1760                acquire C
1761                        signal A & B & C
1762                release C
1763        release B
1764release A
1765\end{cfa}
1766\end{multicols}
1767\begin{cfa}[caption={Extension to three monitors of listing \ref{f:int-bulk-cfa}},label={f:explosion}]
1768\end{cfa}
1769\end{figure}
1770
1771Given 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$).
1772The 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.
1773Resolving dependency graphs being a complex and expensive endeavour, this solution is not the preferred one.
1774
1775\subsubsection{Partial Signalling} \label{partial-sig}
1776\end{comment}
1777
1778
1779\subsection{Signalling: Now or Later}
1780
1781\begin{figure}
1782\centering
1783\newbox\myboxA
1784\begin{lrbox}{\myboxA}
1785\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1786enum { CCodes = 20 };
1787monitor DS {
1788        int GirlPhNo, BoyPhNo;
1789        condition Girls[CCodes], Boys[CCodes];
1790        condition exchange;
1791};
1792int girl( DS & mutex ds, int phNo, int ccode ) {
1793        if ( is_empty( Boys[ccode] ) ) {
1794                wait( Girls[ccode] );
1795                GirlPhNo = phNo;
1796                exchange.signal();
1797        } else {
1798                GirlPhNo = phNo;
1799                signal( Boys[ccode] );
1800                exchange.wait();
1801        } // if
1802        return BoyPhNo;
1803}
1804int boy( DS & mutex ds, int phNo, int ccode ) {
1805        // as above with boy/girl interchanged
1806}
1807\end{cfa}
1808\end{lrbox}
1809
1810\newbox\myboxB
1811\begin{lrbox}{\myboxB}
1812\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1813
1814monitor DS {
1815        int GirlPhNo, BoyPhNo;
1816        condition Girls[CCodes], Boys[CCodes];
1817
1818};
1819int girl( DS & mutex ds, int phNo, int ccode ) {
1820        if ( is_empty( Boys[ccode] ) ) { // no compatible
1821                wait( Girls[ccode] ); // wait for boy
1822                GirlPhNo = phNo; // make phone number available
1823
1824        } else {
1825                GirlPhNo = phNo; // make phone number available
1826                signal_block( Boys[ccode] ); // restart boy
1827
1828        } // if
1829        return BoyPhNo;
1830}
1831int boy( DS & mutex ds, int phNo, int ccode ) {
1832        // as above with boy/girl interchanged
1833}
1834\end{cfa}
1835\end{lrbox}
1836
1837\subfloat[\lstinline@signal@]{\label{f:DatingSignal}\usebox\myboxA}
1838\qquad
1839\subfloat[\lstinline@signal_block@]{\label{f:DatingSignalBlock}\usebox\myboxB}
1840\caption{Dating service. }
1841\label{f:Dating service}
1842\end{figure}
1843
1844An important note is that, until now, signalling a monitor was a delayed operation.
1845The ownership of the monitor is transferred only when the monitor would have otherwise been released, not at the point of the @signal@ statement.
1846However, in some cases, it may be more convenient for users to immediately transfer ownership to the thread that is waiting for cooperation, which is achieved using the @signal_block@ routine.
1847
1848The example in table \ref{tbl:datingservice} highlights the difference in behaviour.
1849As mentioned, @signal@ only transfers ownership once the current critical section exits; this behaviour requires additional synchronization when a two-way handshake is needed.
1850To avoid this explicit synchronization, the @condition@ type offers the @signal_block@ routine, which handles the two-way handshake as shown in the example.
1851This feature removes the need for a second condition variables and simplifies programming.
1852Like every other monitor semantic, @signal_block@ uses barging prevention, which means mutual-exclusion is baton-passed both on the front end and the back end of the call to @signal_block@, meaning no other thread can acquire the monitor either before or after the call.
1853
1854% ======================================================================
1855% ======================================================================
1856\section{External scheduling} \label{extsched}
1857% ======================================================================
1858% ======================================================================
1859An alternative to internal scheduling is external scheduling (see Table~\ref{tbl:sched}).
1860
1861\begin{comment}
1862\begin{table}
1863\begin{tabular}{|c|c|c|}
1864Internal Scheduling & External Scheduling & Go\\
1865\hline
1866\begin{uC++}[tabsize=3]
1867_Monitor Semaphore {
1868        condition c;
1869        bool inUse;
1870public:
1871        void P() {
1872                if(inUse)
1873                        wait(c);
1874                inUse = true;
1875        }
1876        void V() {
1877                inUse = false;
1878                signal(c);
1879        }
1880}
1881\end{uC++}&\begin{uC++}[tabsize=3]
1882_Monitor Semaphore {
1883
1884        bool inUse;
1885public:
1886        void P() {
1887                if(inUse)
1888                        _Accept(V);
1889                inUse = true;
1890        }
1891        void V() {
1892                inUse = false;
1893
1894        }
1895}
1896\end{uC++}&\begin{Go}[tabsize=3]
1897type MySem struct {
1898        inUse bool
1899        c     chan bool
1900}
1901
1902// acquire
1903func (s MySem) P() {
1904        if s.inUse {
1905                select {
1906                case <-s.c:
1907                }
1908        }
1909        s.inUse = true
1910}
1911
1912// release
1913func (s MySem) V() {
1914        s.inUse = false
1915
1916        // This actually deadlocks
1917        // when single thread
1918        s.c <- false
1919}
1920\end{Go}
1921\end{tabular}
1922\caption{Different forms of scheduling.}
1923\label{tbl:sched}
1924\end{table}
1925\end{comment}
1926
1927This method is more constrained and explicit, which helps users reduce the non-deterministic nature of concurrency.
1928Indeed, as the following examples demonstrate, external scheduling allows users to wait for events from other threads without the concern of unrelated events occurring.
1929External scheduling can generally be done either in terms of control flow (\eg Ada with @accept@, \uC with @_Accept@) or in terms of data (\eg Go with channels).
1930Of course, both of these paradigms have their own strengths and weaknesses, but for this project, control-flow semantics was chosen to stay consistent with the rest of the languages semantics.
1931Two challenges specific to \CFA arise when trying to add external scheduling with loose object definitions and multiple-monitor routines.
1932The previous example shows a simple use @_Accept@ versus @wait@/@signal@ and its advantages.
1933Note that while other languages often use @accept@/@select@ as the core external scheduling keyword, \CFA uses @waitfor@ to prevent name collisions with existing socket \textbf{api}s.
1934
1935For 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.
1936On the other hand, external scheduling guarantees that while routine @P@ is waiting, no other routine than @V@ can acquire the monitor.
1937
1938% ======================================================================
1939% ======================================================================
1940\subsection{Loose Object Definitions}
1941% ======================================================================
1942% ======================================================================
1943In \uC, a monitor class declaration includes an exhaustive list of monitor operations.
1944Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user:
1945
1946\begin{cfa}
1947monitor A {};
1948
1949void f(A & mutex a);
1950void g(A & mutex a) {
1951        waitfor(f); // Obvious which f() to wait for
1952}
1953
1954void f(A & mutex a, int); // New different F added in scope
1955void h(A & mutex a) {
1956        waitfor(f); // Less obvious which f() to wait for
1957}
1958\end{cfa}
1959
1960Furthermore, external scheduling is an example where implementation constraints become visible from the interface.
1961Here is the cfa-code for the entering phase of a monitor:
1962\begin{center}
1963\begin{tabular}{l}
1964\begin{cfa}
1965        if monitor is free
1966                enter
1967        elif already own the monitor
1968                continue
1969        elif monitor accepts me
1970                enter
1971        else
1972                block
1973\end{cfa}
1974\end{tabular}
1975\end{center}
1976For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions.
1977However, a fast check for @monitor accepts me@ is much harder to implement depending on the constraints put on the monitors.
1978Indeed, monitors are often expressed as an entry queue and some acceptor queue as in Figure~\ref{fig:ClassicalMonitor}.
1979
1980\begin{figure}
1981\centering
1982\subfloat[Classical Monitor] {
1983\label{fig:ClassicalMonitor}
1984{\resizebox{0.45\textwidth}{!}{\input{monitor}}}
1985}% subfloat
1986\qquad
1987\subfloat[bulk acquire Monitor] {
1988\label{fig:BulkMonitor}
1989{\resizebox{0.45\textwidth}{!}{\input{ext_monitor}}}
1990}% subfloat
1991\caption{External Scheduling Monitor}
1992\end{figure}
1993
1994There are other alternatives to these pictures, but in the case of the left picture, implementing a fast accept check is relatively easy.
1995Restricted to a fixed number of mutex members, N, the accept check reduces to updating a bitmask when the acceptor queue changes, a check that executes in a single instruction even with a fairly large number (\eg 128) of mutex members.
1996This approach requires a unique dense ordering of routines with an upper-bound and that ordering must be consistent across translation units.
1997For OO languages these constraints are common, since objects only offer adding member routines consistently across translation units via inheritance.
1998However, in \CFA users can extend objects with mutex routines that are only visible in certain translation unit.
1999This means that establishing a program-wide dense-ordering among mutex routines can only be done in the program linking phase, and still could have issues when using dynamically shared objects.
2000
2001The alternative is to alter the implementation as in Figure~\ref{fig:BulkMonitor}.
2002Here, the mutex routine called is associated with a thread on the entry queue while a list of acceptable routines is kept separate.
2003Generating a mask dynamically means that the storage for the mask information can vary between calls to @waitfor@, allowing for more flexibility and extensions.
2004Storing an array of accepted routine pointers replaces the single instruction bitmask comparison with dereferencing a pointer followed by a linear search.
2005Furthermore, supporting nested external scheduling (\eg listing \ref{f:nest-ext}) may now require additional searches for the @waitfor@ statement to check if a routine is already queued.
2006
2007\begin{figure}
2008\begin{cfa}[caption={Example of nested external scheduling},label={f:nest-ext}]
2009monitor M {};
2010void foo( M & mutex a ) {}
2011void bar( M & mutex b ) {
2012        // Nested in the waitfor(bar, c) call
2013        waitfor(foo, b);
2014}
2015void baz( M & mutex c ) {
2016        waitfor(bar, c);
2017}
2018
2019\end{cfa}
2020\end{figure}
2021
2022Note 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.
2023These details are omitted from the picture for the sake of simplicity.
2024
2025At this point, a decision must be made between flexibility and performance.
2026Many 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.
2027Here, however, the cost of flexibility cannot be trivially removed.
2028In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be  hard to write.
2029This 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.
2030
2031% ======================================================================
2032% ======================================================================
2033\subsection{Multi-Monitor Scheduling}
2034% ======================================================================
2035% ======================================================================
2036
2037External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax.
2038Even in the simplest possible case, some new semantics needs to be established:
2039\begin{cfa}
2040monitor M {};
2041
2042void f(M & mutex a);
2043
2044void g(M & mutex b, M & mutex c) {
2045        waitfor(f); // two monitors M => unknown which to pass to f(M & mutex)
2046}
2047\end{cfa}
2048The obvious solution is to specify the correct monitor as follows:
2049
2050\begin{cfa}
2051monitor M {};
2052
2053void f(M & mutex a);
2054
2055void g(M & mutex a, M & mutex b) {
2056        // wait for call to f with argument b
2057        waitfor(f, b);
2058}
2059\end{cfa}
2060This syntax is unambiguous.
2061Both locks are acquired and kept by @g@.
2062When routine @f@ is called, the lock for monitor @b@ is temporarily transferred from @g@ to @f@ (while @g@ still holds lock @a@).
2063This behaviour can be extended to the multi-monitor @waitfor@ statement as follows.
2064
2065\begin{cfa}
2066monitor M {};
2067
2068void f(M & mutex a, M & mutex b);
2069
2070void g(M & mutex a, M & mutex b) {
2071        // wait for call to f with arguments a and b
2072        waitfor(f, a, b);
2073}
2074\end{cfa}
2075
2076Note that the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired in the routine. @waitfor@ used in any other context is undefined behaviour.
2077
2078An important behaviour to note is when a set of monitors only match partially:
2079
2080\begin{cfa}
2081mutex struct A {};
2082
2083mutex struct B {};
2084
2085void g(A & mutex a, B & mutex b) {
2086        waitfor(f, a, b);
2087}
2088
2089A a1, a2;
2090B b;
2091
2092void foo() {
2093        g(a1, b); // block on accept
2094}
2095
2096void bar() {
2097        f(a2, b); // fulfill cooperation
2098}
2099\end{cfa}
2100While 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.
2101In both cases, partially matching monitor sets does not wakeup the waiting thread.
2102It 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.
2103
2104% ======================================================================
2105% ======================================================================
2106\subsection{\protect\lstinline|waitfor| Semantics}
2107% ======================================================================
2108% ======================================================================
2109
2110Syntactically, the @waitfor@ statement takes a routine identifier and a set of monitors.
2111While 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.
2112It checks that the set of monitors passed in matches the requirements for a routine call.
2113Figure~\ref{f:waitfor} shows various usages of the waitfor statement and which are acceptable.
2114The choice of the routine type is made ignoring any non-@mutex@ parameter.
2115One limitation of the current implementation is that it does not handle overloading, but overloading is possible.
2116\begin{figure}
2117\begin{cfa}[caption={Various correct and incorrect uses of the waitfor statement},label={f:waitfor}]
2118monitor A{};
2119monitor B{};
2120
2121void f1( A & mutex );
2122void f2( A & mutex, B & mutex );
2123void f3( A & mutex, int );
2124void f4( A & mutex, int );
2125void f4( A & mutex, double );
2126
2127void foo( A & mutex a1, A & mutex a2, B & mutex b1, B & b2 ) {
2128        A * ap = & a1;
2129        void (*fp)( A & mutex ) = f1;
2130
2131        waitfor(f1, a1);     // Correct : 1 monitor case
2132        waitfor(f2, a1, b1); // Correct : 2 monitor case
2133        waitfor(f3, a1);     // Correct : non-mutex arguments are ignored
2134        waitfor(f1, *ap);    // Correct : expression as argument
2135
2136        waitfor(f1, a1, b1); // Incorrect : Too many mutex arguments
2137        waitfor(f2, a1);     // Incorrect : Too few mutex arguments
2138        waitfor(f2, a1, a2); // Incorrect : Mutex arguments don't match
2139        waitfor(f1, 1);      // Incorrect : 1 not a mutex argument
2140        waitfor(f9, a1);     // Incorrect : f9 routine does not exist
2141        waitfor(*fp, a1 );   // Incorrect : fp not an identifier
2142        waitfor(f4, a1);     // Incorrect : f4 ambiguous
2143
2144        waitfor(f2, a1, b2); // Undefined behaviour : b2 not mutex
2145}
2146\end{cfa}
2147\end{figure}
2148
2149Finally, for added flexibility, \CFA supports constructing a complex @waitfor@ statement using the @or@, @timeout@ and @else@.
2150Indeed, 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.
2151To 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.
2152A @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.
2153Any 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.
2154Figure~\ref{f:waitfor2} demonstrates several complex masks and some incorrect ones.
2155
2156\begin{figure}
2157\lstset{language=CFA,deletedelim=**[is][]{`}{`}}
2158\begin{cfa}
2159monitor A{};
2160
2161void f1( A & mutex );
2162void f2( A & mutex );
2163
2164void foo( A & mutex a, bool b, int t ) {
2165        waitfor(f1, a);                                                 $\C{// Correct : blocking case}$
2166
2167        waitfor(f1, a) {                                                $\C{// Correct : block with statement}$
2168                sout | "f1" | endl;
2169        }
2170        waitfor(f1, a) {                                                $\C{// Correct : block waiting for f1 or f2}$
2171                sout | "f1" | endl;
2172        } or waitfor(f2, a) {
2173                sout | "f2" | endl;
2174        }
2175        waitfor(f1, a); or else;                                $\C{// Correct : non-blocking case}$
2176
2177        waitfor(f1, a) {                                                $\C{// Correct : non-blocking case}$
2178                sout | "blocked" | endl;
2179        } or else {
2180                sout | "didn't block" | endl;
2181        }
2182        waitfor(f1, a) {                                                $\C{// Correct : block at most 10 seconds}$
2183                sout | "blocked" | endl;
2184        } or timeout( 10`s) {
2185                sout | "didn't block" | endl;
2186        }
2187        // Correct : block only if b == true if b == false, don't even make the call
2188        when(b) waitfor(f1, a);
2189
2190        // Correct : block only if b == true if b == false, make non-blocking call
2191        waitfor(f1, a); or when(!b) else;
2192
2193        // Correct : block only of t > 1
2194        waitfor(f1, a); or when(t > 1) timeout(t); or else;
2195
2196        // Incorrect : timeout clause is dead code
2197        waitfor(f1, a); or timeout(t); or else;
2198
2199        // Incorrect : order must be waitfor [or waitfor... [or timeout] [or else]]
2200        timeout(t); or waitfor(f1, a); or else;
2201}
2202\end{cfa}
2203\caption{Correct and incorrect uses of the or, else, and timeout clause around a waitfor statement}
2204\label{f:waitfor2}
2205\end{figure}
2206
2207% ======================================================================
2208% ======================================================================
2209\subsection{Waiting For The Destructor}
2210% ======================================================================
2211% ======================================================================
2212An interesting use for the @waitfor@ statement is destructor semantics.
2213Indeed, the @waitfor@ statement can accept any @mutex@ routine, which includes the destructor (see section \ref{data}).
2214However, 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.
2215The simplest approach is to disallow @waitfor@ on a destructor.
2216However, 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.
2217\begin{figure}
2218\begin{cfa}[caption={Example of an executor which executes action in series until the destructor is called.},label={f:dtor-order}]
2219monitor Executer {};
2220struct  Action;
2221
2222void ^?{}   (Executer & mutex this);
2223void execute(Executer & mutex this, const Action & );
2224void run    (Executer & mutex this) {
2225        while(true) {
2226                   waitfor(execute, this);
2227                or waitfor(^?{}   , this) {
2228                        break;
2229                }
2230        }
2231}
2232\end{cfa}
2233\end{figure}
2234For 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.
2235Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction.
2236
2237
2238% ######     #    ######     #    #       #       ####### #       ###  #####  #     #
2239% #     #   # #   #     #   # #   #       #       #       #        #  #     # ##   ##
2240% #     #  #   #  #     #  #   #  #       #       #       #        #  #       # # # #
2241% ######  #     # ######  #     # #       #       #####   #        #   #####  #  #  #
2242% #       ####### #   #   ####### #       #       #       #        #        # #     #
2243% #       #     # #    #  #     # #       #       #       #        #  #     # #     #
2244% #       #     # #     # #     # ####### ####### ####### ####### ###  #####  #     #
2245\section{Parallelism}
2246Historically, computer performance was about processor speeds and instruction counts.
2247However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}.
2248In this decade, it is no longer reasonable to create a high-performance application without caring about parallelism.
2249Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization.
2250The lowest-level approach of parallelism is to use \textbf{kthread} in combination with semantics like @fork@, @join@, \etc.
2251However, since these have significant costs and limitations, \textbf{kthread} are now mostly used as an implementation tool rather than a user oriented one.
2252There are several alternatives to solve these issues that all have strengths and weaknesses.
2253While 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.
2254
2255\section{Paradigms}
2256\subsection{User-Level Threads}
2257A direct improvement on the \textbf{kthread} approach is to use \textbf{uthread}.
2258These threads offer most of the same features that the operating system already provides but can be used on a much larger scale.
2259This 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.
2260The 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.
2261These issues can be somewhat alleviated by a concurrency toolkit with strong guarantees, but the parallelism toolkit offers very little to reduce complexity in itself.
2262
2263Examples of languages that support \textbf{uthread} are Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
2264
2265\subsection{Fibers : User-Level Threads Without Preemption} \label{fibers}
2266A popular variant of \textbf{uthread} is what is often referred to as \textbf{fiber}.
2267However, \textbf{fiber} do not present meaningful semantic differences with \textbf{uthread}.
2268The significant difference between \textbf{uthread} and \textbf{fiber} is the lack of \textbf{preemption} in the latter.
2269Advocates 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.
2270Therefore this proposal largely ignores fibers.
2271
2272An example of a language that uses fibers is Go~\cite{Go}
2273
2274\subsection{Jobs and Thread Pools}
2275An approach on the opposite end of the spectrum is to base parallelism on \textbf{pool}.
2276Indeed, \textbf{pool} offer limited flexibility but at the benefit of a simpler user interface.
2277In \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.
2278This approach means users need not worry about concurrency but significantly limit the interaction that can occur among jobs.
2279Indeed, any \textbf{job} that blocks also block the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably.
2280It can be argued that a solution to this problem is to use more workers than available cores.
2281However, unless the number of jobs and the number of workers are comparable, having a significant number of blocked jobs always results in idles cores.
2282
2283The gold standard of this implementation is Intel's TBB library~\cite{TBB}.
2284
2285\subsection{Paradigm Performance}
2286While 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.
2287Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload.
2288Having 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).
2289However, interactions among jobs can easily exacerbate contention.
2290User-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.
2291Finally, if the units of uninterrupted work are large, enough the paradigm choice is largely amortized by the actual work done.
2292
2293\section{The \protect\CFA\ Kernel : Processors, Clusters and Threads}\label{kernel}
2294A \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}.
2295It 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.
2296A \textbf{cfacluster} also offers a pluggable scheduler that can optimize the workload generated by the \textbf{uthread}.
2297
2298\textbf{cfacluster} have not been fully implemented in the context of this paper.
2299Currently \CFA only supports one \textbf{cfacluster}, the initial one.
2300
2301\subsection{Future Work: Machine Setup}\label{machine}
2302While this was not done in the context of this paper, another important aspect of clusters is affinity.
2303While many common desktop and laptop PCs have homogeneous CPUs, other devices often have more heterogeneous setups.
2304For example, a system using \textbf{numa} configurations may benefit from users being able to tie clusters and/or kernel threads to certain CPU cores.
2305OS 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.
2306
2307\subsection{Paradigms}\label{cfaparadigms}
2308Given these building blocks, it is possible to reproduce all three of the popular paradigms.
2309Indeed, \textbf{uthread} is the default paradigm in \CFA.
2310However, disabling \textbf{preemption} on a cluster means threads effectively become fibers.
2311Since 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.
2312Finally, it is possible to build executors for thread pools from \textbf{uthread} or \textbf{fiber}, which includes specialized jobs like actors~\cite{Actors}.
2313
2314
2315
2316\section{Behind the Scenes}
2317There are several challenges specific to \CFA when implementing concurrency.
2318These challenges are a direct result of bulk acquire and loose object definitions.
2319These two constraints are the root cause of most design decisions in the implementation.
2320Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs.
2321This 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.
2322This extra goal means that memory management is a constant concern in the design of the system.
2323
2324The main memory concern for concurrency is queues.
2325All 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.
2326Since 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.
2327Conveniently, 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.
2328Since 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.
2329The 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.
2330
2331Note 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.
2332
2333% ======================================================================
2334% ======================================================================
2335\section{Mutex Routines}
2336% ======================================================================
2337% ======================================================================
2338
2339The first step towards the monitor implementation is simple @mutex@ routines.
2340In the single monitor case, mutual-exclusion is done using the entry/exit procedure in listing \ref{f:entry1}.
2341The entry/exit procedures do not have to be extended to support multiple monitors.
2342Indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlock~\cite{Havender68}.
2343In \CFA, ordering of monitor acquisition relies on memory ordering.
2344This 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.
2345When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer array and sorted based on pointer values.
2346This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively.
2347\begin{figure}
2348\begin{multicols}{2}
2349Entry
2350\begin{cfa}
2351if monitor is free
2352        enter
2353elif already own the monitor
2354        continue
2355else
2356        block
2357increment recursions
2358\end{cfa}
2359\columnbreak
2360Exit
2361\begin{cfa}
2362decrement recursion
2363if recursion == 0
2364        if entry queue not empty
2365                wake-up thread
2366\end{cfa}
2367\end{multicols}
2368\begin{cfa}[caption={Initial entry and exit routine for monitors},label={f:entry1}]
2369\end{cfa}
2370\end{figure}
2371
2372\subsection{Details: Interaction with polymorphism}
2373Depending 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.
2374However, it is shown that entry-point locking solves most of the issues.
2375
2376First of all, interaction between @otype@ polymorphism (see Section~\ref{s:ParametricPolymorphism}) and monitors is impossible since monitors do not support copying.
2377Therefore, the main question is how to support @dtype@ polymorphism.
2378It 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.
2379For example:
2380\begin{table}
2381\begin{center}
2382\begin{tabular}{|c|c|c|}
2383Mutex & \textbf{callsite-locking} & \textbf{entry-point-locking} \\
2384call & cfa-code & cfa-code \\
2385\hline
2386\begin{cfa}[tabsize=3]
2387void foo(monitor& mutex a){
2388
2389        // Do Work
2390        //...
2391
2392}
2393
2394void main() {
2395        monitor a;
2396
2397        foo(a);
2398
2399}
2400\end{cfa} & \begin{cfa}[tabsize=3]
2401foo(& a) {
2402
2403        // Do Work
2404        //...
2405
2406}
2407
2408main() {
2409        monitor a;
2410        acquire(a);
2411        foo(a);
2412        release(a);
2413}
2414\end{cfa} & \begin{cfa}[tabsize=3]
2415foo(& a) {
2416        acquire(a);
2417        // Do Work
2418        //...
2419        release(a);
2420}
2421
2422main() {
2423        monitor a;
2424
2425        foo(a);
2426
2427}
2428\end{cfa}
2429\end{tabular}
2430\end{center}
2431\caption{Call-site vs entry-point locking for mutex calls}
2432\label{tbl:locking-site}
2433\end{table}
2434
2435Note 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:
2436\begin{cfa}
2437// Incorrect: T may not be monitor
2438forall(dtype T)
2439void foo(T * mutex t);
2440
2441// Correct: this routine only works on monitors (any monitor)
2442forall(dtype T | is_monitor(T))
2443void bar(T * mutex t));
2444\end{cfa}
2445
2446Both entry point and \textbf{callsite-locking} are feasible implementations.
2447The 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.
2448It 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.
2449For example, the monitor call can appear in the middle of an expression.
2450Furthermore, 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.
2451
2452% ======================================================================
2453% ======================================================================
2454\section{Threading} \label{impl:thread}
2455% ======================================================================
2456% ======================================================================
2457
2458Figure \ref{fig:system1} shows a high-level picture if the \CFA runtime system in regards to concurrency.
2459Each component of the picture is explained in detail in the flowing sections.
2460
2461\begin{figure}
2462\begin{center}
2463{\resizebox{\textwidth}{!}{\input{system.pstex_t}}}
2464\end{center}
2465\caption{Overview of the entire system}
2466\label{fig:system1}
2467\end{figure}
2468
2469\subsection{Processors}
2470Parallelism 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.
2471Indeed, any parallelism must go through operating-system libraries.
2472However, \textbf{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism.
2473Indeed, processor \textbf{kthread} simply fetch a \textbf{uthread} from the scheduler and run it; they are effectively executers for user-threads.
2474The 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.
2475Processors internally use coroutines to take advantage of the existing context-switching semantics.
2476
2477\subsection{Stack Management}
2478One of the challenges of this system is to reduce the footprint as much as possible.
2479Specifically, all @pthread@s created also have a stack created with them, which should be used as much as possible.
2480Normally, 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.
2481The exception to this rule is the Main Processor, \ie the initial \textbf{kthread} that is given to any program.
2482In 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.
2483
2484\subsection{Context Switching}
2485As 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.
2486To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific routine call.
2487This 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.
2488Note that the instruction pointer can be left untouched since the context-switch is always inside the same routine
2489Threads, however, do not context-switch between each other directly.
2490They context-switch to the scheduler.
2491This 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.
2492Obviously, this doubles the context-switch cost because threads must context-switch to an intermediate stack.
2493The alternative 1-step context-switch uses the stack of the ``from'' thread to schedule and then context-switches directly to the ``to'' thread.
2494However, the performance of the 2-step context-switch is still superior to a @pthread_yield@ (see section \ref{results}).
2495Additionally, 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).
2496This option is not currently present in \CFA, but the changes required to add it are strictly additive.
2497
2498\subsection{Preemption} \label{preemption}
2499Finally, an important aspect for any complete threading system is preemption.
2500As 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.
2501Indeed, preemption is desirable because it adds a degree of isolation among threads.
2502In 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.
2503Obviously, preemption is not optimal for every workload.
2504However any preemptive system can become a cooperative system by making the time slices extremely large.
2505Therefore, \CFA uses a preemptive threading system.
2506
2507Preemption in \CFA\footnote{Note that the implementation of preemption is strongly tied with the underlying threading system.
2508For 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.
2509Every processor keeps track of the current time and registers an expiration time with the preemption system.
2510When 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.
2511These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread.
2512This 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:
2513\begin{quote}
2514A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
2515If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
2516SIGNAL(7) - Linux Programmer's Manual
2517\end{quote}
2518For 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.
2519
2520Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread.
2521Hence, 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.
2522This 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.
2523As a result, a signal handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread).
2524It 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.
2525This 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}.
2526However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel-alarm thread can cause deadlocks.
2527For this reason, the alarm thread is in a tight loop around a system call to @sigwaitinfo@, requiring very little CPU time for preemption.
2528One final detail about the alarm thread is how to wake it when additional communication is required (\eg on thread termination).
2529This unblocking is also done using {\tt SIGALRM}, but sent through the @pthread_sigqueue@.
2530Indeed, @sigwait@ can differentiate signals sent from @pthread_sigqueue@ from signals sent from alarms or the kernel.
2531
2532\subsection{Scheduler}
2533Finally, an aspect that was not mentioned yet is the scheduling algorithm.
2534Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling.
2535Further discussion on scheduling is present in section \ref{futur:sched}.
2536
2537% ======================================================================
2538% ======================================================================
2539\section{Internal Scheduling} \label{impl:intsched}
2540% ======================================================================
2541% ======================================================================
2542The following figure is the traditional illustration of a monitor (repeated from page~\pageref{fig:ClassicalMonitor} for convenience):
2543
2544\begin{figure}
2545\begin{center}
2546{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
2547\end{center}
2548\caption{Traditional illustration of a monitor}
2549\end{figure}
2550
2551This picture has several components, the two most important being the entry queue and the AS-stack.
2552The 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.
2553
2554For \CFA, this picture does not have support for blocking multiple monitors on a single condition.
2555To support bulk acquire two changes to this picture are required.
2556First, it is no longer helpful to attach the condition to \emph{a single} monitor.
2557Secondly, the thread waiting on the condition has to be separated across multiple monitors, seen in figure \ref{fig:monitor_cfa}.
2558
2559\begin{figure}
2560\begin{center}
2561{\resizebox{0.8\textwidth}{!}{\input{int_monitor}}}
2562\end{center}
2563\caption{Illustration of \CFA Monitor}
2564\label{fig:monitor_cfa}
2565\end{figure}
2566
2567This picture and the proper entry and leave algorithms (see listing \ref{f:entry2}) is the fundamental implementation of internal scheduling.
2568Note 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.
2569The thread is woken up when all the pieces have popped from the AS-stacks and made active.
2570In this picture, the threads are split into halves but this is only because there are two monitors.
2571For a specific signalling operation every monitor needs a piece of thread on its AS-stack.
2572
2573\begin{figure}
2574\begin{multicols}{2}
2575Entry
2576\begin{cfa}
2577if monitor is free
2578        enter
2579elif already own the monitor
2580        continue
2581else
2582        block
2583increment recursion
2584
2585\end{cfa}
2586\columnbreak
2587Exit
2588\begin{cfa}
2589decrement recursion
2590if recursion == 0
2591        if signal_stack not empty
2592                set_owner to thread
2593                if all monitors ready
2594                        wake-up thread
2595
2596        if entry queue not empty
2597                wake-up thread
2598\end{cfa}
2599\end{multicols}
2600\begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling},label={f:entry2}]
2601\end{cfa}
2602\end{figure}
2603
2604The solution discussed in \ref{s:InternalScheduling} can be seen in the exit routine of listing \ref{f:entry2}.
2605Basically, 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.
2606This solution is deadlock safe as well as preventing any potential barging.
2607The 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.
2608
2609\begin{figure}
2610\begin{center}
2611{\resizebox{0.8\textwidth}{!}{\input{monitor_structs.pstex_t}}}
2612\end{center}
2613\caption{Data structures involved in internal/external scheduling}
2614\label{fig:structs}
2615\end{figure}
2616
2617Figure \ref{fig:structs} shows a high-level representation of these data structures.
2618The main idea behind them is that, a thread cannot contain an arbitrary number of intrusive ``next'' pointers for linking onto monitors.
2619The @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.
2620Once 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}.
2621
2622% ======================================================================
2623% ======================================================================
2624\section{External Scheduling}
2625% ======================================================================
2626% ======================================================================
2627Similarly 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}.
2628For 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).
2629However, in the case of external scheduling, there is no equivalent object which is associated with @waitfor@ statements.
2630This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired.
2631These monitors being the only objects that have sufficient lifetime and are available on both sides of the @waitfor@ statement.
2632This requires an algorithm to choose which monitor holds the relevant queue.
2633It is also important that said algorithm be independent of the order in which users list parameters.
2634The 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.
2635This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint.
2636
2637This algorithm choice has two consequences:
2638\begin{itemize}
2639        \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.
2640These queues need to contain a set of monitors for each of the waiting threads.
2641Therefore, 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.
2642        \item The queue of the lowest priority monitor is both required and potentially unused.
2643Indeed, 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.
2644\end{itemize}
2645Therefore, the following modifications need to be made to support external scheduling:
2646\begin{itemize}
2647        \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.
2648The @mutex@ routine already has all the required information on its stack, so the thread only needs to keep a pointer to that information.
2649        \item The monitors need to keep a mask of acceptable routines.
2650This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it.
2651It also needs storage to keep track of which routine was accepted.
2652Since this information is not specific to any monitor, the monitors actually contain a pointer to an integer on the stack of the waiting thread.
2653Note 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.
2654This becomes relevant when @when@ clauses affect the number of monitors passed to a @waitfor@ statement.
2655        \item The entry/exit routines need to be updated as shown in listing \ref{f:entry3}.
2656\end{itemize}
2657
2658\subsection{External Scheduling - Destructors}
2659Finally, to support the ordering inversion of destructors, the code generation needs to be modified to use a special entry routine.
2660This routine is needed because of the storage requirements of the call order inversion.
2661Indeed, 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.
2662For 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.
2663The @waitfor@ semantics can then be adjusted correspondingly, as seen in listing \ref{f:entry-dtor}
2664
2665\begin{figure}
2666\begin{multicols}{2}
2667Entry
2668\begin{cfa}
2669if monitor is free
2670        enter
2671elif already own the monitor
2672        continue
2673elif matches waitfor mask
2674        push criteria to AS-stack
2675        continue
2676else
2677        block
2678increment recursion
2679\end{cfa}
2680\columnbreak
2681Exit
2682\begin{cfa}
2683decrement recursion
2684if recursion == 0
2685        if signal_stack not empty
2686                set_owner to thread
2687                if all monitors ready
2688                        wake-up thread
2689                endif
2690        endif
2691
2692        if entry queue not empty
2693                wake-up thread
2694        endif
2695\end{cfa}
2696\end{multicols}
2697\begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling and external scheduling},label={f:entry3}]
2698\end{cfa}
2699\end{figure}
2700
2701\begin{figure}
2702\begin{multicols}{2}
2703Destructor Entry
2704\begin{cfa}
2705if monitor is free
2706        enter
2707elif already own the monitor
2708        increment recursion
2709        return
2710create wait context
2711if matches waitfor mask
2712        reset mask
2713        push self to AS-stack
2714        baton pass
2715else
2716        wait
2717increment recursion
2718\end{cfa}
2719\columnbreak
2720Waitfor
2721\begin{cfa}
2722if matching thread is already there
2723        if found destructor
2724                push destructor to AS-stack
2725                unlock all monitors
2726        else
2727                push self to AS-stack
2728                baton pass
2729        endif
2730        return
2731endif
2732if non-blocking
2733        Unlock all monitors
2734        Return
2735endif
2736
2737push self to AS-stack
2738set waitfor mask
2739block
2740return
2741\end{cfa}
2742\end{multicols}
2743\begin{cfa}[caption={Pseudo code for the \protect\lstinline|waitfor| routine and the \protect\lstinline|mutex| entry routine for destructors},label={f:entry-dtor}]
2744\end{cfa}
2745\end{figure}
2746
2747
2748% ======================================================================
2749% ======================================================================
2750\section{Putting It All Together}
2751% ======================================================================
2752% ======================================================================
2753
2754
2755\section{Threads As Monitors}
2756As 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.
2757For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine:
2758\begin{figure}
2759\begin{cfa}[caption={Toy simulator using \protect\lstinline|thread|s and \protect\lstinline|monitor|s.},label={f:engine-v1}]
2760// Visualization declaration
2761thread Renderer {} renderer;
2762Frame * simulate( Simulator & this );
2763
2764// Simulation declaration
2765thread Simulator{} simulator;
2766void render( Renderer & this );
2767
2768// Blocking call used as communication
2769void draw( Renderer & mutex this, Frame * frame );
2770
2771// Simulation loop
2772void main( Simulator & this ) {
2773        while( true ) {
2774                Frame * frame = simulate( this );
2775                draw( renderer, frame );
2776        }
2777}
2778
2779// Rendering loop
2780void main( Renderer & this ) {
2781        while( true ) {
2782                waitfor( draw, this );
2783                render( this );
2784        }
2785}
2786\end{cfa}
2787\end{figure}
2788One 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.
2789Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner:
2790\begin{figure}
2791\begin{cfa}[caption={Same toy simulator with proper termination condition.},label={f:engine-v2}]
2792// Visualization declaration
2793thread Renderer {} renderer;
2794Frame * simulate( Simulator & this );
2795
2796// Simulation declaration
2797thread Simulator{} simulator;
2798void render( Renderer & this );
2799
2800// Blocking call used as communication
2801void draw( Renderer & mutex this, Frame * frame );
2802
2803// Simulation loop
2804void main( Simulator & this ) {
2805        while( true ) {
2806                Frame * frame = simulate( this );
2807                draw( renderer, frame );
2808
2809                // Exit main loop after the last frame
2810                if( frame->is_last ) break;
2811        }
2812}
2813
2814// Rendering loop
2815void main( Renderer & this ) {
2816        while( true ) {
2817                   waitfor( draw, this );
2818                or waitfor( ^?{}, this ) {
2819                        // Add an exit condition
2820                        break;
2821                }
2822
2823                render( this );
2824        }
2825}
2826
2827// Call destructor for simulator once simulator finishes
2828// Call destructor for renderer to signify shutdown
2829\end{cfa}
2830\end{figure}
2831
2832\section{Fibers \& Threads}
2833As mentioned in section \ref{preemption}, \CFA uses preemptive threads by default but can use fibers on demand.
2834Currently, using fibers is done by adding the following line of code to the program~:
2835\begin{cfa}
2836unsigned int default_preemption() {
2837        return 0;
2838}
2839\end{cfa}
2840This routine is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice, \ie no preemption.
2841However, 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}
2842\begin{figure}
2843\lstset{language=CFA,deletedelim=**[is][]{`}{`}}
2844\begin{cfa}[caption={Using fibers and \textbf{uthread} side-by-side in \CFA},label={f:fiber-uthread}]
2845// Cluster forward declaration
2846struct cluster;
2847
2848// Processor forward declaration
2849struct processor;
2850
2851// Construct clusters with a preemption rate
2852void ?{}(cluster& this, unsigned int rate);
2853// Construct processor and add it to cluster
2854void ?{}(processor& this, cluster& cluster);
2855// Construct thread and schedule it on cluster
2856void ?{}(thread& this, cluster& cluster);
2857
2858// Declare two clusters
2859cluster thread_cluster = { 10`ms };                     // Preempt every 10 ms
2860cluster fibers_cluster = { 0 };                         // Never preempt
2861
2862// Construct 4 processors
2863processor processors[4] = {
2864        //2 for the thread cluster
2865        thread_cluster;
2866        thread_cluster;
2867        //2 for the fibers cluster
2868        fibers_cluster;
2869        fibers_cluster;
2870};
2871
2872// Declares thread
2873thread UThread {};
2874void ?{}(UThread& this) {
2875        // Construct underlying thread to automatically
2876        // be scheduled on the thread cluster
2877        (this){ thread_cluster }
2878}
2879
2880void main(UThread & this);
2881
2882// Declares fibers
2883thread Fiber {};
2884void ?{}(Fiber& this) {
2885        // Construct underlying thread to automatically
2886        // be scheduled on the fiber cluster
2887        (this.__thread){ fibers_cluster }
2888}
2889
2890void main(Fiber & this);
2891\end{cfa}
2892\end{figure}
2893
2894
2895% ======================================================================
2896% ======================================================================
2897\section{Performance Results} \label{results}
2898% ======================================================================
2899% ======================================================================
2900\section{Machine Setup}
2901Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks.
2902All tests were made on this machine.
2903\begin{table}
2904\begin{center}
2905\begin{tabular}{| l | r | l | r |}
2906\hline
2907Architecture            & x86\_64                       & NUMA node(s)  & 8 \\
2908\hline
2909CPU op-mode(s)          & 32-bit, 64-bit                & Model name    & AMD Opteron\texttrademark  Processor 6380 \\
2910\hline
2911Byte Order                      & Little Endian                 & CPU Freq              & 2.5\si{\giga\hertz} \\
2912\hline
2913CPU(s)                  & 64                            & L1d cache     & \SI{16}{\kibi\byte} \\
2914\hline
2915Thread(s) per core      & 2                             & L1i cache     & \SI{64}{\kibi\byte} \\
2916\hline
2917Core(s) per socket      & 8                             & L2 cache              & \SI{2048}{\kibi\byte} \\
2918\hline
2919Socket(s)                       & 4                             & L3 cache              & \SI{6144}{\kibi\byte} \\
2920\hline
2921\hline
2922Operating system                & Ubuntu 16.04.3 LTS    & Kernel                & Linux 4.4-97-generic \\
2923\hline
2924Compiler                        & GCC 6.3               & Translator    & CFA 1 \\
2925\hline
2926Java version            & OpenJDK-9             & Go version    & 1.9.2 \\
2927\hline
2928\end{tabular}
2929\end{center}
2930\caption{Machine setup used for the tests}
2931\label{tab:machine}
2932\end{table}
2933
2934\section{Micro Benchmarks}
2935All benchmarks are run using the same harness to produce the results, seen as the @BENCH()@ macro in the following examples.
2936This macro uses the following logic to benchmark the code:
2937\begin{cfa}
2938#define BENCH(run, result) \
2939        before = gettime(); \
2940        run; \
2941        after  = gettime(); \
2942        result = (after - before) / N;
2943\end{cfa}
2944The method used to get time is @clock_gettime(CLOCK_THREAD_CPUTIME_ID);@.
2945Each benchmark is using many iterations of a simple call to measure the cost of the call.
2946The specific number of iterations depends on the specific benchmark.
2947
2948\subsection{Context-Switching}
2949The first interesting benchmark is to measure how long context-switches take.
2950The simplest approach to do this is to yield on a thread, which executes a 2-step context switch.
2951Yielding 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).
2952In 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.
2953Figure~\ref{f:ctx-switch} shows the code for coroutines and threads with the results in table \ref{tab:ctx-switch}.
2954All omitted tests are functionally identical to one of these tests.
2955The difference between coroutines and threads can be attributed to the cost of scheduling.
2956\begin{figure}
2957\begin{multicols}{2}
2958\CFA Coroutines
2959\begin{cfa}
2960coroutine GreatSuspender {};
2961void main(GreatSuspender& this) {
2962        while(true) { suspend(); }
2963}
2964int main() {
2965        GreatSuspender s;
2966        resume(s);
2967        BENCH(
2968                for(size_t i=0; i<n; i++) {
2969                        resume(s);
2970                },
2971                result
2972        )
2973        printf("%llu\n", result);
2974}
2975\end{cfa}
2976\columnbreak
2977\CFA Threads
2978\begin{cfa}
2979
2980
2981
2982
2983int main() {
2984
2985
2986        BENCH(
2987                for(size_t i=0; i<n; i++) {
2988                        yield();
2989                },
2990                result
2991        )
2992        printf("%llu\n", result);
2993}
2994\end{cfa}
2995\end{multicols}
2996\begin{cfa}[caption={\CFA benchmark code used to measure context-switches for coroutines and threads.},label={f:ctx-switch}]
2997\end{cfa}
2998\end{figure}
2999
3000\begin{table}
3001\begin{center}
3002\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] |}
3003\cline{2-4}
3004\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3005\hline
3006Kernel Thread   & 241.5 & 243.86        & 5.08 \\
3007\CFA Coroutine  & 38            & 38            & 0    \\
3008\CFA Thread             & 103           & 102.96        & 2.96 \\
3009\uC Coroutine   & 46            & 45.86 & 0.35 \\
3010\uC Thread              & 98            & 99.11 & 1.42 \\
3011Goroutine               & 150           & 149.96        & 3.16 \\
3012Java Thread             & 289           & 290.68        & 8.72 \\
3013\hline
3014\end{tabular}
3015\end{center}
3016\caption{Context Switch comparison.
3017All numbers are in nanoseconds(\si{\nano\second})}
3018\label{tab:ctx-switch}
3019\end{table}
3020
3021\subsection{Mutual-Exclusion}
3022The next interesting benchmark is to measure the overhead to enter/leave a critical-section.
3023For monitors, the simplest approach is to measure how long it takes to enter and leave a monitor routine.
3024Figure~\ref{f:mutex} shows the code for \CFA.
3025To 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.
3026The results can be shown in table \ref{tab:mutex}.
3027
3028\begin{figure}
3029\begin{cfa}[caption={\CFA benchmark code used to measure mutex routines.},label={f:mutex}]
3030monitor M {};
3031void __attribute__((noinline)) call( M & mutex m /*, m2, m3, m4*/ ) {}
3032
3033int main() {
3034        M m/*, m2, m3, m4*/;
3035        BENCH(
3036                for(size_t i=0; i<n; i++) {
3037                        call(m/*, m2, m3, m4*/);
3038                },
3039                result
3040        )
3041        printf("%llu\n", result);
3042}
3043\end{cfa}
3044\end{figure}
3045
3046\begin{table}
3047\begin{center}
3048\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] |}
3049\cline{2-4}
3050\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3051\hline
3052C routine                                               & 2             & 2             & 0    \\
3053FetchAdd + FetchSub                             & 26            & 26            & 0    \\
3054Pthreads Mutex Lock                             & 31            & 31.86 & 0.99 \\
3055\uC @monitor@ member routine            & 30            & 30            & 0    \\
3056\CFA @mutex@ routine, 1 argument        & 41            & 41.57 & 0.9  \\
3057\CFA @mutex@ routine, 2 argument        & 76            & 76.96 & 1.57 \\
3058\CFA @mutex@ routine, 4 argument        & 145           & 146.68        & 3.85 \\
3059Java synchronized routine                       & 27            & 28.57 & 2.6  \\
3060\hline
3061\end{tabular}
3062\end{center}
3063\caption{Mutex routine comparison.
3064All numbers are in nanoseconds(\si{\nano\second})}
3065\label{tab:mutex}
3066\end{table}
3067
3068\subsection{Internal Scheduling}
3069The internal-scheduling benchmark measures the cost of waiting on and signalling a condition variable.
3070Figure~\ref{f:int-sched} shows the code for \CFA, with results table \ref{tab:int-sched}.
3071As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
3072
3073\begin{figure}
3074\begin{cfa}[caption={Benchmark code for internal scheduling},label={f:int-sched}]
3075volatile int go = 0;
3076condition c;
3077monitor M {};
3078M m1;
3079
3080void __attribute__((noinline)) do_call( M & mutex a1 ) { signal(c); }
3081
3082thread T {};
3083void ^?{}( T & mutex this ) {}
3084void main( T & this ) {
3085        while(go == 0) { yield(); }
3086        while(go == 1) { do_call(m1); }
3087}
3088int  __attribute__((noinline)) do_wait( M & mutex a1 ) {
3089        go = 1;
3090        BENCH(
3091                for(size_t i=0; i<n; i++) {
3092                        wait(c);
3093                },
3094                result
3095        )
3096        printf("%llu\n", result);
3097        go = 0;
3098        return 0;
3099}
3100int main() {
3101        T t;
3102        return do_wait(m1);
3103}
3104\end{cfa}
3105\end{figure}
3106
3107\begin{table}
3108\begin{center}
3109\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] |}
3110\cline{2-4}
3111\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3112\hline
3113Pthreads Condition Variable                     & 5902.5        & 6093.29       & 714.78 \\
3114\uC @signal@                                    & 322           & 323   & 3.36   \\
3115\CFA @signal@, 1 @monitor@      & 352.5 & 353.11        & 3.66   \\
3116\CFA @signal@, 2 @monitor@      & 430           & 430.29        & 8.97   \\
3117\CFA @signal@, 4 @monitor@      & 594.5 & 606.57        & 18.33  \\
3118Java @notify@                           & 13831.5       & 15698.21      & 4782.3 \\
3119\hline
3120\end{tabular}
3121\end{center}
3122\caption{Internal scheduling comparison.
3123All numbers are in nanoseconds(\si{\nano\second})}
3124\label{tab:int-sched}
3125\end{table}
3126
3127\subsection{External Scheduling}
3128The Internal scheduling benchmark measures the cost of the @waitfor@ statement (@_Accept@ in \uC).
3129Figure~\ref{f:ext-sched} shows the code for \CFA, with results in table \ref{tab:ext-sched}.
3130As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
3131
3132\begin{figure}
3133\begin{cfa}[caption={Benchmark code for external scheduling},label={f:ext-sched}]
3134volatile int go = 0;
3135monitor M {};
3136M m1;
3137thread T {};
3138
3139void __attribute__((noinline)) do_call( M & mutex a1 ) {}
3140
3141void ^?{}( T & mutex this ) {}
3142void main( T & this ) {
3143        while(go == 0) { yield(); }
3144        while(go == 1) { do_call(m1); }
3145}
3146int  __attribute__((noinline)) do_wait( M & mutex a1 ) {
3147        go = 1;
3148        BENCH(
3149                for(size_t i=0; i<n; i++) {
3150                        waitfor(call, a1);
3151                },
3152                result
3153        )
3154        printf("%llu\n", result);
3155        go = 0;
3156        return 0;
3157}
3158int main() {
3159        T t;
3160        return do_wait(m1);
3161}
3162\end{cfa}
3163\end{figure}
3164
3165\begin{table}
3166\begin{center}
3167\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] |}
3168\cline{2-4}
3169\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3170\hline
3171\uC @Accept@                                    & 350           & 350.61        & 3.11  \\
3172\CFA @waitfor@, 1 @monitor@     & 358.5 & 358.36        & 3.82  \\
3173\CFA @waitfor@, 2 @monitor@     & 422           & 426.79        & 7.95  \\
3174\CFA @waitfor@, 4 @monitor@     & 579.5 & 585.46        & 11.25 \\
3175\hline
3176\end{tabular}
3177\end{center}
3178\caption{External scheduling comparison.
3179All numbers are in nanoseconds(\si{\nano\second})}
3180\label{tab:ext-sched}
3181\end{table}
3182
3183
3184\subsection{Object Creation}
3185Finally, the last benchmark measures the cost of creation for concurrent objects.
3186Figure~\ref{f:creation} shows the code for @pthread@s and \CFA threads, with results shown in table \ref{tab:creation}.
3187As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
3188The 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.
3189
3190\begin{figure}
3191\begin{center}
3192@pthread@
3193\begin{cfa}
3194int main() {
3195        BENCH(
3196                for(size_t i=0; i<n; i++) {
3197                        pthread_t thread;
3198                        if(pthread_create(&thread,NULL,foo,NULL)<0) {
3199                                perror( "failure" );
3200                                return 1;
3201                        }
3202
3203                        if(pthread_join(thread, NULL)<0) {
3204                                perror( "failure" );
3205                                return 1;
3206                        }
3207                },
3208                result
3209        )
3210        printf("%llu\n", result);
3211}
3212\end{cfa}
3213
3214
3215
3216\CFA Threads
3217\begin{cfa}
3218int main() {
3219        BENCH(
3220                for(size_t i=0; i<n; i++) {
3221                        MyThread m;
3222                },
3223                result
3224        )
3225        printf("%llu\n", result);
3226}
3227\end{cfa}
3228\end{center}
3229\caption{Benchmark code for \protect\lstinline|pthread|s and \CFA to measure object creation}
3230\label{f:creation}
3231\end{figure}
3232
3233\begin{table}
3234\begin{center}
3235\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] |}
3236\cline{2-4}
3237\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3238\hline
3239Pthreads                        & 26996 & 26984.71      & 156.6  \\
3240\CFA Coroutine Lazy     & 6             & 5.71  & 0.45   \\
3241\CFA Coroutine Eager    & 708           & 706.68        & 4.82   \\
3242\CFA Thread                     & 1173.5        & 1176.18       & 15.18  \\
3243\uC Coroutine           & 109           & 107.46        & 1.74   \\
3244\uC Thread                      & 526           & 530.89        & 9.73   \\
3245Goroutine                       & 2520.5        & 2530.93       & 61,56  \\
3246Java Thread                     & 91114.5       & 92272.79      & 961.58 \\
3247\hline
3248\end{tabular}
3249\end{center}
3250\caption{Creation comparison.
3251All numbers are in nanoseconds(\si{\nano\second}).}
3252\label{tab:creation}
3253\end{table}
3254
3255
3256
3257\section{Conclusion}
3258This paper has achieved a minimal concurrency \textbf{api} that is simple, efficient and usable as the basis for higher-level features.
3259The approach presented is based on a lightweight thread-system for parallelism, which sits on top of clusters of processors.
3260This M:N model is judged to be both more efficient and allow more flexibility for users.
3261Furthermore, this document introduces monitors as the main concurrency tool for users.
3262This paper also offers a novel approach allowing multiple monitors to be accessed simultaneously without running into the Nested Monitor Problem~\cite{Lister77}.
3263It also offers a full implementation of the concurrency runtime written entirely in \CFA, effectively the largest \CFA code base to date.
3264
3265
3266% ======================================================================
3267% ======================================================================
3268\section{Future Work}
3269% ======================================================================
3270% ======================================================================
3271
3272\subsection{Performance} \label{futur:perf}
3273This paper presents a first implementation of the \CFA concurrency runtime.
3274Therefore, there is still significant work to improve performance.
3275Many of the data structures and algorithms may change in the future to more efficient versions.
3276For example, the number of monitors in a single bulk acquire is only bound by the stack size, this is probably unnecessarily generous.
3277It may be possible that limiting the number helps increase performance.
3278However, it is not obvious that the benefit would be significant.
3279
3280\subsection{Flexible Scheduling} \label{futur:sched}
3281An important part of concurrency is scheduling.
3282Different scheduling algorithms can affect performance (both in terms of average and variation).
3283However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
3284One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted to the requirements of the workload.
3285However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms.
3286For 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.
3287This path of flexible schedulers will be explored for \CFA.
3288
3289\subsection{Non-Blocking I/O} \label{futur:nbio}
3290While 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).
3291These types of workloads often require significant engineering around amortizing costs of blocking IO operations.
3292At 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.
3293In this context, the role of the language makes Non-Blocking IO easily available and with low overhead.
3294The 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.
3295However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear.
3296
3297\subsection{Other Concurrency Tools} \label{futur:tools}
3298While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
3299Examples of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, executors and actors.
3300These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
3301
3302\subsection{Implicit Threading} \label{futur:implcit}
3303Simpler applications can benefit greatly from having implicit parallelism.
3304That is, parallelism that does not rely on the user to write concurrency.
3305This type of parallelism can be achieved both at the language level and at the library level.
3306The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithms~\cite{uC++book}.
3307Table \ref{f:parfor} shows three different code examples that accomplish point-wise sums of large arrays.
3308Note that none of these examples explicitly declare any concurrency or parallelism objects.
3309
3310\begin{table}
3311\begin{center}
3312\begin{tabular}[t]{|c|c|c|}
3313Sequential & Library Parallel & Language Parallel \\
3314\begin{cfa}[tabsize=3]
3315void big_sum(
3316        int* a, int* b,
3317        int* o,
3318        size_t len)
3319{
3320        for(
3321                int i = 0;
3322                i < len;
3323                ++i )
3324        {
3325                o[i]=a[i]+b[i];
3326        }
3327}
3328
3329
3330
3331
3332
3333int* a[10000];
3334int* b[10000];
3335int* c[10000];
3336//... fill in a & b
3337big_sum(a,b,c,10000);
3338\end{cfa} &\begin{cfa}[tabsize=3]
3339void big_sum(
3340        int* a, int* b,
3341        int* o,
3342        size_t len)
3343{
3344        range ar(a, a+len);
3345        range br(b, b+len);
3346        range or(o, o+len);
3347        parfor( ai, bi, oi,
3348        [](     int* ai,
3349                int* bi,
3350                int* oi)
3351        {
3352                oi=ai+bi;
3353        });
3354}
3355
3356
3357int* a[10000];
3358int* b[10000];
3359int* c[10000];
3360//... fill in a & b
3361big_sum(a,b,c,10000);
3362\end{cfa}&\begin{cfa}[tabsize=3]
3363void big_sum(
3364        int* a, int* b,
3365        int* o,
3366        size_t len)
3367{
3368        parfor (ai,bi,oi)
3369            in (a, b, o )
3370        {
3371                oi = ai + bi;
3372        }
3373}
3374
3375
3376
3377
3378
3379
3380
3381int* a[10000];
3382int* b[10000];
3383int* c[10000];
3384//... fill in a & b
3385big_sum(a,b,c,10000);
3386\end{cfa}
3387\end{tabular}
3388\end{center}
3389\caption{For loop to sum numbers: Sequential, using library parallelism and language parallelism.}
3390\label{f:parfor}
3391\end{table}
3392
3393Implicit parallelism is a restrictive solution and therefore has its limitations.
3394However, 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.
3395
3396
3397% A C K N O W L E D G E M E N T S
3398% -------------------------------
3399\section{Acknowledgements}
3400
3401Thanks 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.
3402Partial funding was supplied by the Natural Sciences and Engineering Research Council of Canada and a corporate partnership with Huawei Ltd.
3403
3404
3405% B I B L I O G R A P H Y
3406% -----------------------------
3407%\bibliographystyle{plain}
3408\bibliography{pl,local}
3409
3410
3411\end{document}
3412
3413% Local Variables: %
3414% tab-width: 4 %
3415% fill-column: 120 %
3416% compile-command: "make" %
3417% End: %
Note: See TracBrowser for help on using the repository browser.