source: doc/papers/concurrency/Paper.tex @ 6f9bc09

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

more writing

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