source: doc/papers/concurrency/Paper.tex @ 0a89a8f

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

numerous updates

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