source: doc/papers/concurrency/Paper.tex @ 9a72c4d

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

updates

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