source: doc/papers/concurrency/Paper.tex @ 604e76d

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

initial setup for general and concurrency papers

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