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

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

updates

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