source: doc/papers/concurrency/Paper.tex @ 48b9b36

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

writing updates

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