source: doc/papers/concurrency/Paper.tex @ 1dc58fd

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

more writing

  • Property mode set to 100644
File size: 161.6 KB
Line 
1\documentclass[AMA,STIX1COL]{WileyNJD-v2}
2
3\articletype{RESEARCH ARTICLE}%
4
5\received{26 April 2016}
6\revised{6 June 2016}
7\accepted{6 June 2016}
8
9\raggedbottom
10
11%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
12
13% Latex packages used in the document.
14
15\usepackage{epic,eepic}
16\usepackage{xspace}
17\usepackage{comment}
18\usepackage{upquote}                                            % switch curled `'" to straight
19\usepackage{listings}                                           % format program code
20\usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig}
21\renewcommand{\thesubfigure}{(\Alph{subfigure})}
22\captionsetup{justification=raggedright,singlelinecheck=false}
23\usepackage{siunitx}
24\sisetup{binary-units=true}
25
26\hypersetup{breaklinks=true}
27\definecolor{OliveGreen}{cmyk}{0.64 0 0.95 0.40}
28\definecolor{Mahogany}{cmyk}{0 0.85 0.87 0.35}
29\definecolor{Plum}{cmyk}{0.50 1 0 0}
30
31\usepackage[pagewise]{lineno}
32\renewcommand{\linenumberfont}{\scriptsize\sffamily}
33
34\renewcommand{\textfraction}{0.0}                       % the entire page maybe devoted to floats with no text on the page at all
35
36\lefthyphenmin=3                                                        % hyphen only after 4 characters
37\righthyphenmin=3
38
39%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
41% Names used in the document.
42
43\newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
44\newcommand{\CFA}{\protect\CFAIcon}             % safe for section/caption
45\newcommand{\CFL}{\textrm{Cforall}\xspace}      % Cforall symbolic name
46\newcommand{\Celeven}{\textrm{C11}\xspace}      % C11 symbolic name
47\newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
48\newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
49\newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
50\newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
51\newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name
52\newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name
53
54%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
55
56\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
57\newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}}
58\newcommand{\R}[1]{\Textbf{#1}}
59\newcommand{\B}[1]{{\Textbf[blue]{#1}}}
60\newcommand{\G}[1]{{\Textbf[OliveGreen]{#1}}}
61\newcommand{\uC}{$\mu$\CC}
62\newcommand{\cit}{\textsuperscript{[Citation Needed]}\xspace}
63\newcommand{\TODO}{{\Textbf{TODO}}}
64
65%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
66
67% Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
68% removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
69% AFTER HYPERREF.
70%\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}
71\renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}
72
73\renewcommand*{\thefootnote}{\Alph{footnote}} % hack because fnsymbol does not work
74%\renewcommand*{\thefootnote}{\fnsymbol{footnote}}
75
76\makeatletter
77% parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
78% use rather than use \parident directly.
79\newlength{\parindentlnth}
80\setlength{\parindentlnth}{\parindent}
81
82\newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{\lst@basicstyle{#1}}}}
83\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
84\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
85
86\newlength{\gcolumnposn}                                        % temporary hack because lstlisting does not handle tabs correctly
87\newlength{\columnposn}
88\setlength{\gcolumnposn}{3.5in}
89\setlength{\columnposn}{\gcolumnposn}
90
91\newcommand{\C}[2][\@empty]{\ifx#1\@empty\else\global\setlength{\columnposn}{#1}\global\columnposn=\columnposn\fi\hfill\makebox[\textwidth-\columnposn][l]{\lst@basicstyle{\LstCommentStyle{#2}}}}
92\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
93
94% Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
95% The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
96% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
97\newcommand{\newtermFontInline}{\emph}
98\newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
99\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
100\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
101
102% Latin abbreviation
103\newcommand{\abbrevFont}{\textit}                       % set empty for no italics
104\@ifundefined{eg}{
105\newcommand{\EG}{\abbrevFont{e}\abbrevFont{g}}
106\newcommand*{\eg}{%
107        \@ifnextchar{,}{\EG}%
108                {\@ifnextchar{:}{\EG}%
109                        {\EG,\xspace}}%
110}}{}%
111\@ifundefined{ie}{
112\newcommand{\IE}{\abbrevFont{i}\abbrevFont{e}}
113\newcommand*{\ie}{%
114        \@ifnextchar{,}{\IE}%
115                {\@ifnextchar{:}{\IE}%
116                        {\IE,\xspace}}%
117}}{}%
118\@ifundefined{etc}{
119\newcommand{\ETC}{\abbrevFont{etc}}
120\newcommand*{\etc}{%
121        \@ifnextchar{.}{\ETC}%
122        {\ETC.\xspace}%
123}}{}%
124\@ifundefined{etal}{
125\newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}}
126\newcommand*{\etal}{%
127        \@ifnextchar{.}{\protect\ETAL}%
128                {\protect\ETAL.\xspace}%
129}}{}%
130\@ifundefined{viz}{
131\newcommand{\VIZ}{\abbrevFont{viz}}
132\newcommand*{\viz}{%
133        \@ifnextchar{.}{\VIZ}%
134                {\VIZ.\xspace}%
135}}{}%
136\makeatother
137
138\newenvironment{cquote}{%
139        \list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
140        \item\relax
141}{%
142        \endlist
143}% cquote
144
145% CFA programming language, based on ANSI C (with some gcc additions)
146\lstdefinelanguage{CFA}[ANSI]{C}{
147        morekeywords={
148                _Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, __attribute, __attribute__,
149                auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__, __const, __const__,
150                coroutine, disable, dtype, enable, exception, __extension__, fallthrough, fallthru, finally,
151                __float80, float80, __float128, float128, forall, ftype, _Generic, _Imaginary, __imag, __imag__,
152                inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
153                otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread,
154                _Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
155                virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
156        moredirectives={defined,include_next}%
157}
158
159\lstset{
160language=CFA,
161columns=fullflexible,
162basicstyle=\linespread{0.9}\sf,                                                 % reduce line spacing and use sanserif font
163stringstyle=\tt,                                                                                % use typewriter font
164tabsize=5,                                                                                              % N space tabbing
165xleftmargin=\parindentlnth,                                                             % indent code to paragraph indentation
166%mathescape=true,                                                                               % LaTeX math escape in CFA code $...$
167escapechar=\$,                                                                                  % LaTeX escape in CFA code
168keepspaces=true,                                                                                %
169showstringspaces=false,                                                                 % do not show spaces with cup
170showlines=true,                                                                                 % show blank lines at end of code
171aboveskip=4pt,                                                                                  % spacing above/below code block
172belowskip=3pt,
173% replace/adjust listing characters that look bad in sanserif
174literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
175        {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
176        {<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
177        {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex{\textrm{\textgreater}}}2,
178moredelim=**[is][\color{red}]{`}{`},
179}% lstset
180
181% uC++ programming language, based on ANSI C++
182\lstdefinelanguage{uC++}[ANSI]{C++}{
183        morekeywords={
184                _Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _CatchResume, _Cormonitor, _Coroutine, _Disable,
185                _Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
186                _Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
187}
188\lstdefinelanguage{Golang}{
189        morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
190        morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
191                bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
192        morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
193        morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
194        morekeywords=[5]{Println,Printf,Error,},
195        sensitive=true,
196        morecomment=[l]{//},
197        morecomment=[s]{/*}{*/},
198        morestring=[b]',
199        morestring=[b]",
200        morestring=[s]{`}{`},
201}
202
203\lstnewenvironment{cfa}[1][]
204{\lstset{#1}}
205{}
206\lstnewenvironment{C++}[1][]                            % use C++ style
207{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
208{}
209\lstnewenvironment{uC++}[1][]
210{\lstset{#1}}
211{}
212\lstnewenvironment{Go}[1][]
213{\lstset{#1}}
214{}
215
216% inline code @...@
217\lstMakeShortInline@%
218
219\let\OLDthebibliography\thebibliography
220\renewcommand\thebibliography[1]{
221  \OLDthebibliography{#1}
222  \setlength{\parskip}{0pt}
223  \setlength{\itemsep}{4pt plus 0.3ex}
224}
225
226\title{\texorpdfstring{Concurrency in \protect\CFA}{Concurrency in Cforall}}
227
228\author[1]{Thierry Delisle}
229\author[1]{Peter A. Buhr*}
230\authormark{DELISLE \textsc{et al.}}
231
232\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}
233
234\corres{*Peter A. Buhr, Cheriton School of Computer Science, University of Waterloo, 200 University Avenue West, Waterloo, ON, N2L 3G1, Canada. \email{pabuhr{\char`\@}uwaterloo.ca}}
235
236\fundingInfo{Natural Sciences and Engineering Research Council of Canada}
237
238\abstract[Summary]{
239\CFA is a modern, polymorphic, \emph{non-object-oriented} extension of the C programming language.
240This paper discusses the design of the concurrency and parallelism features in \CFA, and the concurrent runtime-system.
241These features are created from scratch as ISO C lacks concurrency, relying largely on the pthreads library.
242Coroutines and lightweight (user) threads are introduced into the language.
243In addition, monitors are added as a high-level mechanism for mutual exclusion and synchronization.
244A unique contribution is allowing multiple monitors to be safely acquired simultaneously.
245All features respect the expectations of C programmers, while being fully integrate with the \CFA polymorphic type-system and other language features.
246Finally, experimental results are presented to compare the performance of the new features with similar mechanisms in other concurrent programming-languages.
247}%
248
249\keywords{concurrency, parallelism, coroutines, threads, monitors, runtime, C, Cforall}
250
251
252\begin{document}
253\linenumbers                                            % comment out to turn off line numbering
254
255\maketitle
256
257
258\section{Introduction}
259
260This paper provides a minimal concurrency \newterm{Abstract Program Interface} (API) that is simple, efficient and can be used to build other concurrency features.
261While the simplest concurrency system is a thread and a lock, this low-level approach is hard to master.
262An easier approach for programmers is to support higher-level constructs as the basis of concurrency.
263Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{Hochstein05}.
264Examples of high-level approaches are task (work) based~\cite{TBB}, implicit threading~\cite{OpenMP}, monitors~\cite{Java}, channels~\cite{CSP,Go}, and message passing~\cite{Erlang,MPI}.
265
266The following terminology is used.
267A \newterm{thread} is a fundamental unit of execution that runs a sequence of code and requires a stack to maintain state.
268Multiple simultaneous threads give rise to \newterm{concurrency}, which requires locking to ensure safe communication and access to shared data.
269% Correspondingly, concurrency is defined as the concepts and challenges that occur when multiple independent (sharing memory, timing dependencies, \etc) concurrent threads are introduced.
270\newterm{Locking}, and by extension \newterm{locks}, are defined as a mechanism to prevent progress of threads to provide safety.
271\newterm{Parallelism} is running multiple threads simultaneously.
272Parallelism implies \emph{actual} simultaneous execution, where concurrency only requires \emph{apparent} simultaneous execution.
273As such, parallelism only affects performance, which is observed through differences in space and/or time at runtime.
274
275Hence, there are two problems to be solved: concurrency and parallelism.
276While these two concepts are often combined, they are distinct, requiring different tools~\cite[\S~2]{Buhr05a}.
277Concurrency tools handle synchronization and mutual exclusion, while parallelism tools handle performance, cost and resource utilization.
278
279The proposed concurrency API is implemented in a dialect of C, called \CFA.
280The paper discusses how the language features are added to the \CFA translator with respect to parsing, semantic, and type checking, and the corresponding high-performance runtime-library to implement the concurrency features.
281
282
283\section{\CFA Overview}
284
285The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency.
286Extended versions and explanation of the following code examples are available at the \CFA website~\cite{Cforall} or in Moss~\etal~\cite{Moss18}.
287
288\CFA is an extension of ISO-C, and hence, supports all C paradigms.
289%It is a non-object-oriented system-language, meaning most of the major abstractions have either no runtime overhead or can be opted out easily.
290Like C, the basics of \CFA revolve around structures and 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 \newterm{synchronization} is a timing relationship among threads and \newterm{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{Basics}
1236
1237Non-determinism requires concurrent systems to offer support for mutual-exclusion and synchronization.
1238Mutual-exclusion is the concept that only a fixed number of threads can access a critical section at any given time, where a critical section is a group of instructions on an associated portion of data that requires the restricted access.
1239On the other hand, synchronization enforces relative ordering of execution and synchronization tools provide numerous mechanisms to establish timing relationships among threads.
1240
1241
1242\subsubsection{Mutual-Exclusion}
1243
1244As mentioned above, mutual-exclusion is the guarantee that only a fix number of threads can enter a critical section at once.
1245However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
1246Methods range from low-level locks, which are fast and flexible but require significant attention to be correct, to  higher-level concurrency techniques, which sacrifice some performance in order to improve ease of use.
1247Ease of use comes by either guaranteeing some problems cannot occur (\eg being deadlock free) or by offering a more explicit coupling between data and corresponding critical section.
1248For 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).
1249Another challenge with low-level locks is composability.
1250Locks have restricted composability because it takes careful organizing for multiple locks to be used while preventing deadlocks.
1251Easing composability is another feature higher-level mutual-exclusion mechanisms often offer.
1252
1253
1254\subsubsection{Synchronization}
1255
1256As with mutual-exclusion, low-level synchronization primitives often offer good performance and good flexibility at the cost of ease of use.
1257Again, higher-level mechanisms often simplify usage by adding either better coupling between synchronization and data (\eg message passing) or offering a simpler solution to otherwise involved challenges.
1258As mentioned above, synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}.
1259Most of the time, synchronization happens within a critical section, where threads must acquire mutual-exclusion in a certain order.
1260However, it may also be desirable to guarantee that event \textit{Z} does not occur between \textit{X} and \textit{Y}.
1261Not satisfying this property is called \textbf{barging}.
1262For example, where event \textit{X} tries to effect event \textit{Y} but another thread acquires the critical section and emits \textit{Z} before \textit{Y}.
1263The classic example is the thread that finishes using a resource and unblocks a thread waiting to use the resource, but the unblocked thread must compete to acquire the resource.
1264Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
1265This challenge is often split into two different methods, barging avoidance and barging prevention.
1266Algorithms that use flag variables to detect barging threads are said to be using barging avoidance, while algorithms that baton-pass locks~\cite{Andrews89} between threads instead of releasing the locks are said to be using barging prevention.
1267
1268
1269\section{Monitors}
1270\label{s:Monitors}
1271
1272A \textbf{monitor} is a set of routines that ensure mutual-exclusion when accessing shared state.
1273More precisely, a monitor is a programming technique that 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.
1274This strong association eases readability and maintainability, at the cost of flexibility.
1275Note that both monitors and mutex locks, require an abstract handle to identify them.
1276This concept is generally associated with object-oriented languages like Java~\cite{Java} or \uC~\cite{uC++book} but does not strictly require OO semantics.
1277The only requirement is the ability to declare a handle to a shared object and a set of routines that act on it:
1278\begin{cfa}
1279typedef /*some monitor type*/ monitor;
1280int f(monitor & m);
1281
1282int main() {
1283        monitor m;  // Handle m
1284        f(m);       // Routine using handle
1285}
1286\end{cfa}
1287
1288% ======================================================================
1289% ======================================================================
1290\subsection{Call Semantics} \label{call}
1291% ======================================================================
1292% ======================================================================
1293The above monitor example displays some of the intrinsic characteristics.
1294First, it is necessary to use pass-by-reference over pass-by-value for monitor routines.
1295This semantics is important, because at their core, monitors are implicit mutual-exclusion objects (locks), and these objects cannot be copied.
1296Therefore, monitors are non-copy-able objects (@dtype@).
1297
1298Another aspect to consider is when a monitor acquires its mutual exclusion.
1299For example, a monitor may need to be passed through multiple helper routines that do not acquire the monitor mutual-exclusion on entry.
1300Passthrough can occur for generic helper routines (@swap@, @sort@, \etc) or specific helper routines like the following to implement an atomic counter:
1301
1302\begin{cfa}
1303monitor counter_t { /*...see section $\ref{data}$...*/ };
1304
1305void ?{}(counter_t & nomutex this); // constructor
1306size_t ++?(counter_t & mutex this); // increment
1307
1308// need for mutex is platform dependent
1309void ?{}(size_t * this, counter_t & mutex cnt); // conversion
1310\end{cfa}
1311This counter is used as follows:
1312\begin{center}
1313\begin{tabular}{c @{\hskip 0.35in} c @{\hskip 0.35in} c}
1314\begin{cfa}
1315// shared counter
1316counter_t cnt1, cnt2;
1317
1318// multiple threads access counter
1319thread 1 : cnt1++; cnt2++;
1320thread 2 : cnt1++; cnt2++;
1321thread 3 : cnt1++; cnt2++;
1322        ...
1323thread N : cnt1++; cnt2++;
1324\end{cfa}
1325\end{tabular}
1326\end{center}
1327Notice 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@.
1328
1329Here, the constructor (@?{}@) uses the @nomutex@ keyword to signify that it does not acquire the monitor mutual-exclusion when constructing.
1330This semantics is because an object not yet constructed should never be shared and therefore does not require mutual exclusion.
1331Furthermore, it allows the implementation greater freedom when it initializes the monitor locking.
1332The prefix increment operator uses @mutex@ to protect the incrementing process from race conditions.
1333Finally, there is a conversion operator from @counter_t@ to @size_t@.
1334This conversion may or may not require the @mutex@ keyword depending on whether or not reading a @size_t@ is an atomic operation.
1335
1336For maximum usability, monitors use \textbf{multi-acq} semantics, which means a single thread can acquire the same monitor multiple times without deadlock.
1337For example, listing \ref{fig:search} uses recursion and \textbf{multi-acq} to print values inside a binary tree.
1338\begin{figure}
1339\begin{cfa}[caption={Recursive printing algorithm using \textbf{multi-acq}.},label={fig:search}]
1340monitor printer { ... };
1341struct tree {
1342        tree * left, right;
1343        char * value;
1344};
1345void print(printer & mutex p, char * v);
1346
1347void print(printer & mutex p, tree * t) {
1348        print(p, t->value);
1349        print(p, t->left );
1350        print(p, t->right);
1351}
1352\end{cfa}
1353\end{figure}
1354
1355Having both @mutex@ and @nomutex@ keywords can be redundant, depending on the meaning of a routine having neither of these keywords.
1356For 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.
1357On the other hand, @nomutex@ is the ``normal'' parameter behaviour, it effectively states explicitly that ``this routine is not special''.
1358Another alternative is making exactly one of these keywords mandatory, which provides the same semantics but without the ambiguity of supporting routines with neither keyword.
1359Mandatory keywords would also have the added benefit of being self-documented but at the cost of extra typing.
1360While there are several benefits to mandatory keywords, they do bring a few challenges.
1361Mandatory keywords in \CFA would imply that the compiler must know without doubt whether or not a parameter is a monitor or not.
1362Since \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.
1363For this reason, \CFA only has the @mutex@ keyword and uses no keyword to mean @nomutex@.
1364
1365The next semantic decision is to establish when @mutex@ may be used as a type qualifier.
1366Consider the following declarations:
1367\begin{cfa}
1368int f1(monitor & mutex m);
1369int f2(const monitor & mutex m);
1370int f3(monitor ** mutex m);
1371int f4(monitor * mutex m []);
1372int f5(graph(monitor *) & mutex m);
1373\end{cfa}
1374The problem is to identify which object(s) should be acquired.
1375Furthermore, each object needs to be acquired only once.
1376In the case of simple routines like @f1@ and @f2@ it is easy to identify an exhaustive list of objects to acquire on entry.
1377Adding indirections (@f3@) still allows the compiler and programmer to identify which object is acquired.
1378However, adding in arrays (@f4@) makes it much harder.
1379Array lengths are not necessarily known in C, and even then, making sure objects are only acquired once becomes none-trivial.
1380This problem can be extended to absurd limits like @f5@, which uses a graph of monitors.
1381To 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).
1382Also 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.
1383However, this ambiguity is part of the C type-system with respects to arrays.
1384For this reason, @mutex@ is disallowed in the context where arrays may be passed:
1385\begin{cfa}
1386int f1(monitor & mutex m);    // Okay : recommended case
1387int f2(monitor * mutex m);    // Not Okay : Could be an array
1388int f3(monitor mutex m []);  // Not Okay : Array of unknown length
1389int f4(monitor ** mutex m);   // Not Okay : Could be an array
1390int f5(monitor * mutex m []); // Not Okay : Array of unknown length
1391\end{cfa}
1392Note that not all array functions are actually distinct in the type system.
1393However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
1394
1395Unlike 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.
1396A consequence of this approach is that it extends naturally to multi-monitor calls.
1397\begin{cfa}
1398int f(MonitorA & mutex a, MonitorB & mutex b);
1399
1400MonitorA a;
1401MonitorB b;
1402f(a,b);
1403\end{cfa}
1404While OO monitors could be extended with a mutex qualifier for multiple-monitor calls, no example of this feature could be found.
1405The capability to acquire multiple locks before entering a critical section is called \emph{\textbf{bulk-acq}}.
1406In practice, writing multi-locking routines that do not lead to deadlocks is tricky.
1407Having language support for such a feature is therefore a significant asset for \CFA.
1408In the case presented above, \CFA guarantees that the order of acquisition is consistent across calls to different routines using the same monitors as arguments.
1409This consistent ordering means acquiring multiple monitors is safe from deadlock when using \textbf{bulk-acq}.
1410However, users can still force the acquiring order.
1411For example, notice which routines use @mutex@/@nomutex@ and how this affects acquiring order:
1412\begin{cfa}
1413void foo(A& mutex a, B& mutex b) { // acquire a & b
1414        ...
1415}
1416
1417void bar(A& mutex a, B& /*nomutex*/ b) { // acquire a
1418        ... foo(a, b); ... // acquire b
1419}
1420
1421void baz(A& /*nomutex*/ a, B& mutex b) { // acquire b
1422        ... foo(a, b); ... // acquire a
1423}
1424\end{cfa}
1425The \textbf{multi-acq} monitor lock allows a monitor lock to be acquired by both @bar@ or @baz@ and acquired again in @foo@.
1426In the calls to @bar@ and @baz@ the monitors are acquired in opposite order.
1427
1428However, such use leads to lock acquiring order problems.
1429In the example above, the user uses implicit ordering in the case of function @foo@ but explicit ordering in the case of @bar@ and @baz@.
1430This subtle difference means that calling these routines concurrently may lead to deadlock and is therefore undefined behaviour.
1431As shown~\cite{Lister77}, solving this problem requires:
1432\begin{enumerate}
1433        \item Dynamically tracking the monitor-call order.
1434        \item Implement rollback semantics.
1435\end{enumerate}
1436While 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}.
1437In \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.
1438While \CFA provides only a partial solution, most systems provide no solution and the \CFA partial solution handles many useful cases.
1439
1440For example, \textbf{multi-acq} and \textbf{bulk-acq} can be used together in interesting ways:
1441\begin{cfa}
1442monitor bank { ... };
1443
1444void deposit( bank & mutex b, int deposit );
1445
1446void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) {
1447        deposit( mybank, -me2you );
1448        deposit( yourbank, me2you );
1449}
1450\end{cfa}
1451This example shows a trivial solution to the bank-account transfer problem~\cite{BankTransfer}.
1452Without \textbf{multi-acq} and \textbf{bulk-acq}, the solution to this problem is much more involved and requires careful engineering.
1453
1454
1455\subsection{\protect\lstinline|mutex| statement} \label{mutex-stmt}
1456
1457The 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}.
1458Table \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.
1459Beyond naming, the @mutex@ statement has no semantic difference from a routine call with @mutex@ parameters.
1460
1461\begin{table}
1462\begin{center}
1463\begin{tabular}{|c|c|}
1464function call & @mutex@ statement \\
1465\hline
1466\begin{cfa}[tabsize=3]
1467monitor M {};
1468void foo( M & mutex m1, M & mutex m2 ) {
1469        // critical section
1470}
1471
1472void bar( M & m1, M & m2 ) {
1473        foo( m1, m2 );
1474}
1475\end{cfa}&\begin{cfa}[tabsize=3]
1476monitor M {};
1477void bar( M & m1, M & m2 ) {
1478        mutex(m1, m2) {
1479                // critical section
1480        }
1481}
1482
1483
1484\end{cfa}
1485\end{tabular}
1486\end{center}
1487\caption{Regular call semantics vs. \protect\lstinline|mutex| statement}
1488\label{f:mutex-stmt}
1489\end{table}
1490
1491% ======================================================================
1492% ======================================================================
1493\subsection{Data semantics} \label{data}
1494% ======================================================================
1495% ======================================================================
1496Once the call semantics are established, the next step is to establish data semantics.
1497Indeed, until now a monitor is used simply as a generic handle but in most cases monitors contain shared data.
1498This data should be intrinsic to the monitor declaration to prevent any accidental use of data without its appropriate protection.
1499For example, here is a complete version of the counter shown in section \ref{call}:
1500\begin{cfa}
1501monitor counter_t {
1502        int value;
1503};
1504
1505void ?{}(counter_t & this) {
1506        this.cnt = 0;
1507}
1508
1509int ?++(counter_t & mutex this) {
1510        return ++this.value;
1511}
1512
1513// need for mutex is platform dependent here
1514void ?{}(int * this, counter_t & mutex cnt) {
1515        *this = (int)cnt;
1516}
1517\end{cfa}
1518
1519Like threads and coroutines, monitors are defined in terms of traits with some additional language support in the form of the @monitor@ keyword.
1520The monitor trait is:
1521\begin{cfa}
1522trait is_monitor(dtype T) {
1523        monitor_desc * get_monitor( T & );
1524        void ^?{}( T & mutex );
1525};
1526\end{cfa}
1527Note that the destructor of a monitor must be a @mutex@ routine to prevent deallocation while a thread is accessing the monitor.
1528As with any object, calls to a monitor, using @mutex@ or otherwise, is undefined behaviour after the destructor has run.
1529
1530% ======================================================================
1531% ======================================================================
1532\section{Internal Scheduling} \label{intsched}
1533% ======================================================================
1534% ======================================================================
1535In addition to mutual exclusion, the monitors at the core of \CFA's concurrency can also be used to achieve synchronization.
1536With monitors, this capability is generally achieved with internal or external scheduling as in~\cite{Hoare74}.
1537With \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).
1538Since internal scheduling within a single monitor is mostly a solved problem, this paper concentrates on extending internal scheduling to multiple monitors.
1539Indeed, 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.
1540
1541First, here is a simple example of internal scheduling:
1542
1543\begin{cfa}
1544monitor A {
1545        condition e;
1546}
1547
1548void foo(A& mutex a1, A& mutex a2) {
1549        ...
1550        // Wait for cooperation from bar()
1551        wait(a1.e);
1552        ...
1553}
1554
1555void bar(A& mutex a1, A& mutex a2) {
1556        // Provide cooperation for foo()
1557        ...
1558        // Unblock foo
1559        signal(a1.e);
1560}
1561\end{cfa}
1562There are two details to note here.
1563First, @signal@ is a delayed operation; it only unblocks the waiting thread when it reaches the end of the critical section.
1564This semantics is needed to respect mutual-exclusion, \ie the signaller and signalled thread cannot be in the monitor simultaneously.
1565The alternative is to return immediately after the call to @signal@, which is significantly more restrictive.
1566Second, 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.
1567Here routine @foo@ waits for the @signal@ from @bar@ before making further progress, ensuring a basic ordering.
1568
1569An 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).
1570This guarantee offers the benefit of not having to loop around waits to recheck that a condition is met.
1571The 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.
1572Supporting 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.
1573
1574% ======================================================================
1575% ======================================================================
1576\subsection{Internal Scheduling - Multi-Monitor}
1577% ======================================================================
1578% ======================================================================
1579It is easy to understand the problem of multi-monitor scheduling using a series of pseudo-code examples.
1580Note 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.
1581Indeed, @wait@ statements always use the implicit condition variable as parameters and explicitly name the monitors (A and B) associated with the condition.
1582Note 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.
1583The example below shows the simple case of having two threads (one for each column) and a single monitor A.
1584
1585\begin{multicols}{2}
1586thread 1
1587\begin{cfa}
1588acquire A
1589        wait A
1590release A
1591\end{cfa}
1592
1593\columnbreak
1594
1595thread 2
1596\begin{cfa}
1597acquire A
1598        signal A
1599release A
1600\end{cfa}
1601\end{multicols}
1602One thread acquires before waiting (atomically blocking and releasing A) and the other acquires before signalling.
1603It is important to note here that both @wait@ and @signal@ must be called with the proper monitor(s) already acquired.
1604This semantic is a logical requirement for barging prevention.
1605
1606A direct extension of the previous example is a \textbf{bulk-acq} version:
1607\begin{multicols}{2}
1608\begin{cfa}
1609acquire A & B
1610        wait A & B
1611release A & B
1612\end{cfa}
1613\columnbreak
1614\begin{cfa}
1615acquire A & B
1616        signal A & B
1617release A & B
1618\end{cfa}
1619\end{multicols}
1620\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.
1621Synchronization happens between the two threads in exactly the same way and order.
1622The only difference is that mutual exclusion covers a group of monitors.
1623On the implementation side, handling multiple monitors does add a degree of complexity as the next few examples demonstrate.
1624
1625While 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.
1626For 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.
1627For example, the following cfa-code runs into the nested-monitor problem:
1628\begin{multicols}{2}
1629\begin{cfa}
1630acquire A
1631        acquire B
1632                wait B
1633        release B
1634release A
1635\end{cfa}
1636
1637\columnbreak
1638
1639\begin{cfa}
1640acquire A
1641        acquire B
1642                signal B
1643        release B
1644release A
1645\end{cfa}
1646\end{multicols}
1647\noindent The @wait@ only releases monitor @B@ so the signalling thread cannot acquire monitor @A@ to get to the @signal@.
1648Attempting 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@.
1649
1650However, for monitors as for locks, it is possible to write a program using nesting without encountering any problems if nesting is done correctly.
1651For 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}.
1652
1653\begin{multicols}{2}
1654\begin{cfa}
1655acquire A
1656        acquire B
1657                wait B
1658        release B
1659release A
1660\end{cfa}
1661
1662\columnbreak
1663
1664\begin{cfa}
1665
1666acquire B
1667        signal B
1668release B
1669
1670\end{cfa}
1671\end{multicols}
1672
1673\noindent However, this simple refactoring may not be possible, forcing more complex restructuring.
1674
1675% ======================================================================
1676% ======================================================================
1677\subsection{Internal Scheduling - In Depth}
1678% ======================================================================
1679% ======================================================================
1680
1681A larger example is presented to show complex issues for \textbf{bulk-acq} and its implementation options are analyzed.
1682Figure~\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}.
1683For 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.
1684
1685\begin{figure}
1686\begin{multicols}{2}
1687Waiting thread
1688\begin{cfa}[numbers=left]
1689acquire A
1690        // Code Section 1
1691        acquire A & B
1692                // Code Section 2
1693                wait A & B
1694                // Code Section 3
1695        release A & B
1696        // Code Section 4
1697release A
1698\end{cfa}
1699\columnbreak
1700Signalling thread
1701\begin{cfa}[numbers=left, firstnumber=10,escapechar=|]
1702acquire A
1703        // Code Section 5
1704        acquire A & B
1705                // Code Section 6
1706                |\label{line:signal1}|signal A & B
1707                // Code Section 7
1708        |\label{line:releaseFirst}|release A & B
1709        // Code Section 8
1710|\label{line:lastRelease}|release A
1711\end{cfa}
1712\end{multicols}
1713\begin{cfa}[caption={Internal scheduling with \textbf{bulk-acq}},label={f:int-bulk-cfa}]
1714\end{cfa}
1715\begin{center}
1716\begin{cfa}[xleftmargin=.4\textwidth]
1717monitor A a;
1718monitor B b;
1719condition c;
1720\end{cfa}
1721\end{center}
1722\begin{multicols}{2}
1723Waiting thread
1724\begin{cfa}
1725mutex(a) {
1726        // Code Section 1
1727        mutex(a, b) {
1728                // Code Section 2
1729                wait(c);
1730                // Code Section 3
1731        }
1732        // Code Section 4
1733}
1734\end{cfa}
1735\columnbreak
1736Signalling thread
1737\begin{cfa}
1738mutex(a) {
1739        // Code Section 5
1740        mutex(a, b) {
1741                // Code Section 6
1742                signal(c);
1743                // Code Section 7
1744        }
1745        // Code Section 8
1746}
1747\end{cfa}
1748\end{multicols}
1749\begin{cfa}[caption={Equivalent \CFA code for listing \ref{f:int-bulk-cfa}},label={f:int-bulk-cfa}]
1750\end{cfa}
1751\begin{multicols}{2}
1752Waiter
1753\begin{cfa}[numbers=left]
1754acquire A
1755        acquire A & B
1756                wait A & B
1757        release A & B
1758release A
1759\end{cfa}
1760
1761\columnbreak
1762
1763Signaller
1764\begin{cfa}[numbers=left, firstnumber=6,escapechar=|]
1765acquire A
1766        acquire A & B
1767                signal A & B
1768        release A & B
1769        |\label{line:secret}|// Secretly keep B here
1770release A
1771// Wakeup waiter and transfer A & B
1772\end{cfa}
1773\end{multicols}
1774\begin{cfa}[caption={Figure~\ref{f:int-bulk-cfa}, with delayed signalling comments},label={f:int-secret}]
1775\end{cfa}
1776\end{figure}
1777
1778The 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.
1779The 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.
1780When 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.
1781This 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@.
1782There are three options:
1783
1784\subsubsection{Delaying Signals}
1785The 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.
1786It 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.
1787This 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.
1788This solution releases the monitors once every monitor in a group can be released.
1789However, since some monitors are never released (\eg the monitor of a thread), this interpretation means a group might never be released.
1790A 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.
1791
1792However, 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.
1793Figure~\ref{f:dependency} shows a slightly different example where a third thread is waiting on monitor @A@, using a different condition variable.
1794Because the third thread is signalled when secretly holding @B@, the goal  becomes unreachable.
1795Depending on the order of signals (listing \ref{f:dependency} line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen:
1796
1797\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.
1798\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.
1799\\
1800
1801Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order.
1802However, 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}.
1803
1804In 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.
1805
1806\subsubsection{Dependency graphs}
1807
1808
1809\begin{figure}
1810\begin{multicols}{3}
1811Thread $\alpha$
1812\begin{cfa}[numbers=left, firstnumber=1]
1813acquire A
1814        acquire A & B
1815                wait A & B
1816        release A & B
1817release A
1818\end{cfa}
1819\columnbreak
1820Thread $\gamma$
1821\begin{cfa}[numbers=left, firstnumber=6, escapechar=|]
1822acquire A
1823        acquire A & B
1824                |\label{line:signal-ab}|signal A & B
1825        |\label{line:release-ab}|release A & B
1826        |\label{line:signal-a}|signal A
1827|\label{line:release-a}|release A
1828\end{cfa}
1829\columnbreak
1830Thread $\beta$
1831\begin{cfa}[numbers=left, firstnumber=12, escapechar=|]
1832acquire A
1833        wait A
1834|\label{line:release-aa}|release A
1835\end{cfa}
1836\end{multicols}
1837\begin{cfa}[caption={Pseudo-code for the three thread example.},label={f:dependency}]
1838\end{cfa}
1839\begin{center}
1840\input{dependency}
1841\end{center}
1842\caption{Dependency graph of the statements in listing \ref{f:dependency}}
1843\label{fig:dependency}
1844\end{figure}
1845
1846In listing \ref{f:int-bulk-cfa}, there is a solution that satisfies both barging prevention and mutual exclusion.
1847If 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).
1848Dynamically finding the correct order is therefore the second possible solution.
1849The problem is effectively resolving a dependency graph of ownership requirements.
1850Here even the simplest of code snippets requires two transfers and has a super-linear complexity.
1851This 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.
1852Furthermore, 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.
1853\begin{figure}
1854\begin{multicols}{2}
1855\begin{cfa}
1856acquire A
1857        acquire B
1858                acquire C
1859                        wait A & B & C
1860                release C
1861        release B
1862release A
1863\end{cfa}
1864
1865\columnbreak
1866
1867\begin{cfa}
1868acquire A
1869        acquire B
1870                acquire C
1871                        signal A & B & C
1872                release C
1873        release B
1874release A
1875\end{cfa}
1876\end{multicols}
1877\begin{cfa}[caption={Extension to three monitors of listing \ref{f:int-bulk-cfa}},label={f:explosion}]
1878\end{cfa}
1879\end{figure}
1880
1881Given 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$).
1882The 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.
1883Resolving dependency graphs being a complex and expensive endeavour, this solution is not the preferred one.
1884
1885\subsubsection{Partial Signalling} \label{partial-sig}
1886Finally, the solution that is chosen for \CFA is to use partial signalling.
1887Again 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@.
1888Only when it reaches line \ref{line:lastRelease} does it actually wake up the waiting thread.
1889This 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.
1890This solution has a much simpler implementation than a dependency graph solving algorithms, which is why it was chosen.
1891Furthermore, after being fully implemented, this solution does not appear to have any significant downsides.
1892
1893Using partial signalling, listing \ref{f:dependency} can be solved easily:
1894\begin{itemize}
1895        \item When thread $\gamma$ reaches line \ref{line:release-ab} it transfers monitor @B@ to thread $\alpha$ and continues to hold monitor @A@.
1896        \item When thread $\gamma$ reaches line \ref{line:release-a}  it transfers monitor @A@ to thread $\beta$  and wakes it up.
1897        \item When thread $\beta$  reaches line \ref{line:release-aa} it transfers monitor @A@ to thread $\alpha$ and wakes it up.
1898\end{itemize}
1899
1900% ======================================================================
1901% ======================================================================
1902\subsection{Signalling: Now or Later}
1903% ======================================================================
1904% ======================================================================
1905\begin{table}
1906\begin{tabular}{|c|c|}
1907@signal@ & @signal_block@ \\
1908\hline
1909\begin{cfa}[tabsize=3]
1910monitor DatingService {
1911        // compatibility codes
1912        enum{ CCodes = 20 };
1913
1914        int girlPhoneNo
1915        int boyPhoneNo;
1916};
1917
1918condition girls[CCodes];
1919condition boys [CCodes];
1920condition exchange;
1921
1922int girl(int phoneNo, int cfa) {
1923        // no compatible boy ?
1924        if(empty(boys[cfa])) {
1925                wait(girls[cfa]);               // wait for boy
1926                girlPhoneNo = phoneNo;          // make phone number available
1927                signal(exchange);               // wake boy from chair
1928        } else {
1929                girlPhoneNo = phoneNo;          // make phone number available
1930                signal(boys[cfa]);              // wake boy
1931                wait(exchange);         // sit in chair
1932        }
1933        return boyPhoneNo;
1934}
1935int boy(int phoneNo, int cfa) {
1936        // same as above
1937        // with boy/girl interchanged
1938}
1939\end{cfa}&\begin{cfa}[tabsize=3]
1940monitor DatingService {
1941
1942        enum{ CCodes = 20 };    // compatibility codes
1943
1944        int girlPhoneNo;
1945        int boyPhoneNo;
1946};
1947
1948condition girls[CCodes];
1949condition boys [CCodes];
1950// exchange is not needed
1951
1952int girl(int phoneNo, int cfa) {
1953        // no compatible boy ?
1954        if(empty(boys[cfa])) {
1955                wait(girls[cfa]);               // wait for boy
1956                girlPhoneNo = phoneNo;          // make phone number available
1957                signal(exchange);               // wake boy from chair
1958        } else {
1959                girlPhoneNo = phoneNo;          // make phone number available
1960                signal_block(boys[cfa]);                // wake boy
1961
1962                // second handshake unnecessary
1963
1964        }
1965        return boyPhoneNo;
1966}
1967
1968int boy(int phoneNo, int cfa) {
1969        // same as above
1970        // with boy/girl interchanged
1971}
1972\end{cfa}
1973\end{tabular}
1974\caption{Dating service example using \protect\lstinline|signal| and \protect\lstinline|signal_block|. }
1975\label{tbl:datingservice}
1976\end{table}
1977An important note is that, until now, signalling a monitor was a delayed operation.
1978The ownership of the monitor is transferred only when the monitor would have otherwise been released, not at the point of the @signal@ statement.
1979However, 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.
1980
1981The example in table \ref{tbl:datingservice} highlights the difference in behaviour.
1982As mentioned, @signal@ only transfers ownership once the current critical section exits; this behaviour requires additional synchronization when a two-way handshake is needed.
1983To avoid this explicit synchronization, the @condition@ type offers the @signal_block@ routine, which handles the two-way handshake as shown in the example.
1984This feature removes the need for a second condition variables and simplifies programming.
1985Like 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.
1986
1987% ======================================================================
1988% ======================================================================
1989\section{External scheduling} \label{extsched}
1990% ======================================================================
1991% ======================================================================
1992An alternative to internal scheduling is external scheduling (see Table~\ref{tbl:sched}).
1993\begin{table}
1994\begin{tabular}{|c|c|c|}
1995Internal Scheduling & External Scheduling & Go\\
1996\hline
1997\begin{uC++}[tabsize=3]
1998_Monitor Semaphore {
1999        condition c;
2000        bool inUse;
2001public:
2002        void P() {
2003                if(inUse)
2004                        wait(c);
2005                inUse = true;
2006        }
2007        void V() {
2008                inUse = false;
2009                signal(c);
2010        }
2011}
2012\end{uC++}&\begin{uC++}[tabsize=3]
2013_Monitor Semaphore {
2014
2015        bool inUse;
2016public:
2017        void P() {
2018                if(inUse)
2019                        _Accept(V);
2020                inUse = true;
2021        }
2022        void V() {
2023                inUse = false;
2024
2025        }
2026}
2027\end{uC++}&\begin{Go}[tabsize=3]
2028type MySem struct {
2029        inUse bool
2030        c     chan bool
2031}
2032
2033// acquire
2034func (s MySem) P() {
2035        if s.inUse {
2036                select {
2037                case <-s.c:
2038                }
2039        }
2040        s.inUse = true
2041}
2042
2043// release
2044func (s MySem) V() {
2045        s.inUse = false
2046
2047        // This actually deadlocks
2048        // when single thread
2049        s.c <- false
2050}
2051\end{Go}
2052\end{tabular}
2053\caption{Different forms of scheduling.}
2054\label{tbl:sched}
2055\end{table}
2056This method is more constrained and explicit, which helps users reduce the non-deterministic nature of concurrency.
2057Indeed, as the following examples demonstrate, external scheduling allows users to wait for events from other threads without the concern of unrelated events occurring.
2058External 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).
2059Of 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.
2060Two challenges specific to \CFA arise when trying to add external scheduling with loose object definitions and multiple-monitor routines.
2061The previous example shows a simple use @_Accept@ versus @wait@/@signal@ and its advantages.
2062Note 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.
2063
2064For 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.
2065On the other hand, external scheduling guarantees that while routine @P@ is waiting, no other routine than @V@ can acquire the monitor.
2066
2067% ======================================================================
2068% ======================================================================
2069\subsection{Loose Object Definitions}
2070% ======================================================================
2071% ======================================================================
2072In \uC, a monitor class declaration includes an exhaustive list of monitor operations.
2073Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user:
2074
2075\begin{cfa}
2076monitor A {};
2077
2078void f(A & mutex a);
2079void g(A & mutex a) {
2080        waitfor(f); // Obvious which f() to wait for
2081}
2082
2083void f(A & mutex a, int); // New different F added in scope
2084void h(A & mutex a) {
2085        waitfor(f); // Less obvious which f() to wait for
2086}
2087\end{cfa}
2088
2089Furthermore, external scheduling is an example where implementation constraints become visible from the interface.
2090Here is the cfa-code for the entering phase of a monitor:
2091\begin{center}
2092\begin{tabular}{l}
2093\begin{cfa}
2094        if monitor is free
2095                enter
2096        elif already own the monitor
2097                continue
2098        elif monitor accepts me
2099                enter
2100        else
2101                block
2102\end{cfa}
2103\end{tabular}
2104\end{center}
2105For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions.
2106However, a fast check for @monitor accepts me@ is much harder to implement depending on the constraints put on the monitors.
2107Indeed, monitors are often expressed as an entry queue and some acceptor queue as in Figure~\ref{fig:ClassicalMonitor}.
2108
2109\begin{figure}
2110\centering
2111\subfloat[Classical Monitor] {
2112\label{fig:ClassicalMonitor}
2113{\resizebox{0.45\textwidth}{!}{\input{monitor}}}
2114}% subfloat
2115\qquad
2116\subfloat[\textbf{bulk-acq} Monitor] {
2117\label{fig:BulkMonitor}
2118{\resizebox{0.45\textwidth}{!}{\input{ext_monitor}}}
2119}% subfloat
2120\caption{External Scheduling Monitor}
2121\end{figure}
2122
2123There are other alternatives to these pictures, but in the case of the left picture, implementing a fast accept check is relatively easy.
2124Restricted 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.
2125This approach requires a unique dense ordering of routines with an upper-bound and that ordering must be consistent across translation units.
2126For OO languages these constraints are common, since objects only offer adding member routines consistently across translation units via inheritance.
2127However, in \CFA users can extend objects with mutex routines that are only visible in certain translation unit.
2128This 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.
2129
2130The alternative is to alter the implementation as in Figure~\ref{fig:BulkMonitor}.
2131Here, the mutex routine called is associated with a thread on the entry queue while a list of acceptable routines is kept separate.
2132Generating a mask dynamically means that the storage for the mask information can vary between calls to @waitfor@, allowing for more flexibility and extensions.
2133Storing an array of accepted function pointers replaces the single instruction bitmask comparison with dereferencing a pointer followed by a linear search.
2134Furthermore, 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.
2135
2136\begin{figure}
2137\begin{cfa}[caption={Example of nested external scheduling},label={f:nest-ext}]
2138monitor M {};
2139void foo( M & mutex a ) {}
2140void bar( M & mutex b ) {
2141        // Nested in the waitfor(bar, c) call
2142        waitfor(foo, b);
2143}
2144void baz( M & mutex c ) {
2145        waitfor(bar, c);
2146}
2147
2148\end{cfa}
2149\end{figure}
2150
2151Note 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.
2152These details are omitted from the picture for the sake of simplicity.
2153
2154At this point, a decision must be made between flexibility and performance.
2155Many 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.
2156Here, however, the cost of flexibility cannot be trivially removed.
2157In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be  hard to write.
2158This 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.
2159
2160% ======================================================================
2161% ======================================================================
2162\subsection{Multi-Monitor Scheduling}
2163% ======================================================================
2164% ======================================================================
2165
2166External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax.
2167Even in the simplest possible case, some new semantics needs to be established:
2168\begin{cfa}
2169monitor M {};
2170
2171void f(M & mutex a);
2172
2173void g(M & mutex b, M & mutex c) {
2174        waitfor(f); // two monitors M => unknown which to pass to f(M & mutex)
2175}
2176\end{cfa}
2177The obvious solution is to specify the correct monitor as follows:
2178
2179\begin{cfa}
2180monitor M {};
2181
2182void f(M & mutex a);
2183
2184void g(M & mutex a, M & mutex b) {
2185        // wait for call to f with argument b
2186        waitfor(f, b);
2187}
2188\end{cfa}
2189This syntax is unambiguous.
2190Both locks are acquired and kept by @g@.
2191When routine @f@ is called, the lock for monitor @b@ is temporarily transferred from @g@ to @f@ (while @g@ still holds lock @a@).
2192This behaviour can be extended to the multi-monitor @waitfor@ statement as follows.
2193
2194\begin{cfa}
2195monitor M {};
2196
2197void f(M & mutex a, M & mutex b);
2198
2199void g(M & mutex a, M & mutex b) {
2200        // wait for call to f with arguments a and b
2201        waitfor(f, a, b);
2202}
2203\end{cfa}
2204
2205Note 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.
2206
2207An important behaviour to note is when a set of monitors only match partially:
2208
2209\begin{cfa}
2210mutex struct A {};
2211
2212mutex struct B {};
2213
2214void g(A & mutex a, B & mutex b) {
2215        waitfor(f, a, b);
2216}
2217
2218A a1, a2;
2219B b;
2220
2221void foo() {
2222        g(a1, b); // block on accept
2223}
2224
2225void bar() {
2226        f(a2, b); // fulfill cooperation
2227}
2228\end{cfa}
2229While 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.
2230In both cases, partially matching monitor sets does not wakeup the waiting thread.
2231It 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.
2232
2233% ======================================================================
2234% ======================================================================
2235\subsection{\protect\lstinline|waitfor| Semantics}
2236% ======================================================================
2237% ======================================================================
2238
2239Syntactically, the @waitfor@ statement takes a function identifier and a set of monitors.
2240While 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.
2241It checks that the set of monitors passed in matches the requirements for a function call.
2242Figure~\ref{f:waitfor} shows various usages of the waitfor statement and which are acceptable.
2243The choice of the function type is made ignoring any non-@mutex@ parameter.
2244One limitation of the current implementation is that it does not handle overloading, but overloading is possible.
2245\begin{figure}
2246\begin{cfa}[caption={Various correct and incorrect uses of the waitfor statement},label={f:waitfor}]
2247monitor A{};
2248monitor B{};
2249
2250void f1( A & mutex );
2251void f2( A & mutex, B & mutex );
2252void f3( A & mutex, int );
2253void f4( A & mutex, int );
2254void f4( A & mutex, double );
2255
2256void foo( A & mutex a1, A & mutex a2, B & mutex b1, B & b2 ) {
2257        A * ap = & a1;
2258        void (*fp)( A & mutex ) = f1;
2259
2260        waitfor(f1, a1);     // Correct : 1 monitor case
2261        waitfor(f2, a1, b1); // Correct : 2 monitor case
2262        waitfor(f3, a1);     // Correct : non-mutex arguments are ignored
2263        waitfor(f1, *ap);    // Correct : expression as argument
2264
2265        waitfor(f1, a1, b1); // Incorrect : Too many mutex arguments
2266        waitfor(f2, a1);     // Incorrect : Too few mutex arguments
2267        waitfor(f2, a1, a2); // Incorrect : Mutex arguments don't match
2268        waitfor(f1, 1);      // Incorrect : 1 not a mutex argument
2269        waitfor(f9, a1);     // Incorrect : f9 function does not exist
2270        waitfor(*fp, a1 );   // Incorrect : fp not an identifier
2271        waitfor(f4, a1);     // Incorrect : f4 ambiguous
2272
2273        waitfor(f2, a1, b2); // Undefined behaviour : b2 not mutex
2274}
2275\end{cfa}
2276\end{figure}
2277
2278Finally, for added flexibility, \CFA supports constructing a complex @waitfor@ statement using the @or@, @timeout@ and @else@.
2279Indeed, 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.
2280To 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.
2281A @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.
2282Any 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.
2283Figure~\ref{f:waitfor2} demonstrates several complex masks and some incorrect ones.
2284
2285\begin{figure}
2286\lstset{language=CFA,deletedelim=**[is][]{`}{`}}
2287\begin{cfa}
2288monitor A{};
2289
2290void f1( A & mutex );
2291void f2( A & mutex );
2292
2293void foo( A & mutex a, bool b, int t ) {
2294        waitfor(f1, a);                                                 $\C{// Correct : blocking case}$
2295
2296        waitfor(f1, a) {                                                $\C{// Correct : block with statement}$
2297                sout | "f1" | endl;
2298        }
2299        waitfor(f1, a) {                                                $\C{// Correct : block waiting for f1 or f2}$
2300                sout | "f1" | endl;
2301        } or waitfor(f2, a) {
2302                sout | "f2" | endl;
2303        }
2304        waitfor(f1, a); or else;                                $\C{// Correct : non-blocking case}$
2305
2306        waitfor(f1, a) {                                                $\C{// Correct : non-blocking case}$
2307                sout | "blocked" | endl;
2308        } or else {
2309                sout | "didn't block" | endl;
2310        }
2311        waitfor(f1, a) {                                                $\C{// Correct : block at most 10 seconds}$
2312                sout | "blocked" | endl;
2313        } or timeout( 10`s) {
2314                sout | "didn't block" | endl;
2315        }
2316        // Correct : block only if b == true if b == false, don't even make the call
2317        when(b) waitfor(f1, a);
2318
2319        // Correct : block only if b == true if b == false, make non-blocking call
2320        waitfor(f1, a); or when(!b) else;
2321
2322        // Correct : block only of t > 1
2323        waitfor(f1, a); or when(t > 1) timeout(t); or else;
2324
2325        // Incorrect : timeout clause is dead code
2326        waitfor(f1, a); or timeout(t); or else;
2327
2328        // Incorrect : order must be waitfor [or waitfor... [or timeout] [or else]]
2329        timeout(t); or waitfor(f1, a); or else;
2330}
2331\end{cfa}
2332\caption{Correct and incorrect uses of the or, else, and timeout clause around a waitfor statement}
2333\label{f:waitfor2}
2334\end{figure}
2335
2336% ======================================================================
2337% ======================================================================
2338\subsection{Waiting For The Destructor}
2339% ======================================================================
2340% ======================================================================
2341An interesting use for the @waitfor@ statement is destructor semantics.
2342Indeed, the @waitfor@ statement can accept any @mutex@ routine, which includes the destructor (see section \ref{data}).
2343However, 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.
2344The simplest approach is to disallow @waitfor@ on a destructor.
2345However, 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.
2346\begin{figure}
2347\begin{cfa}[caption={Example of an executor which executes action in series until the destructor is called.},label={f:dtor-order}]
2348monitor Executer {};
2349struct  Action;
2350
2351void ^?{}   (Executer & mutex this);
2352void execute(Executer & mutex this, const Action & );
2353void run    (Executer & mutex this) {
2354        while(true) {
2355                   waitfor(execute, this);
2356                or waitfor(^?{}   , this) {
2357                        break;
2358                }
2359        }
2360}
2361\end{cfa}
2362\end{figure}
2363For 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.
2364Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction.
2365
2366
2367% ######     #    ######     #    #       #       ####### #       ###  #####  #     #
2368% #     #   # #   #     #   # #   #       #       #       #        #  #     # ##   ##
2369% #     #  #   #  #     #  #   #  #       #       #       #        #  #       # # # #
2370% ######  #     # ######  #     # #       #       #####   #        #   #####  #  #  #
2371% #       ####### #   #   ####### #       #       #       #        #        # #     #
2372% #       #     # #    #  #     # #       #       #       #        #  #     # #     #
2373% #       #     # #     # #     # ####### ####### ####### ####### ###  #####  #     #
2374\section{Parallelism}
2375Historically, computer performance was about processor speeds and instruction counts.
2376However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}.
2377In this decade, it is no longer reasonable to create a high-performance application without caring about parallelism.
2378Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization.
2379The lowest-level approach of parallelism is to use \textbf{kthread} in combination with semantics like @fork@, @join@, \etc.
2380However, since these have significant costs and limitations, \textbf{kthread} are now mostly used as an implementation tool rather than a user oriented one.
2381There are several alternatives to solve these issues that all have strengths and weaknesses.
2382While 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.
2383
2384\section{Paradigms}
2385\subsection{User-Level Threads}
2386A direct improvement on the \textbf{kthread} approach is to use \textbf{uthread}.
2387These threads offer most of the same features that the operating system already provides but can be used on a much larger scale.
2388This 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.
2389The 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.
2390These issues can be somewhat alleviated by a concurrency toolkit with strong guarantees, but the parallelism toolkit offers very little to reduce complexity in itself.
2391
2392Examples of languages that support \textbf{uthread} are Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
2393
2394\subsection{Fibers : User-Level Threads Without Preemption} \label{fibers}
2395A popular variant of \textbf{uthread} is what is often referred to as \textbf{fiber}.
2396However, \textbf{fiber} do not present meaningful semantic differences with \textbf{uthread}.
2397The significant difference between \textbf{uthread} and \textbf{fiber} is the lack of \textbf{preemption} in the latter.
2398Advocates 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.
2399Therefore this proposal largely ignores fibers.
2400
2401An example of a language that uses fibers is Go~\cite{Go}
2402
2403\subsection{Jobs and Thread Pools}
2404An approach on the opposite end of the spectrum is to base parallelism on \textbf{pool}.
2405Indeed, \textbf{pool} offer limited flexibility but at the benefit of a simpler user interface.
2406In \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.
2407This approach means users need not worry about concurrency but significantly limit the interaction that can occur among jobs.
2408Indeed, any \textbf{job} that blocks also block the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably.
2409It can be argued that a solution to this problem is to use more workers than available cores.
2410However, unless the number of jobs and the number of workers are comparable, having a significant number of blocked jobs always results in idles cores.
2411
2412The gold standard of this implementation is Intel's TBB library~\cite{TBB}.
2413
2414\subsection{Paradigm Performance}
2415While 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.
2416Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload.
2417Having 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).
2418However, interactions among jobs can easily exacerbate contention.
2419User-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.
2420Finally, if the units of uninterrupted work are large, enough the paradigm choice is largely amortized by the actual work done.
2421
2422\section{The \protect\CFA\ Kernel : Processors, Clusters and Threads}\label{kernel}
2423A \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}.
2424It 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.
2425A \textbf{cfacluster} also offers a pluggable scheduler that can optimize the workload generated by the \textbf{uthread}.
2426
2427\textbf{cfacluster} have not been fully implemented in the context of this paper.
2428Currently \CFA only supports one \textbf{cfacluster}, the initial one.
2429
2430\subsection{Future Work: Machine Setup}\label{machine}
2431While this was not done in the context of this paper, another important aspect of clusters is affinity.
2432While many common desktop and laptop PCs have homogeneous CPUs, other devices often have more heterogeneous setups.
2433For example, a system using \textbf{numa} configurations may benefit from users being able to tie clusters and/or kernel threads to certain CPU cores.
2434OS 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.
2435
2436\subsection{Paradigms}\label{cfaparadigms}
2437Given these building blocks, it is possible to reproduce all three of the popular paradigms.
2438Indeed, \textbf{uthread} is the default paradigm in \CFA.
2439However, disabling \textbf{preemption} on a cluster means threads effectively become fibers.
2440Since 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.
2441Finally, it is possible to build executors for thread pools from \textbf{uthread} or \textbf{fiber}, which includes specialized jobs like actors~\cite{Actors}.
2442
2443
2444
2445\section{Behind the Scenes}
2446There are several challenges specific to \CFA when implementing concurrency.
2447These challenges are a direct result of \textbf{bulk-acq} and loose object definitions.
2448These two constraints are the root cause of most design decisions in the implementation.
2449Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs.
2450This 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.
2451This extra goal means that memory management is a constant concern in the design of the system.
2452
2453The main memory concern for concurrency is queues.
2454All 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.
2455Since 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.
2456Conveniently, 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.
2457Since 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.
2458The 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.
2459
2460Note 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.
2461
2462% ======================================================================
2463% ======================================================================
2464\section{Mutex Routines}
2465% ======================================================================
2466% ======================================================================
2467
2468The first step towards the monitor implementation is simple @mutex@ routines.
2469In the single monitor case, mutual-exclusion is done using the entry/exit procedure in listing \ref{f:entry1}.
2470The entry/exit procedures do not have to be extended to support multiple monitors.
2471Indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlock~\cite{Havender68}.
2472In \CFA, ordering of monitor acquisition relies on memory ordering.
2473This 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.
2474When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer array and sorted based on pointer values.
2475This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively.
2476\begin{figure}
2477\begin{multicols}{2}
2478Entry
2479\begin{cfa}
2480if monitor is free
2481        enter
2482elif already own the monitor
2483        continue
2484else
2485        block
2486increment recursions
2487\end{cfa}
2488\columnbreak
2489Exit
2490\begin{cfa}
2491decrement recursion
2492if recursion == 0
2493        if entry queue not empty
2494                wake-up thread
2495\end{cfa}
2496\end{multicols}
2497\begin{cfa}[caption={Initial entry and exit routine for monitors},label={f:entry1}]
2498\end{cfa}
2499\end{figure}
2500
2501\subsection{Details: Interaction with polymorphism}
2502Depending 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.
2503However, it is shown that entry-point locking solves most of the issues.
2504
2505First of all, interaction between @otype@ polymorphism (see Section~\ref{s:ParametricPolymorphism}) and monitors is impossible since monitors do not support copying.
2506Therefore, the main question is how to support @dtype@ polymorphism.
2507It 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.
2508For example:
2509\begin{table}
2510\begin{center}
2511\begin{tabular}{|c|c|c|}
2512Mutex & \textbf{callsite-locking} & \textbf{entry-point-locking} \\
2513call & cfa-code & cfa-code \\
2514\hline
2515\begin{cfa}[tabsize=3]
2516void foo(monitor& mutex a){
2517
2518        // Do Work
2519        //...
2520
2521}
2522
2523void main() {
2524        monitor a;
2525
2526        foo(a);
2527
2528}
2529\end{cfa} & \begin{cfa}[tabsize=3]
2530foo(& a) {
2531
2532        // Do Work
2533        //...
2534
2535}
2536
2537main() {
2538        monitor a;
2539        acquire(a);
2540        foo(a);
2541        release(a);
2542}
2543\end{cfa} & \begin{cfa}[tabsize=3]
2544foo(& a) {
2545        acquire(a);
2546        // Do Work
2547        //...
2548        release(a);
2549}
2550
2551main() {
2552        monitor a;
2553
2554        foo(a);
2555
2556}
2557\end{cfa}
2558\end{tabular}
2559\end{center}
2560\caption{Call-site vs entry-point locking for mutex calls}
2561\label{tbl:locking-site}
2562\end{table}
2563
2564Note 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:
2565\begin{cfa}
2566// Incorrect: T may not be monitor
2567forall(dtype T)
2568void foo(T * mutex t);
2569
2570// Correct: this function only works on monitors (any monitor)
2571forall(dtype T | is_monitor(T))
2572void bar(T * mutex t));
2573\end{cfa}
2574
2575Both entry point and \textbf{callsite-locking} are feasible implementations.
2576The 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.
2577It 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.
2578For example, the monitor call can appear in the middle of an expression.
2579Furthermore, 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.
2580
2581% ======================================================================
2582% ======================================================================
2583\section{Threading} \label{impl:thread}
2584% ======================================================================
2585% ======================================================================
2586
2587Figure \ref{fig:system1} shows a high-level picture if the \CFA runtime system in regards to concurrency.
2588Each component of the picture is explained in detail in the flowing sections.
2589
2590\begin{figure}
2591\begin{center}
2592{\resizebox{\textwidth}{!}{\input{system.pstex_t}}}
2593\end{center}
2594\caption{Overview of the entire system}
2595\label{fig:system1}
2596\end{figure}
2597
2598\subsection{Processors}
2599Parallelism 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.
2600Indeed, any parallelism must go through operating-system libraries.
2601However, \textbf{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism.
2602Indeed, processor \textbf{kthread} simply fetch a \textbf{uthread} from the scheduler and run it; they are effectively executers for user-threads.
2603The 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.
2604Processors internally use coroutines to take advantage of the existing context-switching semantics.
2605
2606\subsection{Stack Management}
2607One of the challenges of this system is to reduce the footprint as much as possible.
2608Specifically, all @pthread@s created also have a stack created with them, which should be used as much as possible.
2609Normally, 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.
2610The exception to this rule is the Main Processor, \ie the initial \textbf{kthread} that is given to any program.
2611In 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.
2612
2613\subsection{Context Switching}
2614As 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.
2615To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific function call.
2616This 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.
2617Note that the instruction pointer can be left untouched since the context-switch is always inside the same function.
2618Threads, however, do not context-switch between each other directly.
2619They context-switch to the scheduler.
2620This 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.
2621Obviously, this doubles the context-switch cost because threads must context-switch to an intermediate stack.
2622The alternative 1-step context-switch uses the stack of the ``from'' thread to schedule and then context-switches directly to the ``to'' thread.
2623However, the performance of the 2-step context-switch is still superior to a @pthread_yield@ (see section \ref{results}).
2624Additionally, 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).
2625This option is not currently present in \CFA, but the changes required to add it are strictly additive.
2626
2627\subsection{Preemption} \label{preemption}
2628Finally, an important aspect for any complete threading system is preemption.
2629As 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.
2630Indeed, preemption is desirable because it adds a degree of isolation among threads.
2631In 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.
2632Obviously, preemption is not optimal for every workload.
2633However any preemptive system can become a cooperative system by making the time slices extremely large.
2634Therefore, \CFA uses a preemptive threading system.
2635
2636Preemption in \CFA\footnote{Note that the implementation of preemption is strongly tied with the underlying threading system.
2637For 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.
2638Every processor keeps track of the current time and registers an expiration time with the preemption system.
2639When 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.
2640These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread.
2641This 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:
2642\begin{quote}
2643A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
2644If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
2645SIGNAL(7) - Linux Programmer's Manual
2646\end{quote}
2647For 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.
2648
2649Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread.
2650Hence, 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.
2651This 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.
2652As a result, a signal handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread).
2653It 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.
2654This 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.}.
2655However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel-alarm thread can cause deadlocks.
2656For this reason, the alarm thread is in a tight loop around a system call to @sigwaitinfo@, requiring very little CPU time for preemption.
2657One final detail about the alarm thread is how to wake it when additional communication is required (\eg on thread termination).
2658This unblocking is also done using {\tt SIGALRM}, but sent through the @pthread_sigqueue@.
2659Indeed, @sigwait@ can differentiate signals sent from @pthread_sigqueue@ from signals sent from alarms or the kernel.
2660
2661\subsection{Scheduler}
2662Finally, an aspect that was not mentioned yet is the scheduling algorithm.
2663Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling.
2664Further discussion on scheduling is present in section \ref{futur:sched}.
2665
2666% ======================================================================
2667% ======================================================================
2668\section{Internal Scheduling} \label{impl:intsched}
2669% ======================================================================
2670% ======================================================================
2671The following figure is the traditional illustration of a monitor (repeated from page~\pageref{fig:ClassicalMonitor} for convenience):
2672
2673\begin{figure}
2674\begin{center}
2675{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
2676\end{center}
2677\caption{Traditional illustration of a monitor}
2678\end{figure}
2679
2680This picture has several components, the two most important being the entry queue and the AS-stack.
2681The 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.
2682
2683For \CFA, this picture does not have support for blocking multiple monitors on a single condition.
2684To support \textbf{bulk-acq} two changes to this picture are required.
2685First, it is no longer helpful to attach the condition to \emph{a single} monitor.
2686Secondly, the thread waiting on the condition has to be separated across multiple monitors, seen in figure \ref{fig:monitor_cfa}.
2687
2688\begin{figure}
2689\begin{center}
2690{\resizebox{0.8\textwidth}{!}{\input{int_monitor}}}
2691\end{center}
2692\caption{Illustration of \CFA Monitor}
2693\label{fig:monitor_cfa}
2694\end{figure}
2695
2696This picture and the proper entry and leave algorithms (see listing \ref{f:entry2}) is the fundamental implementation of internal scheduling.
2697Note 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.
2698The thread is woken up when all the pieces have popped from the AS-stacks and made active.
2699In this picture, the threads are split into halves but this is only because there are two monitors.
2700For a specific signalling operation every monitor needs a piece of thread on its AS-stack.
2701
2702\begin{figure}
2703\begin{multicols}{2}
2704Entry
2705\begin{cfa}
2706if monitor is free
2707        enter
2708elif already own the monitor
2709        continue
2710else
2711        block
2712increment recursion
2713
2714\end{cfa}
2715\columnbreak
2716Exit
2717\begin{cfa}
2718decrement recursion
2719if recursion == 0
2720        if signal_stack not empty
2721                set_owner to thread
2722                if all monitors ready
2723                        wake-up thread
2724
2725        if entry queue not empty
2726                wake-up thread
2727\end{cfa}
2728\end{multicols}
2729\begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling},label={f:entry2}]
2730\end{cfa}
2731\end{figure}
2732
2733The solution discussed in \ref{intsched} can be seen in the exit routine of listing \ref{f:entry2}.
2734Basically, 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.
2735This solution is deadlock safe as well as preventing any potential barging.
2736The 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.
2737
2738\begin{figure}
2739\begin{center}
2740{\resizebox{0.8\textwidth}{!}{\input{monitor_structs.pstex_t}}}
2741\end{center}
2742\caption{Data structures involved in internal/external scheduling}
2743\label{fig:structs}
2744\end{figure}
2745
2746Figure \ref{fig:structs} shows a high-level representation of these data structures.
2747The main idea behind them is that, a thread cannot contain an arbitrary number of intrusive ``next'' pointers for linking onto monitors.
2748The @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.
2749Once 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}.
2750
2751% ======================================================================
2752% ======================================================================
2753\section{External Scheduling}
2754% ======================================================================
2755% ======================================================================
2756Similarly 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}.
2757For 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).
2758However, in the case of external scheduling, there is no equivalent object which is associated with @waitfor@ statements.
2759This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired.
2760These monitors being the only objects that have sufficient lifetime and are available on both sides of the @waitfor@ statement.
2761This requires an algorithm to choose which monitor holds the relevant queue.
2762It is also important that said algorithm be independent of the order in which users list parameters.
2763The 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.
2764This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint.
2765
2766This algorithm choice has two consequences:
2767\begin{itemize}
2768        \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.
2769These queues need to contain a set of monitors for each of the waiting threads.
2770Therefore, 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.
2771        \item The queue of the lowest priority monitor is both required and potentially unused.
2772Indeed, 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.
2773\end{itemize}
2774Therefore, the following modifications need to be made to support external scheduling:
2775\begin{itemize}
2776        \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.
2777The @mutex@ routine already has all the required information on its stack, so the thread only needs to keep a pointer to that information.
2778        \item The monitors need to keep a mask of acceptable routines.
2779This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it.
2780It also needs storage to keep track of which routine was accepted.
2781Since this information is not specific to any monitor, the monitors actually contain a pointer to an integer on the stack of the waiting thread.
2782Note 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.
2783This becomes relevant when @when@ clauses affect the number of monitors passed to a @waitfor@ statement.
2784        \item The entry/exit routines need to be updated as shown in listing \ref{f:entry3}.
2785\end{itemize}
2786
2787\subsection{External Scheduling - Destructors}
2788Finally, to support the ordering inversion of destructors, the code generation needs to be modified to use a special entry routine.
2789This routine is needed because of the storage requirements of the call order inversion.
2790Indeed, 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.
2791For 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.
2792The @waitfor@ semantics can then be adjusted correspondingly, as seen in listing \ref{f:entry-dtor}
2793
2794\begin{figure}
2795\begin{multicols}{2}
2796Entry
2797\begin{cfa}
2798if monitor is free
2799        enter
2800elif already own the monitor
2801        continue
2802elif matches waitfor mask
2803        push criteria to AS-stack
2804        continue
2805else
2806        block
2807increment recursion
2808\end{cfa}
2809\columnbreak
2810Exit
2811\begin{cfa}
2812decrement recursion
2813if recursion == 0
2814        if signal_stack not empty
2815                set_owner to thread
2816                if all monitors ready
2817                        wake-up thread
2818                endif
2819        endif
2820
2821        if entry queue not empty
2822                wake-up thread
2823        endif
2824\end{cfa}
2825\end{multicols}
2826\begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling and external scheduling},label={f:entry3}]
2827\end{cfa}
2828\end{figure}
2829
2830\begin{figure}
2831\begin{multicols}{2}
2832Destructor Entry
2833\begin{cfa}
2834if monitor is free
2835        enter
2836elif already own the monitor
2837        increment recursion
2838        return
2839create wait context
2840if matches waitfor mask
2841        reset mask
2842        push self to AS-stack
2843        baton pass
2844else
2845        wait
2846increment recursion
2847\end{cfa}
2848\columnbreak
2849Waitfor
2850\begin{cfa}
2851if matching thread is already there
2852        if found destructor
2853                push destructor to AS-stack
2854                unlock all monitors
2855        else
2856                push self to AS-stack
2857                baton pass
2858        endif
2859        return
2860endif
2861if non-blocking
2862        Unlock all monitors
2863        Return
2864endif
2865
2866push self to AS-stack
2867set waitfor mask
2868block
2869return
2870\end{cfa}
2871\end{multicols}
2872\begin{cfa}[caption={Pseudo code for the \protect\lstinline|waitfor| routine and the \protect\lstinline|mutex| entry routine for destructors},label={f:entry-dtor}]
2873\end{cfa}
2874\end{figure}
2875
2876
2877% ======================================================================
2878% ======================================================================
2879\section{Putting It All Together}
2880% ======================================================================
2881% ======================================================================
2882
2883
2884\section{Threads As Monitors}
2885As 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.
2886For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine:
2887\begin{figure}
2888\begin{cfa}[caption={Toy simulator using \protect\lstinline|thread|s and \protect\lstinline|monitor|s.},label={f:engine-v1}]
2889// Visualization declaration
2890thread Renderer {} renderer;
2891Frame * simulate( Simulator & this );
2892
2893// Simulation declaration
2894thread Simulator{} simulator;
2895void render( Renderer & this );
2896
2897// Blocking call used as communication
2898void draw( Renderer & mutex this, Frame * frame );
2899
2900// Simulation loop
2901void main( Simulator & this ) {
2902        while( true ) {
2903                Frame * frame = simulate( this );
2904                draw( renderer, frame );
2905        }
2906}
2907
2908// Rendering loop
2909void main( Renderer & this ) {
2910        while( true ) {
2911                waitfor( draw, this );
2912                render( this );
2913        }
2914}
2915\end{cfa}
2916\end{figure}
2917One 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.
2918Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner:
2919\begin{figure}
2920\begin{cfa}[caption={Same toy simulator with proper termination condition.},label={f:engine-v2}]
2921// Visualization declaration
2922thread Renderer {} renderer;
2923Frame * simulate( Simulator & this );
2924
2925// Simulation declaration
2926thread Simulator{} simulator;
2927void render( Renderer & this );
2928
2929// Blocking call used as communication
2930void draw( Renderer & mutex this, Frame * frame );
2931
2932// Simulation loop
2933void main( Simulator & this ) {
2934        while( true ) {
2935                Frame * frame = simulate( this );
2936                draw( renderer, frame );
2937
2938                // Exit main loop after the last frame
2939                if( frame->is_last ) break;
2940        }
2941}
2942
2943// Rendering loop
2944void main( Renderer & this ) {
2945        while( true ) {
2946                   waitfor( draw, this );
2947                or waitfor( ^?{}, this ) {
2948                        // Add an exit condition
2949                        break;
2950                }
2951
2952                render( this );
2953        }
2954}
2955
2956// Call destructor for simulator once simulator finishes
2957// Call destructor for renderer to signify shutdown
2958\end{cfa}
2959\end{figure}
2960
2961\section{Fibers \& Threads}
2962As mentioned in section \ref{preemption}, \CFA uses preemptive threads by default but can use fibers on demand.
2963Currently, using fibers is done by adding the following line of code to the program~:
2964\begin{cfa}
2965unsigned int default_preemption() {
2966        return 0;
2967}
2968\end{cfa}
2969This function is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice, \ie no preemption.
2970However, 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}
2971\begin{figure}
2972\lstset{language=CFA,deletedelim=**[is][]{`}{`}}
2973\begin{cfa}[caption={Using fibers and \textbf{uthread} side-by-side in \CFA},label={f:fiber-uthread}]
2974// Cluster forward declaration
2975struct cluster;
2976
2977// Processor forward declaration
2978struct processor;
2979
2980// Construct clusters with a preemption rate
2981void ?{}(cluster& this, unsigned int rate);
2982// Construct processor and add it to cluster
2983void ?{}(processor& this, cluster& cluster);
2984// Construct thread and schedule it on cluster
2985void ?{}(thread& this, cluster& cluster);
2986
2987// Declare two clusters
2988cluster thread_cluster = { 10`ms };                     // Preempt every 10 ms
2989cluster fibers_cluster = { 0 };                         // Never preempt
2990
2991// Construct 4 processors
2992processor processors[4] = {
2993        //2 for the thread cluster
2994        thread_cluster;
2995        thread_cluster;
2996        //2 for the fibers cluster
2997        fibers_cluster;
2998        fibers_cluster;
2999};
3000
3001// Declares thread
3002thread UThread {};
3003void ?{}(UThread& this) {
3004        // Construct underlying thread to automatically
3005        // be scheduled on the thread cluster
3006        (this){ thread_cluster }
3007}
3008
3009void main(UThread & this);
3010
3011// Declares fibers
3012thread Fiber {};
3013void ?{}(Fiber& this) {
3014        // Construct underlying thread to automatically
3015        // be scheduled on the fiber cluster
3016        (this.__thread){ fibers_cluster }
3017}
3018
3019void main(Fiber & this);
3020\end{cfa}
3021\end{figure}
3022
3023
3024% ======================================================================
3025% ======================================================================
3026\section{Performance Results} \label{results}
3027% ======================================================================
3028% ======================================================================
3029\section{Machine Setup}
3030Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks.
3031All tests were made on this machine.
3032\begin{table}
3033\begin{center}
3034\begin{tabular}{| l | r | l | r |}
3035\hline
3036Architecture            & x86\_64                       & NUMA node(s)  & 8 \\
3037\hline
3038CPU op-mode(s)          & 32-bit, 64-bit                & Model name    & AMD Opteron\texttrademark  Processor 6380 \\
3039\hline
3040Byte Order                      & Little Endian                 & CPU Freq              & 2.5\si{\giga\hertz} \\
3041\hline
3042CPU(s)                  & 64                            & L1d cache     & \SI{16}{\kibi\byte} \\
3043\hline
3044Thread(s) per core      & 2                             & L1i cache     & \SI{64}{\kibi\byte} \\
3045\hline
3046Core(s) per socket      & 8                             & L2 cache              & \SI{2048}{\kibi\byte} \\
3047\hline
3048Socket(s)                       & 4                             & L3 cache              & \SI{6144}{\kibi\byte} \\
3049\hline
3050\hline
3051Operating system                & Ubuntu 16.04.3 LTS    & Kernel                & Linux 4.4-97-generic \\
3052\hline
3053Compiler                        & GCC 6.3               & Translator    & CFA 1 \\
3054\hline
3055Java version            & OpenJDK-9             & Go version    & 1.9.2 \\
3056\hline
3057\end{tabular}
3058\end{center}
3059\caption{Machine setup used for the tests}
3060\label{tab:machine}
3061\end{table}
3062
3063\section{Micro Benchmarks}
3064All benchmarks are run using the same harness to produce the results, seen as the @BENCH()@ macro in the following examples.
3065This macro uses the following logic to benchmark the code:
3066\begin{cfa}
3067#define BENCH(run, result) \
3068        before = gettime(); \
3069        run; \
3070        after  = gettime(); \
3071        result = (after - before) / N;
3072\end{cfa}
3073The method used to get time is @clock_gettime(CLOCK_THREAD_CPUTIME_ID);@.
3074Each benchmark is using many iterations of a simple call to measure the cost of the call.
3075The specific number of iterations depends on the specific benchmark.
3076
3077\subsection{Context-Switching}
3078The first interesting benchmark is to measure how long context-switches take.
3079The simplest approach to do this is to yield on a thread, which executes a 2-step context switch.
3080Yielding 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).
3081In 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.
3082Figure~\ref{f:ctx-switch} shows the code for coroutines and threads with the results in table \ref{tab:ctx-switch}.
3083All omitted tests are functionally identical to one of these tests.
3084The difference between coroutines and threads can be attributed to the cost of scheduling.
3085\begin{figure}
3086\begin{multicols}{2}
3087\CFA Coroutines
3088\begin{cfa}
3089coroutine GreatSuspender {};
3090void main(GreatSuspender& this) {
3091        while(true) { suspend(); }
3092}
3093int main() {
3094        GreatSuspender s;
3095        resume(s);
3096        BENCH(
3097                for(size_t i=0; i<n; i++) {
3098                        resume(s);
3099                },
3100                result
3101        )
3102        printf("%llu\n", result);
3103}
3104\end{cfa}
3105\columnbreak
3106\CFA Threads
3107\begin{cfa}
3108
3109
3110
3111
3112int main() {
3113
3114
3115        BENCH(
3116                for(size_t i=0; i<n; i++) {
3117                        yield();
3118                },
3119                result
3120        )
3121        printf("%llu\n", result);
3122}
3123\end{cfa}
3124\end{multicols}
3125\begin{cfa}[caption={\CFA benchmark code used to measure context-switches for coroutines and threads.},label={f:ctx-switch}]
3126\end{cfa}
3127\end{figure}
3128
3129\begin{table}
3130\begin{center}
3131\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] |}
3132\cline{2-4}
3133\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3134\hline
3135Kernel Thread   & 241.5 & 243.86        & 5.08 \\
3136\CFA Coroutine  & 38            & 38            & 0    \\
3137\CFA Thread             & 103           & 102.96        & 2.96 \\
3138\uC Coroutine   & 46            & 45.86 & 0.35 \\
3139\uC Thread              & 98            & 99.11 & 1.42 \\
3140Goroutine               & 150           & 149.96        & 3.16 \\
3141Java Thread             & 289           & 290.68        & 8.72 \\
3142\hline
3143\end{tabular}
3144\end{center}
3145\caption{Context Switch comparison.
3146All numbers are in nanoseconds(\si{\nano\second})}
3147\label{tab:ctx-switch}
3148\end{table}
3149
3150\subsection{Mutual-Exclusion}
3151The next interesting benchmark is to measure the overhead to enter/leave a critical-section.
3152For monitors, the simplest approach is to measure how long it takes to enter and leave a monitor routine.
3153Figure~\ref{f:mutex} shows the code for \CFA.
3154To 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.
3155The results can be shown in table \ref{tab:mutex}.
3156
3157\begin{figure}
3158\begin{cfa}[caption={\CFA benchmark code used to measure mutex routines.},label={f:mutex}]
3159monitor M {};
3160void __attribute__((noinline)) call( M & mutex m /*, m2, m3, m4*/ ) {}
3161
3162int main() {
3163        M m/*, m2, m3, m4*/;
3164        BENCH(
3165                for(size_t i=0; i<n; i++) {
3166                        call(m/*, m2, m3, m4*/);
3167                },
3168                result
3169        )
3170        printf("%llu\n", result);
3171}
3172\end{cfa}
3173\end{figure}
3174
3175\begin{table}
3176\begin{center}
3177\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] |}
3178\cline{2-4}
3179\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3180\hline
3181C routine                                               & 2             & 2             & 0    \\
3182FetchAdd + FetchSub                             & 26            & 26            & 0    \\
3183Pthreads Mutex Lock                             & 31            & 31.86 & 0.99 \\
3184\uC @monitor@ member routine            & 30            & 30            & 0    \\
3185\CFA @mutex@ routine, 1 argument        & 41            & 41.57 & 0.9  \\
3186\CFA @mutex@ routine, 2 argument        & 76            & 76.96 & 1.57 \\
3187\CFA @mutex@ routine, 4 argument        & 145           & 146.68        & 3.85 \\
3188Java synchronized routine                       & 27            & 28.57 & 2.6  \\
3189\hline
3190\end{tabular}
3191\end{center}
3192\caption{Mutex routine comparison.
3193All numbers are in nanoseconds(\si{\nano\second})}
3194\label{tab:mutex}
3195\end{table}
3196
3197\subsection{Internal Scheduling}
3198The internal-scheduling benchmark measures the cost of waiting on and signalling a condition variable.
3199Figure~\ref{f:int-sched} shows the code for \CFA, with results table \ref{tab:int-sched}.
3200As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
3201
3202\begin{figure}
3203\begin{cfa}[caption={Benchmark code for internal scheduling},label={f:int-sched}]
3204volatile int go = 0;
3205condition c;
3206monitor M {};
3207M m1;
3208
3209void __attribute__((noinline)) do_call( M & mutex a1 ) { signal(c); }
3210
3211thread T {};
3212void ^?{}( T & mutex this ) {}
3213void main( T & this ) {
3214        while(go == 0) { yield(); }
3215        while(go == 1) { do_call(m1); }
3216}
3217int  __attribute__((noinline)) do_wait( M & mutex a1 ) {
3218        go = 1;
3219        BENCH(
3220                for(size_t i=0; i<n; i++) {
3221                        wait(c);
3222                },
3223                result
3224        )
3225        printf("%llu\n", result);
3226        go = 0;
3227        return 0;
3228}
3229int main() {
3230        T t;
3231        return do_wait(m1);
3232}
3233\end{cfa}
3234\end{figure}
3235
3236\begin{table}
3237\begin{center}
3238\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] |}
3239\cline{2-4}
3240\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3241\hline
3242Pthreads Condition Variable                     & 5902.5        & 6093.29       & 714.78 \\
3243\uC @signal@                                    & 322           & 323   & 3.36   \\
3244\CFA @signal@, 1 @monitor@      & 352.5 & 353.11        & 3.66   \\
3245\CFA @signal@, 2 @monitor@      & 430           & 430.29        & 8.97   \\
3246\CFA @signal@, 4 @monitor@      & 594.5 & 606.57        & 18.33  \\
3247Java @notify@                           & 13831.5       & 15698.21      & 4782.3 \\
3248\hline
3249\end{tabular}
3250\end{center}
3251\caption{Internal scheduling comparison.
3252All numbers are in nanoseconds(\si{\nano\second})}
3253\label{tab:int-sched}
3254\end{table}
3255
3256\subsection{External Scheduling}
3257The Internal scheduling benchmark measures the cost of the @waitfor@ statement (@_Accept@ in \uC).
3258Figure~\ref{f:ext-sched} shows the code for \CFA, with results in table \ref{tab:ext-sched}.
3259As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
3260
3261\begin{figure}
3262\begin{cfa}[caption={Benchmark code for external scheduling},label={f:ext-sched}]
3263volatile int go = 0;
3264monitor M {};
3265M m1;
3266thread T {};
3267
3268void __attribute__((noinline)) do_call( M & mutex a1 ) {}
3269
3270void ^?{}( T & mutex this ) {}
3271void main( T & this ) {
3272        while(go == 0) { yield(); }
3273        while(go == 1) { do_call(m1); }
3274}
3275int  __attribute__((noinline)) do_wait( M & mutex a1 ) {
3276        go = 1;
3277        BENCH(
3278                for(size_t i=0; i<n; i++) {
3279                        waitfor(call, a1);
3280                },
3281                result
3282        )
3283        printf("%llu\n", result);
3284        go = 0;
3285        return 0;
3286}
3287int main() {
3288        T t;
3289        return do_wait(m1);
3290}
3291\end{cfa}
3292\end{figure}
3293
3294\begin{table}
3295\begin{center}
3296\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] |}
3297\cline{2-4}
3298\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3299\hline
3300\uC @Accept@                                    & 350           & 350.61        & 3.11  \\
3301\CFA @waitfor@, 1 @monitor@     & 358.5 & 358.36        & 3.82  \\
3302\CFA @waitfor@, 2 @monitor@     & 422           & 426.79        & 7.95  \\
3303\CFA @waitfor@, 4 @monitor@     & 579.5 & 585.46        & 11.25 \\
3304\hline
3305\end{tabular}
3306\end{center}
3307\caption{External scheduling comparison.
3308All numbers are in nanoseconds(\si{\nano\second})}
3309\label{tab:ext-sched}
3310\end{table}
3311
3312
3313\subsection{Object Creation}
3314Finally, the last benchmark measures the cost of creation for concurrent objects.
3315Figure~\ref{f:creation} shows the code for @pthread@s and \CFA threads, with results shown in table \ref{tab:creation}.
3316As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
3317The 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.
3318
3319\begin{figure}
3320\begin{center}
3321@pthread@
3322\begin{cfa}
3323int main() {
3324        BENCH(
3325                for(size_t i=0; i<n; i++) {
3326                        pthread_t thread;
3327                        if(pthread_create(&thread,NULL,foo,NULL)<0) {
3328                                perror( "failure" );
3329                                return 1;
3330                        }
3331
3332                        if(pthread_join(thread, NULL)<0) {
3333                                perror( "failure" );
3334                                return 1;
3335                        }
3336                },
3337                result
3338        )
3339        printf("%llu\n", result);
3340}
3341\end{cfa}
3342
3343
3344
3345\CFA Threads
3346\begin{cfa}
3347int main() {
3348        BENCH(
3349                for(size_t i=0; i<n; i++) {
3350                        MyThread m;
3351                },
3352                result
3353        )
3354        printf("%llu\n", result);
3355}
3356\end{cfa}
3357\end{center}
3358\caption{Benchmark code for \protect\lstinline|pthread|s and \CFA to measure object creation}
3359\label{f:creation}
3360\end{figure}
3361
3362\begin{table}
3363\begin{center}
3364\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] |}
3365\cline{2-4}
3366\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
3367\hline
3368Pthreads                        & 26996 & 26984.71      & 156.6  \\
3369\CFA Coroutine Lazy     & 6             & 5.71  & 0.45   \\
3370\CFA Coroutine Eager    & 708           & 706.68        & 4.82   \\
3371\CFA Thread                     & 1173.5        & 1176.18       & 15.18  \\
3372\uC Coroutine           & 109           & 107.46        & 1.74   \\
3373\uC Thread                      & 526           & 530.89        & 9.73   \\
3374Goroutine                       & 2520.5        & 2530.93       & 61,56  \\
3375Java Thread                     & 91114.5       & 92272.79      & 961.58 \\
3376\hline
3377\end{tabular}
3378\end{center}
3379\caption{Creation comparison.
3380All numbers are in nanoseconds(\si{\nano\second}).}
3381\label{tab:creation}
3382\end{table}
3383
3384
3385
3386\section{Conclusion}
3387This paper has achieved a minimal concurrency \textbf{api} that is simple, efficient and usable as the basis for higher-level features.
3388The approach presented is based on a lightweight thread-system for parallelism, which sits on top of clusters of processors.
3389This M:N model is judged to be both more efficient and allow more flexibility for users.
3390Furthermore, this document introduces monitors as the main concurrency tool for users.
3391This paper also offers a novel approach allowing multiple monitors to be accessed simultaneously without running into the Nested Monitor Problem~\cite{Lister77}.
3392It also offers a full implementation of the concurrency runtime written entirely in \CFA, effectively the largest \CFA code base to date.
3393
3394
3395% ======================================================================
3396% ======================================================================
3397\section{Future Work}
3398% ======================================================================
3399% ======================================================================
3400
3401\subsection{Performance} \label{futur:perf}
3402This paper presents a first implementation of the \CFA concurrency runtime.
3403Therefore, there is still significant work to improve performance.
3404Many of the data structures and algorithms may change in the future to more efficient versions.
3405For example, the number of monitors in a single \textbf{bulk-acq} is only bound by the stack size, this is probably unnecessarily generous.
3406It may be possible that limiting the number helps increase performance.
3407However, it is not obvious that the benefit would be significant.
3408
3409\subsection{Flexible Scheduling} \label{futur:sched}
3410An important part of concurrency is scheduling.
3411Different scheduling algorithms can affect performance (both in terms of average and variation).
3412However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
3413One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted to the requirements of the workload.
3414However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms.
3415For 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.
3416This path of flexible schedulers will be explored for \CFA.
3417
3418\subsection{Non-Blocking I/O} \label{futur:nbio}
3419While 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).
3420These types of workloads often require significant engineering around amortizing costs of blocking IO operations.
3421At 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.
3422In this context, the role of the language makes Non-Blocking IO easily available and with low overhead.
3423The 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.
3424However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear.
3425
3426\subsection{Other Concurrency Tools} \label{futur:tools}
3427While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
3428Examples of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, executors and actors.
3429These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
3430
3431\subsection{Implicit Threading} \label{futur:implcit}
3432Simpler applications can benefit greatly from having implicit parallelism.
3433That is, parallelism that does not rely on the user to write concurrency.
3434This type of parallelism can be achieved both at the language level and at the library level.
3435The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithms~\cite{uC++book}.
3436Table \ref{f:parfor} shows three different code examples that accomplish point-wise sums of large arrays.
3437Note that none of these examples explicitly declare any concurrency or parallelism objects.
3438
3439\begin{table}
3440\begin{center}
3441\begin{tabular}[t]{|c|c|c|}
3442Sequential & Library Parallel & Language Parallel \\
3443\begin{cfa}[tabsize=3]
3444void big_sum(
3445        int* a, int* b,
3446        int* o,
3447        size_t len)
3448{
3449        for(
3450                int i = 0;
3451                i < len;
3452                ++i )
3453        {
3454                o[i]=a[i]+b[i];
3455        }
3456}
3457
3458
3459
3460
3461
3462int* a[10000];
3463int* b[10000];
3464int* c[10000];
3465//... fill in a & b
3466big_sum(a,b,c,10000);
3467\end{cfa} &\begin{cfa}[tabsize=3]
3468void big_sum(
3469        int* a, int* b,
3470        int* o,
3471        size_t len)
3472{
3473        range ar(a, a+len);
3474        range br(b, b+len);
3475        range or(o, o+len);
3476        parfor( ai, bi, oi,
3477        [](     int* ai,
3478                int* bi,
3479                int* oi)
3480        {
3481                oi=ai+bi;
3482        });
3483}
3484
3485
3486int* a[10000];
3487int* b[10000];
3488int* c[10000];
3489//... fill in a & b
3490big_sum(a,b,c,10000);
3491\end{cfa}&\begin{cfa}[tabsize=3]
3492void big_sum(
3493        int* a, int* b,
3494        int* o,
3495        size_t len)
3496{
3497        parfor (ai,bi,oi)
3498            in (a, b, o )
3499        {
3500                oi = ai + bi;
3501        }
3502}
3503
3504
3505
3506
3507
3508
3509
3510int* a[10000];
3511int* b[10000];
3512int* c[10000];
3513//... fill in a & b
3514big_sum(a,b,c,10000);
3515\end{cfa}
3516\end{tabular}
3517\end{center}
3518\caption{For loop to sum numbers: Sequential, using library parallelism and language parallelism.}
3519\label{f:parfor}
3520\end{table}
3521
3522Implicit parallelism is a restrictive solution and therefore has its limitations.
3523However, 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.
3524
3525
3526% A C K N O W L E D G E M E N T S
3527% -------------------------------
3528\section{Acknowledgements}
3529
3530Thanks 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.
3531Partial funding was supplied by the Natural Sciences and Engineering Research Council of Canada and a corporate partnership with Huawei Ltd.
3532
3533
3534% B I B L I O G R A P H Y
3535% -----------------------------
3536%\bibliographystyle{plain}
3537\bibliography{pl,local}
3538
3539
3540\end{document}
3541
3542% Local Variables: %
3543% tab-width: 4 %
3544% fill-column: 120 %
3545% compile-command: "make" %
3546% End: %
Note: See TracBrowser for help on using the repository browser.