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

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since f6f0d06f was f6f0d06f, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Pass 1 up to 3.1

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