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

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 3265399 was d046db2, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

relocate AMA paper macros

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