source: doc/papers/concurrency/Paper.tex @ 251454a0

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

more writing

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