source: doc/papers/concurrency/Paper.tex @ 84832d87

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 84832d87 was aac7197, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

working copy, no latin-1 characters

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