source: doc/papers/concurrency/Paper.tex @ 161cdf1

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

redo section on tour of Cforall

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