source: doc/papers/concurrency/Paper.tex @ 7951100

arm-ehjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-expr
Last change on this file since 7951100 was 7951100, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

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