Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • doc/papers/concurrency/Paper.tex

    r0a89a8f r5ff188f  
    1 \documentclass[AMA,STIX1COL]{WileyNJD-v2}
    2 
    3 \articletype{RESEARCH ARTICLE}%
    4 
    5 \received{26 April 2016}
    6 \revised{6 June 2016}
    7 \accepted{6 June 2016}
    8 
    9 \raggedbottom
     1% inline code ©...© (copyright symbol) emacs: C-q M-)
     2% red highlighting ®...® (registered trademark symbol) emacs: C-q M-.
     3% blue highlighting ß...ß (sharp s symbol) emacs: C-q M-_
     4% green highlighting ¢...¢ (cent symbol) emacs: C-q M-"
     5% LaTex escape §...§ (section symbol) emacs: C-q M-'
     6% keyword escape ¶...¶ (pilcrow symbol) emacs: C-q M-^
     7% math escape $...$ (dollar symbol)
     8
     9\documentclass[10pt]{article}
    1010
    1111%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    1212
    1313% Latex packages used in the document.
     14\usepackage[T1]{fontenc}                                        % allow Latin1 (extended ASCII) characters
     15\usepackage{textcomp}
     16\usepackage[latin1]{inputenc}
     17\usepackage{fullpage,times,comment}
    1418\usepackage{epic,eepic}
     19\usepackage{upquote}                                            % switch curled `'" to straight
     20\usepackage{calc}
    1521\usepackage{xspace}
    16 \usepackage{comment}
    17 \usepackage{upquote}                                            % switch curled `'" to straight
     22\usepackage[labelformat=simple]{subfig}
     23\renewcommand{\thesubfigure}{(\alph{subfigure})}
     24\usepackage{graphicx}
     25\usepackage{tabularx}
     26\usepackage{multicol}
     27\usepackage{varioref}
    1828\usepackage{listings}                                           % format program code
    19 \usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig}
    20 \renewcommand{\thesubfigure}{(\alph{subfigure})}
     29\usepackage[flushmargin]{footmisc}                              % support label/reference in footnote
     30\usepackage{latexsym}                                           % \Box glyph
     31\usepackage{mathptmx}                                           % better math font with "times"
     32\usepackage[usenames]{color}
     33\usepackage[pagewise]{lineno}
     34\renewcommand{\linenumberfont}{\scriptsize\sffamily}
     35\usepackage{fancyhdr}
     36\usepackage{float}
    2137\usepackage{siunitx}
    2238\sisetup{ binary-units=true }
    23 %\input{style}                                                          % bespoke macros used in the document
    24 
    25 \hypersetup{breaklinks=true}
    26 \definecolor{OliveGreen}{cmyk}{0.64 0 0.95 0.40}
    27 \definecolor{Mahogany}{cmyk}{0 0.85 0.87 0.35}
    28 \definecolor{Plum}{cmyk}{0.50 1 0 0}
    29 
    30 \usepackage[pagewise]{lineno}
    31 \renewcommand{\linenumberfont}{\scriptsize\sffamily}
    32 
    33 \lefthyphenmin=4                                                        % hyphen only after 4 characters
    34 \righthyphenmin=4
     39\input{style}                                                   % bespoke macros used in the document
     40\usepackage{url}
     41\usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
     42\usepackage{breakurl}
     43\urlstyle{rm}
     44
     45\setlength{\topmargin}{-0.45in}                         % move running title into header
     46\setlength{\headsep}{0.25in}
    3547
    3648%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     
    3850% Names used in the document.
    3951
    40 \newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
    41 \newcommand{\CFA}{\protect\CFAIcon}             % safe for section/caption
    42 \newcommand{\CFL}{\textrm{Cforall}\xspace}      % Cforall symbolic name
    43 \newcommand{\Celeven}{\textrm{C11}\xspace}      % C11 symbolic name
    44 \newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
    45 \newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
    46 \newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
    47 \newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
    48 \newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name
    49 \newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name
    50 
    51 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     52\newcommand{\Version}{1.0.0}
     53\newcommand{\CS}{C\raisebox{-0.9ex}{\large$^\sharp$}\xspace}
    5254
    5355\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
     
    6062\newcommand{\TODO}{{\Textbf{TODO}}}
    6163
     64
     65\newsavebox{\LstBox}
     66
    6267%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    6368
    64 % Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
    65 % removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
    66 % AFTER HYPERREF.
    67 %\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}
    68 \renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}
    69 
    70 \makeatletter
    71 % parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
    72 % use rather than use \parident directly.
    73 \newlength{\parindentlnth}
    74 \setlength{\parindentlnth}{\parindent}
    75 
    76 \newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{\lst@basicstyle{#1}}}}
    77 \newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
    78 \newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
    79 
    80 \newlength{\gcolumnposn}                                        % temporary hack because lstlisting does not handle tabs correctly
    81 \newlength{\columnposn}
    82 \setlength{\gcolumnposn}{3.5in}
    83 \setlength{\columnposn}{\gcolumnposn}
    84 \newcommand{\C}[2][\@empty]{\ifx#1\@empty\else\global\setlength{\columnposn}{#1}\global\columnposn=\columnposn\fi\hfill\makebox[\textwidth-\columnposn][l]{\lst@basicstyle{\LstCommentStyle{#2}}}}
    85 \newcommand{\CRT}{\global\columnposn=\gcolumnposn}
    86 
    87 % Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
    88 % The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
    89 % The star version does not lowercase the index information, e.g., \newterm*{IBM}.
    90 \newcommand{\newtermFontInline}{\emph}
    91 \newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
    92 \newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
    93 \newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
    94 
    95 % Latin abbreviation
    96 \newcommand{\abbrevFont}{\textit}                       % set empty for no italics
    97 \@ifundefined{eg}{
    98 \newcommand{\EG}{\abbrevFont{e}.\abbrevFont{g}.}
    99 \newcommand*{\eg}{%
    100         \@ifnextchar{,}{\EG}%
    101                 {\@ifnextchar{:}{\EG}%
    102                         {\EG,\xspace}}%
    103 }}{}%
    104 \@ifundefined{ie}{
    105 \newcommand{\IE}{\abbrevFont{i}.\abbrevFont{e}.}
    106 \newcommand*{\ie}{%
    107         \@ifnextchar{,}{\IE}%
    108                 {\@ifnextchar{:}{\IE}%
    109                         {\IE,\xspace}}%
    110 }}{}%
    111 \@ifundefined{etc}{
    112 \newcommand{\ETC}{\abbrevFont{etc}}
    113 \newcommand*{\etc}{%
    114         \@ifnextchar{.}{\ETC}%
    115         {\ETC.\xspace}%
    116 }}{}%
    117 \@ifundefined{etal}{
    118 \newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}}
    119 \newcommand*{\etal}{%
    120         \@ifnextchar{.}{\protect\ETAL}%
    121                 {\protect\ETAL.\xspace}%
    122 }}{}%
    123 \@ifundefined{viz}{
    124 \newcommand{\VIZ}{\abbrevFont{viz}}
    125 \newcommand*{\viz}{%
    126         \@ifnextchar{.}{\VIZ}%
    127                 {\VIZ.\xspace}%
    128 }}{}%
    129 \makeatother
    130 
    131 \newenvironment{cquote}{%
    132         \list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
    133         \item\relax
    134 }{%
    135         \endlist
    136 }% cquote
    137 
    138 % CFA programming language, based on ANSI C (with some gcc additions)
    139 \lstdefinelanguage{CFA}[ANSI]{C}{
    140         morekeywords={
    141                 _Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, __attribute, __attribute__,
    142                 auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__, __const, __const__,
    143                 coroutine, disable, dtype, enable, __extension__, exception, fallthrough, fallthru, finally,
    144                 __float80, float80, __float128, float128, forall, ftype, _Generic, _Imaginary, __imag, __imag__,
    145                 inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
    146                 otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread,
    147                 _Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
    148                 virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
    149         moredirectives={defined,include_next}%
    150 }
    151 
    152 \lstset{
    153 language=CFA,
    154 columns=fullflexible,
    155 basicstyle=\linespread{0.9}\sf,                                                 % reduce line spacing and use sanserif font
    156 stringstyle=\tt,                                                                                % use typewriter font
    157 tabsize=5,                                                                                              % N space tabbing
    158 xleftmargin=\parindentlnth,                                                             % indent code to paragraph indentation
    159 %mathescape=true,                                                                               % LaTeX math escape in CFA code $...$
    160 escapechar=\$,                                                                                  % LaTeX escape in CFA code
    161 keepspaces=true,                                                                                %
    162 showstringspaces=false,                                                                 % do not show spaces with cup
    163 showlines=true,                                                                                 % show blank lines at end of code
    164 aboveskip=4pt,                                                                                  % spacing above/below code block
    165 belowskip=3pt,
    166 % replace/adjust listing characters that look bad in sanserif
    167 literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
    168         {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
    169         {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex{\textgreater}}2,
    170 moredelim=**[is][\color{red}]{`}{`},
    171 }% lstset
    172 
    173 % uC++ programming language, based on ANSI C++
    174 \lstdefinelanguage{uC++}[ANSI]{C++}{
    175         morekeywords={
    176                 _Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _CatchResume, _Cormonitor, _Coroutine, _Disable,
    177                 _Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
    178                 _Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
    179 }
    180 \lstdefinelanguage{Golang}{
    181         morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
    182         morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
    183                 bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
    184         morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
    185         morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
    186         morekeywords=[5]{Println,Printf,Error,},
    187         sensitive=true,
    188         morecomment=[l]{//},
    189         morecomment=[s]{/*}{*/},
    190         morestring=[b]',
    191         morestring=[b]",
    192         morestring=[s]{`}{`},
    193 }
    194 
    195 \lstnewenvironment{cfa}[1][]
    196 {\lstset{#1}}
    197 {}
    198 \lstnewenvironment{C++}[1][]                            % use C++ style
    199 {\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
    200 {}
    201 \lstnewenvironment{uC++}[1][]
    202 {\lstset{#1}}
    203 {}
    204 \lstnewenvironment{Go}[1][]
    205 {\lstset{#1}}
    206 {}
    207 
    208 % inline code @...@
    209 \lstMakeShortInline@%
    210 
    211 
    212 \title{\texorpdfstring{Concurrency in \protect\CFA}{Concurrency in Cforall}}
    213 
    214 \author[1]{Thierry Delisle}
    215 \author[1]{Peter A. Buhr*}
    216 \authormark{Thierry Delisle \textsc{et al}}
    217 
    218 \address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Ontario}, \country{Canada}}}
    219 
    220 \corres{*Peter A. Buhr, \email{pabuhr{\char`\@}uwaterloo.ca}}
    221 \presentaddress{Cheriton School of Computer Science, University of Waterloo, Waterloo, ON, N2L 3G1, Canada}
    222 
    223 
    224 \abstract[Summary]{
    225 \CFA is a modern, polymorphic, \emph{non-object-oriented} extension of the C programming language.
    226 This paper discusses the design of the concurrency and parallelism features in \CFA, and the concurrent runtime-system.
    227 These features are created from scratch as ISO C lacks concurrency, relying largely on pthreads.
    228 Coroutines and lightweight (user) threads are introduced into the language.
    229 In addition, monitors are added as a high-level mechanism for mutual exclusion and synchronization.
    230 A unique contribution is allowing multiple monitors to be safely acquired simultaneously.
    231 All features respect the expectations of C programmers, while being fully integrate with the \CFA polymorphic type-system and other language features.
    232 Finally, experimental results are presented to compare the performance of the new features with similar mechanisms in other concurrent programming-languages.
    233 }%
    234 
    235 \keywords{concurrency, parallelism, coroutines, threads, monitors, runtime, C, Cforall}
     69\setcounter{secnumdepth}{2}                           % number subsubsections
     70\setcounter{tocdepth}{2}                              % subsubsections in table of contents
     71% \linenumbers                                          % comment out to turn off line numbering
     72
     73\title{Concurrency in \CFA}
     74\author{Thierry Delisle and Peter A. Buhr, Waterloo, Ontario, Canada}
    23675
    23776
    23877\begin{document}
    239 \linenumbers                                            % comment out to turn off line numbering
    240 
    24178\maketitle
    24279
    243 % ======================================================================
     80\begin{abstract}
     81\CFA is a modern, \emph{non-object-oriented} extension of the C programming language.
     82This paper 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 paper 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.
     83\end{abstract}
     84
     85%----------------------------------------------------------------------
     86% MAIN BODY
     87%----------------------------------------------------------------------
     88
    24489% ======================================================================
    24590\section{Introduction}
    24691% ======================================================================
    247 % ======================================================================
    248 
    249 This paper provides a minimal concurrency \newterm{Abstract Program Interface} (API) that is simple, efficient and can be used to build other concurrency features.
    250 While the simplest concurrency system is a thread and a lock, this low-level approach is hard to master.
    251 An easier approach for programmers is to support higher-level constructs as the basis of concurrency.
    252 Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{Hochstein05}.
    253 Examples of high-level approaches are task based~\cite{TBB}, message passing~\cite{Erlang,MPI}, and implicit threading~\cite{OpenMP}.
    254 
    255 This paper used the following terminology.
    256 A \newterm{thread} is a fundamental unit of execution that runs a sequence of code and requires a stack to maintain state.
    257 Multiple simultaneous threads gives rise to \newterm{concurrency}, which requires locking to ensure safe communication and access to shared data.
    258 % Correspondingly, concurrency is defined as the concepts and challenges that occur when multiple independent (sharing memory, timing dependencies, \etc) concurrent threads are introduced.
    259 \newterm{Locking}, and by extension locks, are defined as a mechanism to prevent progress of threads to provide safety.
    260 \newterm{Parallelism} is running multiple threads simultaneously.
    261 Parallelism implies \emph{actual} simultaneous execution, where concurrency only requires \emph{apparent} simultaneous execution.
    262 As such, parallelism is only observable in differences in performance, which is observed through differences in timing.
    263 
    264 Hence, there are two problems to be solved in the design of concurrency for a programming language: concurrency and parallelism.
    265 While these two concepts are often combined, they are in fact distinct, requiring different tools~\cite[\S~2]{Buhr05a}.
    266 Concurrency tools handle synchronization and mutual exclusion, while parallelism tools handle performance, cost and resource utilization.
    267 
    268 The proposed concurrency API is implemented in a dialect of C, called \CFA.
    269 The paper discusses how the language features are added to the \CFA translator with respect to parsing, semantic, and type checking, and the corresponding high-perforamnce runtime-library to implement the concurrency features.
     92
     93This paper 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 paper 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.
     94
     95There 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.
     96
     97In the context of this paper, 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 paper \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.
    27098
    27199% ======================================================================
     
    277105The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency.
    278106
    279 \CFA is an extension of ISO-C and therefore supports all of the same paradigms as C.
    280 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.
    281 Like C, the basics of \CFA revolve around structures and routines, which are thin abstractions over machine code.
    282 The vast majority of the code produced by the \CFA translator respects memory layouts and calling conventions laid out by C.
    283 Interestingly, while \CFA is not an object-oriented language, lacking the concept of a receiver (\eg {\tt this}), it does have some notion of objects\footnote{C defines the term objects as : ``region of data storage in the execution environment, the contents of which can represent
    284 values''~\cite[3.15]{C11}}, most importantly construction and destruction of objects.
    285 Most of the following code examples can be found on the \CFA website~\cite{Cforall}.
    286 
    287 
     107\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
     108values''~\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}.
     109
     110% ======================================================================
    288111\subsection{References}
    289112
    290 Like \CC, \CFA introduces rebind-able references providing multiple dereferencing as an alternative to pointers.
    291 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:
    292 \begin{cfa}
     113Like \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:
     114\begin{cfacode}
    293115int x, *p1 = &x, **p2 = &p1, ***p3 = &p2,
    294116        &r1 = x,    &&r2 = r1,   &&&r3 = r2;
    295 ***p3 = 3;                                                      $\C{// change x}$
    296 r3    = 3;                                                      $\C{// change x, ***r3}$
    297 **p3  = ...;                                            $\C{// change p1}$
    298 *p3   = ...;                                            $\C{// change p2}$
    299 int y, z, & ar[3] = {x, y, z};          $\C{// initialize array of references}$
    300 typeof( ar[1]) p;                                       $\C{// is int, referenced object type}$
    301 typeof(&ar[1]) q;                                       $\C{// is int \&, reference type}$
    302 sizeof( ar[1]) == sizeof(int);          $\C{// is true, referenced object size}$
    303 sizeof(&ar[1]) == sizeof(int *);        $\C{// is true, reference size}$
    304 \end{cfa}
     117***p3 = 3;                                                      //change x
     118r3    = 3;                                                      //change x, ***r3
     119**p3  = ...;                                            //change p1
     120*p3   = ...;                                            //change p2
     121int y, z, & ar[3] = {x, y, z};          //initialize array of references
     122typeof( ar[1]) p;                                       //is int, referenced object type
     123typeof(&ar[1]) q;                                       //is int &, reference type
     124sizeof( ar[1]) == sizeof(int);          //is true, referenced object size
     125sizeof(&ar[1]) == sizeof(int *);        //is true, reference size
     126\end{cfacode}
    305127The 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.
    306128
     
    308130\subsection{Overloading}
    309131
    310 Another 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.
    311 As well, \CFA uses the return type as part of the selection criteria, as in Ada~\cite{Ada}.
    312 For routines with multiple parameters and returns, the selection is complex.
    313 \begin{cfa}
    314 // selection based on type and number of parameters
    315 void f(void);                   $\C{// (1)}$
    316 void f(char);                   $\C{// (2)}$
    317 void f(int, double);    $\C{// (3)}$
    318 f();                                    $\C{// select (1)}$
    319 f('a');                                 $\C{// select (2)}$
    320 f(3, 5.2);                              $\C{// select (3)}$
    321 
    322 // selection based on  type and number of returns
    323 char   f(int);                  $\C{// (1)}$
    324 double f(int);                  $\C{// (2)}$
    325 char   c = f(3);                $\C{// select (1)}$
    326 double d = f(4);                $\C{// select (2)}$
    327 \end{cfa}
    328 This feature is particularly important for concurrency since the runtime system relies on creating different types to represent concurrency objects.
    329 Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions that prevent name clashes.
    330 As seen in section \ref{basics}, routine @main@ is an example that benefits from overloading.
     132Another 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.
     133\begin{cfacode}
     134//selection based on type and number of parameters
     135void f(void);                   //(1)
     136void f(char);                   //(2)
     137void f(int, double);    //(3)
     138f();                                    //select (1)
     139f('a');                                 //select (2)
     140f(3, 5.2);                              //select (3)
     141
     142//selection based on  type and number of returns
     143char   f(int);                  //(1)
     144double f(int);                  //(2)
     145char   c = f(3);                //select (1)
     146double d = f(4);                //select (2)
     147\end{cfacode}
     148This 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.
    331149
    332150% ======================================================================
    333151\subsection{Operators}
    334 Overloading also extends to operators.
    335 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, \eg:
    336 \begin{cfa}
    337 int ++? (int op);                       $\C{// unary prefix increment}$
    338 int ?++ (int op);                       $\C{// unary postfix increment}$
    339 int ?+? (int op1, int op2);             $\C{// binary plus}$
    340 int ?<=?(int op1, int op2);             $\C{// binary less than}$
    341 int ?=? (int & op1, int op2);           $\C{// binary assignment}$
    342 int ?+=?(int & op1, int op2);           $\C{// binary plus-assignment}$
     152Overloading 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.:
     153\begin{cfacode}
     154int ++? (int op);                       //unary prefix increment
     155int ?++ (int op);                       //unary postfix increment
     156int ?+? (int op1, int op2);             //binary plus
     157int ?<=?(int op1, int op2);             //binary less than
     158int ?=? (int & op1, int op2);           //binary assignment
     159int ?+=?(int & op1, int op2);           //binary plus-assignment
    343160
    344161struct S {int i, j;};
    345 S ?+?(S op1, S op2) {                           $\C{// add two structures}$
     162S ?+?(S op1, S op2) {                           //add two structures
    346163        return (S){op1.i + op2.i, op1.j + op2.j};
    347164}
    348165S s1 = {1, 2}, s2 = {2, 3}, s3;
    349 s3 = s1 + s2;                                           $\C{// compute sum: s3 == {2, 5}}$
    350 \end{cfa}
     166s3 = s1 + s2;                                           //compute sum: s3 == {2, 5}
     167\end{cfacode}
    351168While concurrency does not use operator overloading directly, this feature is more important as an introduction for the syntax of constructors.
    352169
    353170% ======================================================================
    354171\subsection{Constructors/Destructors}
    355 Object 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.
    356 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:
    357 \begin{cfa}
     172Object 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:
     173\begin{cfacode}
    358174struct S {
    359175        size_t size;
    360176        int * ia;
    361177};
    362 void ?{}(S & s, int asize) {    $\C{// constructor operator}$
    363         s.size = asize;                         $\C{// initialize fields}$
     178void ?{}(S & s, int asize) {    //constructor operator
     179        s.size = asize;                         //initialize fields
    364180        s.ia = calloc(size, sizeof(S));
    365181}
    366 void ^?{}(S & s) {                              $\C{// destructor operator}$
    367         free(ia);                                       $\C{// de-initialization fields}$
     182void ^?{}(S & s) {                              //destructor operator
     183        free(ia);                                       //de-initialization fields
    368184}
    369185int main() {
    370         S x = {10}, y = {100};          $\C{// implicit calls: ?\{\}(x, 10), ?\{\}(y, 100)}$
    371         ...                                                     $\C{// use x and y}$
    372         ^x{};  ^y{};                            $\C{// explicit calls to de-initialize}$
    373         x{20};  y{200};                         $\C{// explicit calls to reinitialize}$
    374         ...                                                     $\C{// reuse x and y}$
    375 }                                                               $\C{// implicit calls: \^?\{\}(y), \^?\{\}(x)}$
    376 \end{cfa}
    377 The language guarantees that every object and all their fields are constructed.
    378 Like \CC, construction of an object is automatically done on allocation and destruction of the object is done on deallocation.
    379 Allocation and deallocation can occur on the stack or on the heap.
    380 \begin{cfa}
     186        S x = {10}, y = {100};          //implicit calls: ?{}(x, 10), ?{}(y, 100)
     187        ...                                                     //use x and y
     188        ^x{};  ^y{};                            //explicit calls to de-initialize
     189        x{20};  y{200};                         //explicit calls to reinitialize
     190        ...                                                     //reuse x and y
     191}                                                               //implicit calls: ^?{}(y), ^?{}(x)
     192\end{cfacode}
     193The 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.
     194\begin{cfacode}
    381195{
    382         struct S s = {10};      $\C{// allocation, call constructor}$
     196        struct S s = {10};      //allocation, call constructor
    383197        ...
    384 }                                               $\C{// deallocation, call destructor}$
    385 struct S * s = new();   $\C{// allocation, call constructor}$
     198}                                               //deallocation, call destructor
     199struct S * s = new();   //allocation, call constructor
    386200...
    387 delete(s);                              $\C{// deallocation, call destructor}$
    388 \end{cfa}
    389 Note that like \CC, \CFA introduces @new@ and @delete@, which behave like @malloc@ and @free@ in addition to constructing and destructing objects, after calling @malloc@ and before calling @free@, respectively.
     201delete(s);                              //deallocation, call destructor
     202\end{cfacode}
     203Note 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.
    390204
    391205% ======================================================================
    392206\subsection{Parametric Polymorphism}
    393207\label{s:ParametricPolymorphism}
    394 Routines in \CFA can also be reused for multiple types.
    395 This capability is done using the @forall@ clauses, which allow separately compiled routines to support generic usage over multiple types.
    396 For example, the following sum function works for any type that supports construction from 0 and addition:
    397 \begin{cfa}
    398 // constraint type, 0 and +
     208Routines 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:
     209\begin{cfacode}
     210//constraint type, 0 and +
    399211forall(otype T | { void ?{}(T *, zero_t); T ?+?(T, T); })
    400212T sum(T a[ ], size_t size) {
    401         T total = 0;                            $\C{// construct T from 0}$
     213        T total = 0;                            //construct T from 0
    402214        for(size_t i = 0; i < size; i++)
    403                 total = total + a[i];   $\C{// select appropriate +}$
     215                total = total + a[i];   //select appropriate +
    404216        return total;
    405217}
    406218
    407219S sa[5];
    408 int i = sum(sa, 5);                             $\C{// use S's 0 construction and +}$
    409 \end{cfa}
    410 
    411 Since writing constraints on types can become cumbersome for more constrained functions, \CFA also has the concept of traits.
    412 Traits are named collection of constraints that can be used both instead and in addition to regular constraints:
    413 \begin{cfa}
     220int i = sum(sa, 5);                             //use S's 0 construction and +
     221\end{cfacode}
     222
     223Since 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:
     224\begin{cfacode}
    414225trait summable( otype T ) {
    415         void ?{}(T *, zero_t);          $\C{// constructor from 0 literal}$
    416         T ?+?(T, T);                            $\C{// assortment of additions}$
     226        void ?{}(T *, zero_t);          //constructor from 0 literal
     227        T ?+?(T, T);                            //assortment of additions
    417228        T ?+=?(T *, T);
    418229        T ++?(T *);
    419230        T ?++(T *);
    420231};
    421 forall( otype T | summable(T) ) $\C{// use trait}$
     232forall( otype T | summable(T) ) //use trait
    422233T sum(T a[], size_t size);
    423 \end{cfa}
    424 
    425 Note that the type use for assertions can be either an @otype@ or a @dtype@.
    426 Types declared as @otype@ refer to ``complete'' objects, \ie objects with a size, a default constructor, a copy constructor, a destructor and an assignment operator.
    427 Using @dtype@, on the other hand, has none of these assumptions but is extremely restrictive, it only guarantees the object is addressable.
     234\end{cfacode}
     235
     236Note 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.
    428237
    429238% ======================================================================
    430239\subsection{with Clause/Statement}
    431 Since \CFA lacks the concept of a receiver, certain functions end up needing to repeat variable names often.
    432 To remove this inconvenience, \CFA provides the @with@ statement, which opens an aggregate scope making its fields directly accessible (like Pascal).
    433 \begin{cfa}
     240Since \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).
     241\begin{cfacode}
    434242struct S { int i, j; };
    435 int mem(S & this) with (this)           $\C{// with clause}$
    436         i = 1;                                                  $\C{// this->i}$
    437         j = 2;                                                  $\C{// this->j}$
     243int mem(S & this) with (this)           //with clause
     244        i = 1;                                                  //this->i
     245        j = 2;                                                  //this->j
    438246}
    439247int foo() {
    440248        struct S1 { ... } s1;
    441249        struct S2 { ... } s2;
    442         with (s1)                                               $\C{// with statement}$
     250        with (s1)                                               //with statement
    443251        {
    444                 // access fields of s1 without qualification
    445                 with (s2)                                       $\C{// nesting}$
     252                //access fields of s1 without qualification
     253                with (s2)                                       //nesting
    446254                {
    447                         // access fields of s1 and s2 without qualification
     255                        //access fields of s1 and s2 without qualification
    448256                }
    449257        }
    450         with (s1, s2)                                   $\C{// scopes open in parallel}$
     258        with (s1, s2)                                   //scopes open in parallel
    451259        {
    452                 // access fields of s1 and s2 without qualification
    453         }
    454 }
    455 \end{cfa}
    456 
    457 For more information on \CFA see \cite{cforall-ug,Schluntz17,www-cfa}.
     260                //access fields of s1 and s2 without qualification
     261        }
     262}
     263\end{cfacode}
     264
     265For more information on \CFA see \cite{cforall-ug,rob-thesis,www-cfa}.
    458266
    459267% ======================================================================
     
    462270% ======================================================================
    463271% ======================================================================
    464 
    465 At its core, concurrency is based on having multiple call-stacks and scheduling among threads of execution executing on these stacks.
    466 Multiple call stacks (or contexts) and a single thread of execution does \emph{not} imply concurrency.
    467 Execution with a single thread and multiple stacks where the thread is deterministically self-scheduling across the stacks is called \newterm{coroutining};
    468 execution with a single thread and multiple stacks but where the thread is scheduled by an oracle (non-deterministic from the thread's perspective) across the stacks is called concurrency~\cite[\S~3]{Buhr05a}.
    469 Therefore, a minimal concurrency system can be achieved using coroutines (see Section \ref{coroutine}), which instead of context-switching among each other, always defer to an oracle for where to context-switch next.
    470 
    471 While coroutines can execute on the caller's stack-frame, stack-full coroutines allow full generality and are sufficient as the basis for concurrency.
    472 The aforementioned oracle is a scheduler and the whole system now follows a cooperative threading-model (a.k.a., non-preemptive scheduling).
    473 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.
    474 In any case, a subset of concurrency related challenges start to appear.
    475 For the complete set of concurrency challenges to occur, the only feature missing is preemption.
    476 
    477 A scheduler introduces order of execution uncertainty, while preemption introduces uncertainty about where context switches occur.
    478 Mutual exclusion and synchronization are ways of limiting non-determinism in a concurrent system.
    479 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.
    480 Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows.
    481 
    482 
    483 \subsection{\protect\CFA's Thread Building Blocks}
    484 
    485 One 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.
    486 As such, library support for threading is far from widespread.
    487 At the time of writing the paper, neither \protect\lstinline|gcc| nor \protect\lstinline|clang| support ``threads.h'' in their standard libraries.}.
    488 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.
    489 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.
    490 And being a system-level language means programmers expect to choose precisely which features they need and which cost they are willing to pay.
    491 
    492 
    493 \subsection{Coroutines: A Stepping Stone}\label{coroutine}
    494 
    495 While the focus of this proposal is concurrency and parallelism, it is important to address coroutines, which are a significant building block of a concurrency system.
    496 \newterm{Coroutine}s are generalized routines with points where execution is suspended and resumed at a later time.
    497 Suspend/resume is a context switche and coroutines have other context-management operations.
    498 Many design challenges of threads are partially present in designing coroutines, which makes the design effort relevant.
    499 The core \textbf{api} of coroutines has two features: independent call-stacks and @suspend@/@resume@.
    500 
    501 A coroutine handles the class of problems that need to retain state between calls (\eg plugin, device driver, finite-state machine).
    502 For example, a problem made easier with coroutines is unbounded generators, \eg generating an infinite sequence of Fibonacci numbers:
    503 \begin{displaymath}
    504 f(n) = \left \{
    505 \begin{array}{ll}
    506 0                               & n = 0         \\
    507 1                               & n = 1         \\
    508 f(n-1) + f(n-2) & n \ge 2       \\
    509 \end{array}
    510 \right.
    511 \end{displaymath}
    512 Figure~\ref{f:C-fibonacci} shows conventional approaches for writing a Fibonacci generator in C.
    513 
    514 Figure~\ref{f:GlobalVariables} illustrates the following problems:
    515 unencapsulated global variables necessary to retain state between calls;
    516 only one fibonacci generator can run at a time;
    517 execution state must be explicitly retained.
    518 Figure~\ref{f:ExternalState} addresses these issues:
    519 unencapsulated program global variables become encapsulated structure variables;
    520 multiple fibonacci generators can run at a time by declaring multiple fibonacci objects;
    521 explicit execution state is removed by precomputing the first two Fibonacci numbers and returning $f(n-2)$.
     272Before 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.
     273
     274\section{Basics of concurrency}
     275At 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.
     276
     277Execution 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.
     278
     279Therefore, 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.
     280
     281A 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.
     282
     283\section{\protect\CFA's Thread Building Blocks}
     284One 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 paper, 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.
     285
     286\section{Coroutines: A Stepping Stone}\label{coroutine}
     287While 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}.
     288
     289\begin{table}
     290\begin{center}
     291\begin{tabular}{c @{\hskip 0.025in}|@{\hskip 0.025in} c @{\hskip 0.025in}|@{\hskip 0.025in} c}
     292\begin{ccode}[tabsize=2]
     293//Using callbacks
     294void fibonacci_func(
     295        int n,
     296        void (*callback)(int)
     297) {
     298        int first = 0;
     299        int second = 1;
     300        int next, i;
     301        for(i = 0; i < n; i++)
     302        {
     303                if(i <= 1)
     304                        next = i;
     305                else {
     306                        next = f1 + f2;
     307                        f1 = f2;
     308                        f2 = next;
     309                }
     310                callback(next);
     311        }
     312}
     313
     314int main() {
     315        void print_fib(int n) {
     316                printf("%d\n", n);
     317        }
     318
     319        fibonacci_func(
     320                10, print_fib
     321        );
     322
     323
     324
     325}
     326\end{ccode}&\begin{ccode}[tabsize=2]
     327//Using output array
     328void fibonacci_array(
     329        int n,
     330        int* array
     331) {
     332        int f1 = 0; int f2 = 1;
     333        int next, i;
     334        for(i = 0; i < n; i++)
     335        {
     336                if(i <= 1)
     337                        next = i;
     338                else {
     339                        next = f1 + f2;
     340                        f1 = f2;
     341                        f2 = next;
     342                }
     343                array[i] = next;
     344        }
     345}
     346
     347
     348int main() {
     349        int a[10];
     350
     351        fibonacci_func(
     352                10, a
     353        );
     354
     355        for(int i=0;i<10;i++){
     356                printf("%d\n", a[i]);
     357        }
     358
     359}
     360\end{ccode}&\begin{ccode}[tabsize=2]
     361//Using external state
     362typedef struct {
     363        int f1, f2;
     364} Iterator_t;
     365
     366int fibonacci_state(
     367        Iterator_t* it
     368) {
     369        int f;
     370        f = it->f1 + it->f2;
     371        it->f2 = it->f1;
     372        it->f1 = max(f,1);
     373        return f;
     374}
     375
     376
     377
     378
     379
     380
     381
     382int main() {
     383        Iterator_t it={0,0};
     384
     385        for(int i=0;i<10;i++){
     386                printf("%d\n",
     387                        fibonacci_state(
     388                                &it
     389                        );
     390                );
     391        }
     392
     393}
     394\end{ccode}
     395\end{tabular}
     396\end{center}
     397\caption{Different implementations of a Fibonacci sequence generator in C.}
     398\label{lst:fibonacci-c}
     399\end{table}
     400
     401A 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.
     402
     403Listing \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.
    522404
    523405\begin{figure}
    524 \centering
    525 \newbox\myboxA
    526 \begin{lrbox}{\myboxA}
    527 \begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    528 `int f1, f2, state = 1;`   // single global variables
    529 int fib() {
    530         int fn;
    531         `switch ( state )` {  // explicit execution state
    532           case 1: fn = 0;  f1 = fn;  state = 2;  break;
    533           case 2: fn = 1;  f2 = f1;  f1 = fn;  state = 3;  break;
    534           case 3: fn = f1 + f2;  f2 = f1;  f1 = fn;  break;
    535         }
    536         return fn;
    537 }
    538 int main() {
    539 
    540         for ( int i = 0; i < 10; i += 1 ) {
    541                 printf( "%d\n", fib() );
    542         }
    543 }
    544 \end{lstlisting}
    545 \end{lrbox}
    546 
    547 \newbox\myboxB
    548 \begin{lrbox}{\myboxB}
    549 \begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    550 #define FIB_INIT `{ 0, 1 }`
    551 typedef struct { int f2, f1; } Fib;
    552 int fib( Fib * f ) {
    553 
    554         int ret = f->f2;
    555         int fn = f->f1 + f->f2;
    556         f->f2 = f->f1; f->f1 = fn;
    557 
    558         return ret;
    559 }
    560 int main() {
    561         Fib f1 = FIB_INIT, f2 = FIB_INIT;
    562         for ( int i = 0; i < 10; i += 1 ) {
    563                 printf( "%d %d\n", fib( &f1 ), fib( &f2 ) );
    564         }
    565 }
    566 \end{lstlisting}
    567 \end{lrbox}
    568 
    569 \subfloat[3 States: global variables]{\label{f:GlobalVariables}\usebox\myboxA}
    570 \qquad
    571 \subfloat[1 State: external variables]{\label{f:ExternalState}\usebox\myboxB}
    572 \caption{C Fibonacci Implementations}
    573 \label{f:C-fibonacci}
    574 
    575 \bigskip
    576 
    577 \newbox\myboxA
    578 \begin{lrbox}{\myboxA}
    579 \begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    580 `coroutine` Fib { int fn; };
    581 void main( Fib & f ) with( f ) {
    582         int f1, f2;
    583         fn = 0;  f1 = fn;  `suspend()`;
    584         fn = 1;  f2 = f1;  f1 = fn;  `suspend()`;
     406\begin{cfacode}[caption={Implementation of Fibonacci using coroutines},label={lst:fibonacci-cfa}]
     407coroutine Fibonacci {
     408        int fn; //used for communication
     409};
     410
     411void ?{}(Fibonacci& this) { //constructor
     412        this.fn = 0;
     413}
     414
     415//main automatically called on first resume
     416void main(Fibonacci& this) with (this) {
     417        int fn1, fn2;           //retained between resumes
     418        fn  = 0;
     419        fn1 = fn;
     420        suspend(this);          //return to last resume
     421
     422        fn  = 1;
     423        fn2 = fn1;
     424        fn1 = fn;
     425        suspend(this);          //return to last resume
     426
    585427        for ( ;; ) {
    586                 fn = f1 + f2;  f2 = f1;  f1 = fn;  `suspend()`;
    587         }
    588 }
    589 int next( Fib & fib ) with( fib ) {
    590         `resume( fib );`
    591         return fn;
    592 }
    593 int main() {
    594         Fib f1, f2;
     428                fn  = fn1 + fn2;
     429                fn2 = fn1;
     430                fn1 = fn;
     431                suspend(this);  //return to last resume
     432        }
     433}
     434
     435int next(Fibonacci& this) {
     436        resume(this); //transfer to last suspend
     437        return this.fn;
     438}
     439
     440void main() { //regular program main
     441        Fibonacci f1, f2;
    595442        for ( int i = 1; i <= 10; i += 1 ) {
    596443                sout | next( f1 ) | next( f2 ) | endl;
    597444        }
    598445}
    599 \end{lstlisting}
    600 \end{lrbox}
    601 \newbox\myboxB
    602 \begin{lrbox}{\myboxB}
    603 \begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    604 `coroutine` Fib { int ret; };
    605 void main( Fib & f ) with( f ) {
    606         int fn, f1 = 1, f2 = 0;
    607         for ( ;; ) {
    608                 ret = f2;
    609 
    610                 fn = f1 + f2;  f2 = f1;  f1 = fn; `suspend();`
    611         }
    612 }
    613 int next( Fib & fib ) with( fib ) {
    614         `resume( fib );`
    615         return ret;
    616 }
    617 
    618 
    619 
    620 
    621 
    622 
    623 \end{lstlisting}
    624 \end{lrbox}
    625 \subfloat[3 States, internal variables]{\label{f:Coroutine3States}\usebox\myboxA}
    626 \qquad
    627 \subfloat[1 State, internal variables]{\label{f:Coroutine1State}\usebox\myboxB}
    628 \caption{\CFA Coroutine Fibonacci Implementations}
    629 \label{f:fibonacci-cfa}
     446\end{cfacode}
    630447\end{figure}
    631448
    632 Figure~\ref{f:Coroutine3States} creates a @coroutine@ type, which provides communication for multiple interface functions, and the \newterm{coroutine main}, which runs on the coroutine stack.
    633 \begin{cfa}
    634 `coroutine C { char c; int i; _Bool s; };`      $\C{// used for communication}$
    635 void ?{}( C & c ) { s = false; }                        $\C{// constructor}$
    636 void main( C & cor ) with( cor ) {                      $\C{// actual coroutine}$
    637         while ( ! s ) // process c
    638         if ( v == ... ) s = false;
    639 }
    640 // interface functions
    641 char cont( C & cor, char ch ) { c = ch; resume( cor ); return c; }
    642 _Bool stop( C & cor, int v ) { s = true; i = v; resume( cor ); return s; }
    643 \end{cfa}
    644 
    645 encapsulates the Fibonacci state in the  shows is an example of a solution to the Fibonacci problem using \CFA coroutines, where the coroutine stack holds sufficient state for the next generation.
    646 This solution has the advantage of having very strong decoupling between how the sequence is generated and how it is used.
    647 Indeed, this version is as easy to use as the @fibonacci_state@ solution, while the implementation is very similar to the @fibonacci_func@ example.
    648 
    649 Figure~\ref{f:fmt-line} shows the @Format@ coroutine for restructuring text into groups of character blocks of fixed size.
    650 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.
     449Listing \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.
    651450
    652451\begin{figure}
    653 \centering
    654 \begin{cfa}
    655 `coroutine` Format {
    656         char ch;                                                                $\C{// used for communication}$
    657         int g, b;                                                               $\C{// global because used in destructor}$
     452\begin{cfacode}[tabsize=3,caption={Formatting text into lines of 5 blocks of 4 characters.},label={lst:fmt-line}]
     453//format characters into blocks of 4 and groups of 5 blocks per line
     454coroutine Format {
     455        char ch;                                                                        //used for communication
     456        int g, b;                                                               //global because used in destructor
    658457};
    659 void ?{}( Format & fmt ) { `resume( fmt );` } $\C{// prime (start) coroutine}$
    660 void ^?{}( Format & fmt ) with( fmt ) { if ( g != 0 || b != 0 ) sout | endl; }
    661 void main( Format & fmt ) with( fmt ) {
    662         for ( ;; ) {                                                    $\C{// for as many characters}$
    663                 for ( g = 0; g < 5; g += 1 ) {          $\C{// groups of 5 blocks}$
    664                         for ( b = 0; b < 4; b += 1 ) {  $\C{// blocks of 4 characters}$
    665                                 `suspend();`
    666                                 sout | ch;                                      $\C{// print character}$
     458
     459void  ?{}(Format& fmt) {
     460        resume( fmt );                                                  //prime (start) coroutine
     461}
     462
     463void ^?{}(Format& fmt) with fmt {
     464        if ( fmt.g != 0 || fmt.b != 0 )
     465        sout | endl;
     466}
     467
     468void main(Format& fmt) with fmt {
     469        for ( ;; ) {                                                    //for as many characters
     470                for(g = 0; g < 5; g++) {                //groups of 5 blocks
     471                        for(b = 0; b < 4; fb++) {       //blocks of 4 characters
     472                                suspend();
     473                                sout | ch;                                      //print character
    667474                        }
    668                         sout | "  ";                                    $\C{// print block separator}$
     475                        sout | "  ";                                    //print block separator
    669476                }
    670                 sout | endl;                                            $\C{// print group separator}$
    671         }
    672 }
    673 void prt( Format & fmt, char ch ) {
     477                sout | endl;                                            //print group separator
     478        }
     479}
     480
     481void prt(Format & fmt, char ch) {
    674482        fmt.ch = ch;
    675         `resume( fmt );`
    676 }
     483        resume(fmt);
     484}
     485
    677486int main() {
    678487        Format fmt;
    679488        char ch;
    680         for ( ;; ) {                                                    $\C{// read until end of file}$
    681                 sin | ch;                                                       $\C{// read one character}$
    682           if ( eof( sin ) ) break;                              $\C{// eof ?}$
    683                 prt( fmt, ch );                                         $\C{// push character for formatting}$
    684         }
    685 }
    686 \end{cfa}
    687 \caption{Formatting text into lines of 5 blocks of 4 characters.}
    688 \label{f:fmt-line}
     489        Eof: for ( ;; ) {                                               //read until end of file
     490                sin | ch;                                                       //read one character
     491                if(eof(sin)) break Eof;                 //eof ?
     492                prt(fmt, ch);                                           //push character for formatting
     493        }
     494}
     495\end{cfacode}
    689496\end{figure}
    690497
    691 \begin{figure}
    692 \centering
    693 \lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}
    694 \begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
    695 \begin{cfa}
    696 `coroutine` Prod {
    697         Cons & c;
    698         int N, money, receipt;
    699 };
    700 void main( Prod & prod ) with( prod ) {
    701         // 1st resume starts here
    702         for ( int i = 0; i < N; i += 1 ) {
    703                 int p1 = random( 100 ), p2 = random( 100 );
    704                 sout | p1 | " " | p2 | endl;
    705                 int status = delivery( c, p1, p2 );
    706                 sout | " $" | money | endl | status | endl;
    707                 receipt += 1;
    708         }
    709         stop( c );
    710         sout | "prod stops" | endl;
    711 }
    712 int payment( Prod & prod, int money ) {
    713         prod.money = money;
    714         `resume( prod );`
    715         return prod.receipt;
    716 }
    717 void start( Prod & prod, int N, Cons &c ) {
    718         &prod.c = &c;
    719         prod.[N, receipt] = [N, 0];
    720         `resume( prod );`
    721 }
    722 int main() {
    723         Prod prod;
    724         Cons cons = { prod };
    725         srandom( getpid() );
    726         start( prod, 5, cons );
    727 }
    728 \end{cfa}
    729 &
    730 \begin{cfa}
    731 `coroutine` Cons {
    732         Prod & p;
    733         int p1, p2, status;
    734         _Bool done;
    735 };
    736 void ?{}( Cons & cons, Prod & p ) {
    737         &cons.p = &p;
    738         cons.[status, done ] = [0, false];
    739 }
    740 void ^?{}( Cons & cons ) {}
    741 void main( Cons & cons ) with( cons ) {
    742         // 1st resume starts here
    743         int money = 1, receipt;
    744         for ( ; ! done; ) {
    745                 sout | p1 | " " | p2 | endl | " $" | money | endl;
    746                 status += 1;
    747                 receipt = payment( p, money );
    748                 sout | " #" | receipt | endl;
    749                 money += 1;
    750         }
    751         sout | "cons stops" | endl;
    752 }
    753 int delivery( Cons & cons, int p1, int p2 ) {
    754         cons.[p1, p2] = [p1, p2];
    755         `resume( cons );`
    756         return cons.status;
    757 }
    758 void stop( Cons & cons ) {
    759         cons.done = true;
    760         `resume( cons );`
    761 }
    762 
    763 \end{cfa}
    764 \end{tabular}
    765 \caption{Producer / consumer: resume-resume cycle, bi-directional communication}
    766 \label{f:ProdCons}
    767 \end{figure}
    768 
    769 
    770 \subsubsection{Construction}
    771 
    772 One 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.
    773 In the case of coroutines, this challenge is simpler since there is no non-determinism from preemption or scheduling.
    774 However, the underlying challenge remains the same for coroutines and threads.
    775 
    776 The runtime system needs to create the coroutine's stack and, more importantly, prepare it for the first resumption.
    777 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.
    778 There are several solutions to this problem but the chosen option effectively forces the design of the coroutine.
    779 
    780 Furthermore, \CFA faces an extra challenge as polymorphic routines create invisible thunks when cast to non-polymorphic routines and these thunks have function scope.
    781 For example, the following code, while looking benign, can run into undefined behaviour because of thunks:
    782 
    783 \begin{cfa}
    784 // async: Runs function asynchronously on another thread
     498\subsection{Construction}
     499One 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.
     500
     501The 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.
     502
     503Furthermore, \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:
     504
     505\begin{cfacode}
     506//async: Runs function asynchronously on another thread
    785507forall(otype T)
    786508extern void async(void (*func)(T*), T* obj);
     
    791513void bar() {
    792514        int a;
    793         async(noop, &a); // start thread running noop with argument a
    794 }
    795 \end{cfa}
     515        async(noop, &a); //start thread running noop with argument a
     516}
     517\end{cfacode}
    796518
    797519The generated C code\footnote{Code trimmed down for brevity} creates a local thunk to hold type information:
    798520
    799 \begin{cfa}
     521\begin{ccode}
    800522extern void async(/* omitted */, void (*func)(void*), void* obj);
    801523
     
    811533        async(/* omitted */, ((void (*)(void*))(&_thunk0)), (&a));
    812534}
    813 \end{cfa}
    814 The problem in this example is a storage management issue, the function pointer @_thunk0@ is only valid until the end of the block, which limits the viable solutions because storing the function pointer for too long causes undefined behaviour; \ie the stack-based thunk being destroyed before it can be used.
    815 This challenge is an extension of challenges that come with second-class routines.
    816 Indeed, GCC nested routines also have the limitation that nested routine cannot be passed outside of the declaration scope.
    817 The case of coroutines and threads is simply an extension of this problem to multiple call stacks.
    818 
    819 
    820 \subsubsection{Alternative: Composition}
    821 
     535\end{ccode}
     536The 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.
     537
     538\subsection{Alternative: Composition}
    822539One solution to this challenge is to use composition/containment, where coroutine fields are added to manage the coroutine.
    823540
    824 \begin{cfa}
     541\begin{cfacode}
    825542struct Fibonacci {
    826         int fn; // used for communication
    827         coroutine c; // composition
     543        int fn; //used for communication
     544        coroutine c; //composition
    828545};
    829546
     
    834551void ?{}(Fibonacci& this) {
    835552        this.fn = 0;
    836         // Call constructor to initialize coroutine
     553        //Call constructor to initialize coroutine
    837554        (this.c){myMain};
    838555}
    839 \end{cfa}
    840 The downside of this approach is that users need to correctly construct the coroutine handle before using it.
    841 Like any other objects, the user must carefully choose construction order to prevent usage of objects not yet constructed.
    842 However, in the case of coroutines, users must also pass to the coroutine information about the coroutine main, like in the previous example.
    843 This opens the door for user errors and requires extra runtime storage to pass at runtime information that can be known statically.
    844 
    845 
    846 \subsubsection{Alternative: Reserved keyword}
    847 
     556\end{cfacode}
     557The 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.
     558
     559\subsection{Alternative: Reserved keyword}
    848560The next alternative is to use language support to annotate coroutines as follows:
    849 \begin{cfa}
     561
     562\begin{cfacode}
    850563coroutine Fibonacci {
    851         int fn; // used for communication
     564        int fn; //used for communication
    852565};
    853 \end{cfa}
    854 The @coroutine@ keyword means the compiler can find and inject code where needed.
    855 The downside of this approach is that it makes coroutine a special case in the language.
    856 Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language.
    857 Furthermore, implementing coroutines without language supports also displays the power of the programming language used.
    858 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.
    859 The reserved keywords are only present to improve ease of use for the common cases.
    860 
    861 
    862 \subsubsection{Alternative: Lambda Objects}
    863 
    864 For coroutines as for threads, many implementations are based on routine pointers or function objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
    865 For example, Boost implements coroutines in terms of four functor object types:
    866 \begin{cfa}
     566\end{cfacode}
     567The \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.
     568
     569\subsection{Alternative: Lambda Objects}
     570
     571For 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:
     572\begin{cfacode}
    867573asymmetric_coroutine<>::pull_type
    868574asymmetric_coroutine<>::push_type
    869575symmetric_coroutine<>::call_type
    870576symmetric_coroutine<>::yield_type
    871 \end{cfa}
    872 Often, the canonical threading paradigm in languages is based on function pointers, @pthread@ being one of the most well-known examples.
    873 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.
    874 Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda based coroutines adds very little.
    875 
    876 A variation of this would be to use a simple function pointer in the same way @pthread@ does for threads:
    877 \begin{cfa}
     577\end{cfacode}
     578Often, 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.
     579
     580A variation of this would be to use a simple function pointer in the same way \texttt{pthread} does for threads:
     581\begin{cfacode}
    878582void foo( coroutine_t cid, void* arg ) {
    879583        int* value = (int*)arg;
    880         // Coroutine body
     584        //Coroutine body
    881585}
    882586
     
    886590        coroutine_resume( &cid );
    887591}
    888 \end{cfa}
    889 This semantics is more common for thread interfaces but coroutines work equally well.
    890 As discussed in section \ref{threads}, this approach is superseded by static approaches in terms of expressivity.
    891 
    892 
    893 \subsubsection{Alternative: Trait-Based Coroutines}
    894 
    895 Finally, the underlying approach, which is the one closest to \CFA idioms, is to use trait-based lazy coroutines.
    896 This approach defines a coroutine as anything that satisfies the trait @is_coroutine@ (as defined below) and is used as a coroutine.
    897 
    898 \begin{cfa}
     592\end{cfacode}
     593This 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.
     594
     595\subsection{Alternative: Trait-Based Coroutines}
     596
     597Finally, 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.
     598
     599\begin{cfacode}
    899600trait is_coroutine(dtype T) {
    900601      void main(T& this);
     
    904605forall( dtype T | is_coroutine(T) ) void suspend(T&);
    905606forall( dtype T | is_coroutine(T) ) void resume (T&);
    906 \end{cfa}
    907 This ensures that an object is not a coroutine until @resume@ is called on the object.
    908 Correspondingly, any object that is passed to @resume@ is a coroutine since it must satisfy the @is_coroutine@ trait to compile.
    909 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 @get_coroutine@ routine.
    910 The \CFA keyword @coroutine@ simply has the effect of implementing the getter and forward declarations required for users to implement the main routine.
     607\end{cfacode}
     608This 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.
    911609
    912610\begin{center}
    913611\begin{tabular}{c c c}
    914 \begin{cfa}[tabsize=3]
     612\begin{cfacode}[tabsize=3]
    915613coroutine MyCoroutine {
    916614        int someValue;
    917615};
    918 \end{cfa} & == & \begin{cfa}[tabsize=3]
     616\end{cfacode} & == & \begin{cfacode}[tabsize=3]
    919617struct MyCoroutine {
    920618        int someValue;
     
    930628
    931629void main(struct MyCoroutine* this);
    932 \end{cfa}
     630\end{cfacode}
    933631\end{tabular}
    934632\end{center}
     
    936634The 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.
    937635
    938 \subsection{Thread Interface}\label{threads}
    939 The basic building blocks of multithreading in \CFA are \textbf{cfathread}.
    940 Both user and kernel threads are supported, where user threads are the concurrency mechanism and kernel threads are the parallel mechanism.
    941 User threads offer a flexible and lightweight interface.
    942 A thread can be declared using a struct declaration @thread@ as follows:
    943 
    944 \begin{cfa}
     636\section{Thread Interface}\label{threads}
     637The 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:
     638
     639\begin{cfacode}
    945640thread foo {};
    946 \end{cfa}
     641\end{cfacode}
    947642
    948643As for coroutines, the keyword is a thin wrapper around a \CFA trait:
    949644
    950 \begin{cfa}
     645\begin{cfacode}
    951646trait is_thread(dtype T) {
    952647      void ^?{}(T & mutex this);
     
    954649      thread_desc* get_thread(T & this);
    955650};
    956 \end{cfa}
    957 
    958 Obviously, for this thread implementation to be useful it must run some user code.
    959 Several other threading interfaces use a function-pointer representation as the interface of threads (for example \Csharp~\cite{Csharp} and Scala~\cite{Scala}).
    960 However, this proposal considers that statically tying a @main@ routine to a thread supersedes this approach.
    961 Since the @main@ routine is already a special routine in \CFA (where the program begins), it is a natural extension of the semantics to use overloading to declare mains for different threads (the normal main being the main of the initial thread).
    962 As such the @main@ routine of a thread can be defined as
    963 \begin{cfa}
     651\end{cfacode}
     652
     653Obviously, 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
     654\begin{cfacode}
    964655thread foo {};
    965656
     
    967658        sout | "Hello World!" | endl;
    968659}
    969 \end{cfa}
    970 
    971 In this example, threads of type @foo@ start execution in the @void main(foo &)@ routine, which prints @"Hello World!".@ While this paper encourages this approach to enforce strongly typed programming, users may prefer to use the routine-based thread semantics for the sake of simplicity.
    972 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.
    973 \begin{cfa}
     660\end{cfacode}
     661
     662In this example, threads of type \code{foo} start execution in the \code{void main(foo &)} routine, which prints \code{"Hello World!".} While this paper encourages this approach to enforce strongly typed programming, users may prefer to use the routine-based thread semantics for the sake of simplicity. 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.
     663\begin{cfacode}
    974664typedef void (*voidFunc)(int);
    975665
     
    985675
    986676void main(FuncRunner & this) {
    987         // thread starts here and runs the function
     677        //thread starts here and runs the function
    988678        this.func( this.arg );
    989679}
     
    997687        return 0?
    998688}
    999 \end{cfa}
     689\end{cfacode}
    1000690
    1001691A 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}.
    1002692
    1003 Of course, for threads to be useful, it must be possible to start and stop threads and wait for them to complete execution.
    1004 While using an \textbf{api} such as @fork@ and @join@ is relatively common in the literature, such an interface is unnecessary.
    1005 Indeed, the simplest approach is to use \textbf{raii} principles and have threads @fork@ after the constructor has completed and @join@ before the destructor runs.
    1006 \begin{cfa}
     693Of 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.
     694\begin{cfacode}
    1007695thread World;
    1008696
     
    1013701void main() {
    1014702        World w;
    1015         // Thread forks here
    1016 
    1017         // Printing "Hello " and "World!" are run concurrently
     703        //Thread forks here
     704
     705        //Printing "Hello " and "World!" are run concurrently
    1018706        sout | "Hello " | endl;
    1019707
    1020         // Implicit join at end of scope
    1021 }
    1022 \end{cfa}
     708        //Implicit join at end of scope
     709}
     710\end{cfacode}
    1023711
    1024712This 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.
    1025713
    1026 \begin{cfa}
     714\begin{cfacode}
    1027715thread MyThread {
    1028716        //...
    1029717};
    1030718
    1031 // main
     719//main
    1032720void main(MyThread& this) {
    1033721        //...
     
    1036724void foo() {
    1037725        MyThread thrds[10];
    1038         // Start 10 threads at the beginning of the scope
     726        //Start 10 threads at the beginning of the scope
    1039727
    1040728        DoStuff();
    1041729
    1042         // Wait for the 10 threads to finish
    1043 }
    1044 \end{cfa}
    1045 
    1046 However, one of the drawbacks of this approach is that threads always form a tree where nodes must always outlive their children, \ie they are always destroyed in the opposite order of construction because of C scoping rules.
    1047 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.
    1048 
    1049 \begin{cfa}
     730        //Wait for the 10 threads to finish
     731}
     732\end{cfacode}
     733
     734However, 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.
     735
     736\begin{cfacode}
    1050737thread MyThread {
    1051738        //...
     
    1059746        MyThread* long_lived;
    1060747        {
    1061                 // Start a thread at the beginning of the scope
     748                //Start a thread at the beginning of the scope
    1062749                MyThread short_lived;
    1063750
    1064                 // create another thread that will outlive the thread in this scope
     751                //create another thread that will outlive the thread in this scope
    1065752                long_lived = new MyThread;
    1066753
    1067754                DoStuff();
    1068755
    1069                 // Wait for the thread short_lived to finish
     756                //Wait for the thread short_lived to finish
    1070757        }
    1071758        DoMoreStuff();
    1072759
    1073         // Now wait for the long_lived to finish
     760        //Now wait for the long_lived to finish
    1074761        delete long_lived;
    1075762}
    1076 \end{cfa}
     763\end{cfacode}
    1077764
    1078765
     
    1082769% ======================================================================
    1083770% ======================================================================
    1084 Several tools can be used to solve concurrency challenges.
    1085 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}).
    1086 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).
    1087 However, in languages that use routine calls as their core abstraction mechanism, these approaches force a clear distinction between concurrent and non-concurrent paradigms (\ie message passing versus routine calls).
    1088 This distinction in turn means that, in order to be effective, programmers need to learn two sets of design patterns.
    1089 While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
    1090 
    1091 Approaches 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.
    1092 At the lowest level, concurrent paradigms are implemented as atomic operations and locks.
    1093 Many such mechanisms have been proposed, including semaphores~\cite{Dijkstra68b} and path expressions~\cite{Campbell74}.
    1094 However, for productivity reasons it is desirable to have a higher-level construct be the core concurrency paradigm~\cite{Hochstein05}.
    1095 
    1096 An approach that is worth mentioning because it is gaining in popularity is transactional memory~\cite{Herlihy93}.
    1097 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.
    1098 
    1099 One of the most natural, elegant, and efficient mechanisms for synchronization and communication, especially for shared-memory systems, is the \emph{monitor}.
    1100 Monitors were first proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}.
    1101 Many programming languages---\eg Concurrent Pascal~\cite{ConcurrentPascal}, Mesa~\cite{Mesa}, Modula~\cite{Modula-2}, Turing~\cite{Turing:old}, Modula-3~\cite{Modula-3}, NeWS~\cite{NeWS}, Emerald~\cite{Emerald}, \uC~\cite{Buhr92a} and Java~\cite{Java}---provide monitors as explicit language constructs.
    1102 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.
    1103 For these reasons, this project proposes monitors as the core concurrency construct.
    1104 
    1105 
    1106 \subsection{Basics}
    1107 
    1108 Non-determinism requires concurrent systems to offer support for mutual-exclusion and synchronization.
    1109 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.
    1110 On the other hand, synchronization enforces relative ordering of execution and synchronization tools provide numerous mechanisms to establish timing relationships among threads.
    1111 
    1112 
    1113 \subsubsection{Mutual-Exclusion}
    1114 
    1115 As mentioned above, mutual-exclusion is the guarantee that only a fix number of threads can enter a critical section at once.
    1116 However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
    1117 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.
    1118 Ease of use comes by either guaranteeing some problems cannot occur (\eg being deadlock free) or by offering a more explicit coupling between data and corresponding critical section.
    1119 For example, the \CC @std::atomic<T>@ offers an easy way to express mutual-exclusion on a restricted set of operations (\eg reading/writing large types atomically).
    1120 Another challenge with low-level locks is composability.
    1121 Locks have restricted composability because it takes careful organizing for multiple locks to be used while preventing deadlocks.
    1122 Easing composability is another feature higher-level mutual-exclusion mechanisms often offer.
    1123 
    1124 
    1125 \subsubsection{Synchronization}
    1126 
    1127 As with mutual-exclusion, low-level synchronization primitives often offer good performance and good flexibility at the cost of ease of use.
    1128 Again, higher-level mechanisms often simplify usage by adding either better coupling between synchronization and data (\eg message passing) or offering a simpler solution to otherwise involved challenges.
    1129 As mentioned above, synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}.
    1130 Most of the time, synchronization happens within a critical section, where threads must acquire mutual-exclusion in a certain order.
    1131 However, it may also be desirable to guarantee that event \textit{Z} does not occur between \textit{X} and \textit{Y}.
    1132 Not satisfying this property is called \textbf{barging}.
    1133 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}.
    1134 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.
    1135 Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
    1136 This challenge is often split into two different methods, barging avoidance and barging prevention.
    1137 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.
    1138 
     771Several 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.
     772
     773Approaches 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}.
     774
     775An 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.
     776
     777One 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.
     778
     779\section{Basics}
     780Non-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.
     781
     782\subsection{Mutual-Exclusion}
     783As 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.
     784
     785\subsection{Synchronization}
     786As 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.
    1139787
    1140788% ======================================================================
     
    1143791% ======================================================================
    1144792% ======================================================================
    1145 A \textbf{monitor} is a set of routines that ensure mutual-exclusion when accessing shared state.
    1146 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.
    1147 This strong association eases readability and maintainability, at the cost of flexibility.
    1148 Note that both monitors and mutex locks, require an abstract handle to identify them.
    1149 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.
    1150 The only requirement is the ability to declare a handle to a shared object and a set of routines that act on it:
    1151 \begin{cfa}
     793A \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:
     794\begin{cfacode}
    1152795typedef /*some monitor type*/ monitor;
    1153796int f(monitor & m);
    1154797
    1155798int main() {
    1156         monitor m;  // Handle m
    1157         f(m);       // Routine using handle
    1158 }
    1159 \end{cfa}
     799        monitor m;  //Handle m
     800        f(m);       //Routine using handle
     801}
     802\end{cfacode}
    1160803
    1161804% ======================================================================
     
    1164807% ======================================================================
    1165808% ======================================================================
    1166 The above monitor example displays some of the intrinsic characteristics.
    1167 First, it is necessary to use pass-by-reference over pass-by-value for monitor routines.
    1168 This semantics is important, because at their core, monitors are implicit mutual-exclusion objects (locks), and these objects cannot be copied.
    1169 Therefore, monitors are non-copy-able objects (@dtype@).
    1170 
    1171 Another aspect to consider is when a monitor acquires its mutual exclusion.
    1172 For example, a monitor may need to be passed through multiple helper routines that do not acquire the monitor mutual-exclusion on entry.
    1173 Passthrough can occur for generic helper routines (@swap@, @sort@, \etc) or specific helper routines like the following to implement an atomic counter:
    1174 
    1175 \begin{cfa}
     809The 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}).
     810
     811Another 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:
     812
     813\begin{cfacode}
    1176814monitor counter_t { /*...see section $\ref{data}$...*/ };
    1177815
    1178 void ?{}(counter_t & nomutex this); // constructor
    1179 size_t ++?(counter_t & mutex this); // increment
    1180 
    1181 // need for mutex is platform dependent
    1182 void ?{}(size_t * this, counter_t & mutex cnt); // conversion
    1183 \end{cfa}
     816void ?{}(counter_t & nomutex this); //constructor
     817size_t ++?(counter_t & mutex this); //increment
     818
     819//need for mutex is platform dependent
     820void ?{}(size_t * this, counter_t & mutex cnt); //conversion
     821\end{cfacode}
    1184822This counter is used as follows:
    1185823\begin{center}
    1186824\begin{tabular}{c @{\hskip 0.35in} c @{\hskip 0.35in} c}
    1187 \begin{cfa}
    1188 // shared counter
     825\begin{cfacode}
     826//shared counter
    1189827counter_t cnt1, cnt2;
    1190828
    1191 // multiple threads access counter
     829//multiple threads access counter
    1192830thread 1 : cnt1++; cnt2++;
    1193831thread 2 : cnt1++; cnt2++;
     
    1195833        ...
    1196834thread N : cnt1++; cnt2++;
    1197 \end{cfa}
     835\end{cfacode}
    1198836\end{tabular}
    1199837\end{center}
    1200 Notice how the counter is used without any explicit synchronization and yet supports thread-safe semantics for both reading and writing, which is similar in usage to the \CC template @std::atomic@.
    1201 
    1202 Here, the constructor (@?{}@) uses the @nomutex@ keyword to signify that it does not acquire the monitor mutual-exclusion when constructing.
    1203 This semantics is because an object not yet constructed should never be shared and therefore does not require mutual exclusion.
    1204 Furthermore, it allows the implementation greater freedom when it initializes the monitor locking.
    1205 The prefix increment operator uses @mutex@ to protect the incrementing process from race conditions.
    1206 Finally, there is a conversion operator from @counter_t@ to @size_t@.
    1207 This conversion may or may not require the @mutex@ keyword depending on whether or not reading a @size_t@ is an atomic operation.
    1208 
    1209 For maximum usability, monitors use \textbf{multi-acq} semantics, which means a single thread can acquire the same monitor multiple times without deadlock.
    1210 For example, listing \ref{fig:search} uses recursion and \textbf{multi-acq} to print values inside a binary tree.
     838Notice 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}.
     839
     840Here, 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.
     841
     842For 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.
    1211843\begin{figure}
    1212 \begin{cfa}[caption={Recursive printing algorithm using \textbf{multi-acq}.},label={fig:search}]
     844\begin{cfacode}[caption={Recursive printing algorithm using \textbf{multi-acq}.},label={fig:search}]
    1213845monitor printer { ... };
    1214846struct tree {
     
    1223855        print(p, t->right);
    1224856}
    1225 \end{cfa}
     857\end{cfacode}
    1226858\end{figure}
    1227859
    1228 Having both @mutex@ and @nomutex@ keywords can be redundant, depending on the meaning of a routine having neither of these keywords.
    1229 For example, it is reasonable that it should default to the safest option (@mutex@) when given a routine without qualifiers @void foo(counter_t & this)@, whereas assuming @nomutex@ is unsafe and may cause subtle errors.
    1230 On the other hand, @nomutex@ is the ``normal'' parameter behaviour, it effectively states explicitly that ``this routine is not special''.
    1231 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.
    1232 Mandatory keywords would also have the added benefit of being self-documented but at the cost of extra typing.
    1233 While there are several benefits to mandatory keywords, they do bring a few challenges.
    1234 Mandatory keywords in \CFA would imply that the compiler must know without doubt whether or not a parameter is a monitor or not.
    1235 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.
    1236 For this reason, \CFA only has the @mutex@ keyword and uses no keyword to mean @nomutex@.
    1237 
    1238 The next semantic decision is to establish when @mutex@ may be used as a type qualifier.
    1239 Consider the following declarations:
    1240 \begin{cfa}
     860Having 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}.
     861
     862The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
     863\begin{cfacode}
    1241864int f1(monitor & mutex m);
    1242865int f2(const monitor & mutex m);
     
    1244867int f4(monitor * mutex m []);
    1245868int f5(graph(monitor *) & mutex m);
    1246 \end{cfa}
    1247 The problem is to identify which object(s) should be acquired.
    1248 Furthermore, each object needs to be acquired only once.
    1249 In the case of simple routines like @f1@ and @f2@ it is easy to identify an exhaustive list of objects to acquire on entry.
    1250 Adding indirections (@f3@) still allows the compiler and programmer to identify which object is acquired.
    1251 However, adding in arrays (@f4@) makes it much harder.
    1252 Array lengths are not necessarily known in C, and even then, making sure objects are only acquired once becomes none-trivial.
    1253 This problem can be extended to absurd limits like @f5@, which uses a graph of monitors.
    1254 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).
    1255 Also note that while routine @f3@ can be supported, meaning that monitor @**m@ is acquired, passing an array to this routine would be type-safe and yet result in undefined behaviour because only the first element of the array is acquired.
    1256 However, this ambiguity is part of the C type-system with respects to arrays.
    1257 For this reason, @mutex@ is disallowed in the context where arrays may be passed:
    1258 \begin{cfa}
    1259 int f1(monitor & mutex m);    // Okay : recommended case
    1260 int f2(monitor * mutex m);    // Not Okay : Could be an array
    1261 int f3(monitor mutex m []);  // Not Okay : Array of unknown length
    1262 int f4(monitor ** mutex m);   // Not Okay : Could be an array
    1263 int f5(monitor * mutex m []); // Not Okay : Array of unknown length
    1264 \end{cfa}
    1265 Note that not all array functions are actually distinct in the type system.
    1266 However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
    1267 
    1268 Unlike 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.
    1269 A consequence of this approach is that it extends naturally to multi-monitor calls.
    1270 \begin{cfa}
     869\end{cfacode}
     870The 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:
     871\begin{cfacode}
     872int f1(monitor & mutex m);    //Okay : recommended case
     873int f2(monitor * mutex m);    //Not Okay : Could be an array
     874int f3(monitor mutex m []);  //Not Okay : Array of unknown length
     875int f4(monitor ** mutex m);   //Not Okay : Could be an array
     876int f5(monitor * mutex m []); //Not Okay : Array of unknown length
     877\end{cfacode}
     878Note 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.
     879
     880Unlike 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.
     881\begin{cfacode}
    1271882int f(MonitorA & mutex a, MonitorB & mutex b);
    1272883
     
    1274885MonitorB b;
    1275886f(a,b);
    1276 \end{cfa}
    1277 While OO monitors could be extended with a mutex qualifier for multiple-monitor calls, no example of this feature could be found.
    1278 The capability to acquire multiple locks before entering a critical section is called \emph{\textbf{bulk-acq}}.
    1279 In practice, writing multi-locking routines that do not lead to deadlocks is tricky.
    1280 Having language support for such a feature is therefore a significant asset for \CFA.
    1281 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.
    1282 This consistent ordering means acquiring multiple monitors is safe from deadlock when using \textbf{bulk-acq}.
    1283 However, users can still force the acquiring order.
    1284 For example, notice which routines use @mutex@/@nomutex@ and how this affects acquiring order:
    1285 \begin{cfa}
    1286 void foo(A& mutex a, B& mutex b) { // acquire a & b
     887\end{cfacode}
     888While 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:
     889\begin{cfacode}
     890void foo(A& mutex a, B& mutex b) { //acquire a & b
    1287891        ...
    1288892}
    1289893
    1290 void bar(A& mutex a, B& /*nomutex*/ b) { // acquire a
    1291         ... foo(a, b); ... // acquire b
    1292 }
    1293 
    1294 void baz(A& /*nomutex*/ a, B& mutex b) { // acquire b
    1295         ... foo(a, b); ... // acquire a
    1296 }
    1297 \end{cfa}
    1298 The \textbf{multi-acq} monitor lock allows a monitor lock to be acquired by both @bar@ or @baz@ and acquired again in @foo@.
    1299 In the calls to @bar@ and @baz@ the monitors are acquired in opposite order.
    1300 
    1301 However, such use leads to lock acquiring order problems.
    1302 In the example above, the user uses implicit ordering in the case of function @foo@ but explicit ordering in the case of @bar@ and @baz@.
    1303 This subtle difference means that calling these routines concurrently may lead to deadlock and is therefore undefined behaviour.
    1304 As shown~\cite{Lister77}, solving this problem requires:
     894void bar(A& mutex a, B& /*nomutex*/ b) { //acquire a
     895        ... foo(a, b); ... //acquire b
     896}
     897
     898void baz(A& /*nomutex*/ a, B& mutex b) { //acquire b
     899        ... foo(a, b); ... //acquire a
     900}
     901\end{cfacode}
     902The \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.
     903
     904However, 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:
    1305905\begin{enumerate}
    1306906        \item Dynamically tracking the monitor-call order.
    1307907        \item Implement rollback semantics.
    1308908\end{enumerate}
    1309 While 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}.
    1310 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.
    1311 While \CFA provides only a partial solution, most systems provide no solution and the \CFA partial solution handles many useful cases.
     909While 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.
    1312910
    1313911For example, \textbf{multi-acq} and \textbf{bulk-acq} can be used together in interesting ways:
    1314 \begin{cfa}
     912\begin{cfacode}
    1315913monitor bank { ... };
    1316914
     
    1321919        deposit( yourbank, me2you );
    1322920}
    1323 \end{cfa}
    1324 This example shows a trivial solution to the bank-account transfer problem~\cite{BankTransfer}.
    1325 Without \textbf{multi-acq} and \textbf{bulk-acq}, the solution to this problem is much more involved and requires careful engineering.
    1326 
    1327 
    1328 \subsection{\protect\lstinline|mutex| statement} \label{mutex-stmt}
    1329 
    1330 The call semantics discussed above have one software engineering issue: only a routine can acquire the mutual-exclusion of a set of monitor. \CFA offers the @mutex@ statement to work around the need for unnecessary names, avoiding a major software engineering problem~\cite{2FTwoHardThings}.
    1331 Table \ref{f:mutex-stmt} shows an example of the @mutex@ statement, which introduces a new scope in which the mutual-exclusion of a set of monitor is acquired.
    1332 Beyond naming, the @mutex@ statement has no semantic difference from a routine call with @mutex@ parameters.
     921\end{cfacode}
     922This 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.
     923
     924\subsection{\code{mutex} statement} \label{mutex-stmt}
     925
     926The 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.
    1333927
    1334928\begin{table}
    1335929\begin{center}
    1336930\begin{tabular}{|c|c|}
    1337 function call & @mutex@ statement \\
     931function call & \code{mutex} statement \\
    1338932\hline
    1339 \begin{cfa}[tabsize=3]
     933\begin{cfacode}[tabsize=3]
    1340934monitor M {};
    1341935void foo( M & mutex m1, M & mutex m2 ) {
    1342         // critical section
     936        //critical section
    1343937}
    1344938
     
    1346940        foo( m1, m2 );
    1347941}
    1348 \end{cfa}&\begin{cfa}[tabsize=3]
     942\end{cfacode}&\begin{cfacode}[tabsize=3]
    1349943monitor M {};
    1350944void bar( M & m1, M & m2 ) {
    1351945        mutex(m1, m2) {
    1352                 // critical section
    1353         }
    1354 }
    1355 
    1356 
    1357 \end{cfa}
     946                //critical section
     947        }
     948}
     949
     950
     951\end{cfacode}
    1358952\end{tabular}
    1359953\end{center}
    1360 \caption{Regular call semantics vs. \protect\lstinline|mutex| statement}
    1361 \label{f:mutex-stmt}
     954\caption{Regular call semantics vs. \code{mutex} statement}
     955\label{lst:mutex-stmt}
    1362956\end{table}
    1363957
     
    1367961% ======================================================================
    1368962% ======================================================================
    1369 Once the call semantics are established, the next step is to establish data semantics.
    1370 Indeed, until now a monitor is used simply as a generic handle but in most cases monitors contain shared data.
    1371 This data should be intrinsic to the monitor declaration to prevent any accidental use of data without its appropriate protection.
    1372 For example, here is a complete version of the counter shown in section \ref{call}:
    1373 \begin{cfa}
     963Once 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}:
     964\begin{cfacode}
    1374965monitor counter_t {
    1375966        int value;
     
    1384975}
    1385976
    1386 // need for mutex is platform dependent here
     977//need for mutex is platform dependent here
    1387978void ?{}(int * this, counter_t & mutex cnt) {
    1388979        *this = (int)cnt;
    1389980}
    1390 \end{cfa}
    1391 
    1392 Like threads and coroutines, monitors are defined in terms of traits with some additional language support in the form of the @monitor@ keyword.
    1393 The monitor trait is:
    1394 \begin{cfa}
     981\end{cfacode}
     982
     983Like 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:
     984\begin{cfacode}
    1395985trait is_monitor(dtype T) {
    1396986        monitor_desc * get_monitor( T & );
    1397987        void ^?{}( T & mutex );
    1398988};
    1399 \end{cfa}
    1400 Note that the destructor of a monitor must be a @mutex@ routine to prevent deallocation while a thread is accessing the monitor.
    1401 As with any object, calls to a monitor, using @mutex@ or otherwise, is undefined behaviour after the destructor has run.
     989\end{cfacode}
     990Note 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.
    1402991
    1403992% ======================================================================
     
    1406995% ======================================================================
    1407996% ======================================================================
    1408 In addition to mutual exclusion, the monitors at the core of \CFA's concurrency can also be used to achieve synchronization.
    1409 With monitors, this capability is generally achieved with internal or external scheduling as in~\cite{Hoare74}.
    1410 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 (\ie with access to the shared state), while \textbf{external scheduling} means making the decision when entering the critical section (\ie without access to the shared state).
    1411 Since internal scheduling within a single monitor is mostly a solved problem, this paper concentrates on extending internal scheduling to multiple monitors.
    1412 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.
     997In 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 paper 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.
    1413998
    1414999First, here is a simple example of internal scheduling:
    14151000
    1416 \begin{cfa}
     1001\begin{cfacode}
    14171002monitor A {
    14181003        condition e;
     
    14211006void foo(A& mutex a1, A& mutex a2) {
    14221007        ...
    1423         // Wait for cooperation from bar()
     1008        //Wait for cooperation from bar()
    14241009        wait(a1.e);
    14251010        ...
     
    14271012
    14281013void bar(A& mutex a1, A& mutex a2) {
    1429         // Provide cooperation for foo()
     1014        //Provide cooperation for foo()
    14301015        ...
    1431         // Unblock foo
     1016        //Unblock foo
    14321017        signal(a1.e);
    14331018}
    1434 \end{cfa}
    1435 There are two details to note here.
    1436 First, @signal@ is a delayed operation; it only unblocks the waiting thread when it reaches the end of the critical section.
    1437 This semantics is needed to respect mutual-exclusion, \ie the signaller and signalled thread cannot be in the monitor simultaneously.
    1438 The alternative is to return immediately after the call to @signal@, which is significantly more restrictive.
    1439 Second, in \CFA, while it is common to store a @condition@ as a field of the monitor, a @condition@ variable can be stored/created independently of a monitor.
    1440 Here routine @foo@ waits for the @signal@ from @bar@ before making further progress, ensuring a basic ordering.
    1441 
    1442 An important aspect of the implementation is that \CFA does not allow barging, which means that once function @bar@ releases the monitor, @foo@ is guaranteed to be the next thread to acquire the monitor (unless some other thread waited on the same condition).
    1443 This guarantee offers the benefit of not having to loop around waits to recheck that a condition is met.
    1444 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.
    1445 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.
     1019\end{cfacode}
     1020There 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.
     1021
     1022An 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.
    14461023
    14471024% ======================================================================
     
    14501027% ======================================================================
    14511028% ======================================================================
    1452 It is easy to understand the problem of multi-monitor scheduling using a series of pseudo-code examples.
    1453 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.
    1454 Indeed, @wait@ statements always use the implicit condition variable as parameters and explicitly name the monitors (A and B) associated with the condition.
    1455 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.
    1456 The example below shows the simple case of having two threads (one for each column) and a single monitor A.
     1029It 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.
    14571030
    14581031\begin{multicols}{2}
    14591032thread 1
    1460 \begin{cfa}
     1033\begin{pseudo}
    14611034acquire A
    14621035        wait A
    14631036release A
    1464 \end{cfa}
     1037\end{pseudo}
    14651038
    14661039\columnbreak
    14671040
    14681041thread 2
    1469 \begin{cfa}
     1042\begin{pseudo}
    14701043acquire A
    14711044        signal A
    14721045release A
    1473 \end{cfa}
     1046\end{pseudo}
    14741047\end{multicols}
    1475 One thread acquires before waiting (atomically blocking and releasing A) and the other acquires before signalling.
    1476 It is important to note here that both @wait@ and @signal@ must be called with the proper monitor(s) already acquired.
    1477 This semantic is a logical requirement for barging prevention.
     1048One 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.
    14781049
    14791050A direct extension of the previous example is a \textbf{bulk-acq} version:
    14801051\begin{multicols}{2}
    1481 \begin{cfa}
     1052\begin{pseudo}
    14821053acquire A & B
    14831054        wait A & B
    14841055release A & B
    1485 \end{cfa}
     1056\end{pseudo}
    14861057\columnbreak
    1487 \begin{cfa}
     1058\begin{pseudo}
    14881059acquire A & B
    14891060        signal A & B
    14901061release A & B
    1491 \end{cfa}
     1062\end{pseudo}
    14921063\end{multicols}
    1493 \noindent This version uses \textbf{bulk-acq} (denoted using the {\sf\&} symbol), but the presence of multiple monitors does not add a particularly new meaning.
    1494 Synchronization happens between the two threads in exactly the same way and order.
    1495 The only difference is that mutual exclusion covers a group of monitors.
    1496 On the implementation side, handling multiple monitors does add a degree of complexity as the next few examples demonstrate.
    1497 
    1498 While 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.
    1499 For monitors, a well-known deadlock problem is the Nested Monitor Problem~\cite{Lister77}, which occurs when a @wait@ is made by a thread that holds more than one monitor.
    1500 For example, the following cfa-code runs into the nested-monitor problem:
     1064\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.
     1065
     1066While 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:
    15011067\begin{multicols}{2}
    1502 \begin{cfa}
     1068\begin{pseudo}
    15031069acquire A
    15041070        acquire B
     
    15061072        release B
    15071073release A
    1508 \end{cfa}
     1074\end{pseudo}
    15091075
    15101076\columnbreak
    15111077
    1512 \begin{cfa}
     1078\begin{pseudo}
    15131079acquire A
    15141080        acquire B
     
    15161082        release B
    15171083release A
    1518 \end{cfa}
     1084\end{pseudo}
    15191085\end{multicols}
    1520 \noindent The @wait@ only releases monitor @B@ so the signalling thread cannot acquire monitor @A@ to get to the @signal@.
    1521 Attempting release of all acquired monitors at the @wait@ introduces a different set of problems, such as releasing monitor @C@, which has nothing to do with the @signal@.
    1522 
    1523 However, for monitors as for locks, it is possible to write a program using nesting without encountering any problems if nesting is done correctly.
    1524 For example, the next cfa-code snippet acquires monitors {\sf A} then {\sf B} before waiting, while only acquiring {\sf B} when signalling, effectively avoiding the Nested Monitor Problem~\cite{Lister77}.
     1086\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}.
     1087
     1088However, 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}.
    15251089
    15261090\begin{multicols}{2}
    1527 \begin{cfa}
     1091\begin{pseudo}
    15281092acquire A
    15291093        acquire B
     
    15311095        release B
    15321096release A
    1533 \end{cfa}
     1097\end{pseudo}
    15341098
    15351099\columnbreak
    15361100
    1537 \begin{cfa}
     1101\begin{pseudo}
    15381102
    15391103acquire B
     
    15411105release B
    15421106
    1543 \end{cfa}
     1107\end{pseudo}
    15441108\end{multicols}
    15451109
     
    15521116% ======================================================================
    15531117
    1554 A larger example is presented to show complex issues for \textbf{bulk-acq} and its implementation options are analyzed.
    1555 Figure~\ref{f:int-bulk-cfa} shows an example where \textbf{bulk-acq} adds a significant layer of complexity to the internal signalling semantics, and listing \ref{f:int-bulk-cfa} shows the corresponding \CFA code to implement the cfa-code in listing \ref{f:int-bulk-cfa}.
    1556 For the purpose of translating the given cfa-code into \CFA-code, any method of introducing a monitor is acceptable, \eg @mutex@ parameters, global variables, pointer parameters, or using locals with the @mutex@ statement.
    1557 
    1558 \begin{figure}
     1118A 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.
     1119
     1120\begin{figure}[!t]
    15591121\begin{multicols}{2}
    15601122Waiting thread
    1561 \begin{cfa}[numbers=left]
     1123\begin{pseudo}[numbers=left]
    15621124acquire A
    1563         // Code Section 1
     1125        //Code Section 1
    15641126        acquire A & B
    1565                 // Code Section 2
     1127                //Code Section 2
    15661128                wait A & B
    1567                 // Code Section 3
     1129                //Code Section 3
    15681130        release A & B
    1569         // Code Section 4
     1131        //Code Section 4
    15701132release A
    1571 \end{cfa}
     1133\end{pseudo}
    15721134\columnbreak
    15731135Signalling thread
    1574 \begin{cfa}[numbers=left, firstnumber=10,escapechar=|]
     1136\begin{pseudo}[numbers=left, firstnumber=10,escapechar=|]
    15751137acquire A
    1576         // Code Section 5
     1138        //Code Section 5
    15771139        acquire A & B
    1578                 // Code Section 6
     1140                //Code Section 6
    15791141                |\label{line:signal1}|signal A & B
    1580                 // Code Section 7
     1142                //Code Section 7
    15811143        |\label{line:releaseFirst}|release A & B
    1582         // Code Section 8
     1144        //Code Section 8
    15831145|\label{line:lastRelease}|release A
    1584 \end{cfa}
     1146\end{pseudo}
    15851147\end{multicols}
    1586 \begin{cfa}[caption={Internal scheduling with \textbf{bulk-acq}},label={f:int-bulk-cfa}]
    1587 \end{cfa}
     1148\begin{cfacode}[caption={Internal scheduling with \textbf{bulk-acq}},label={lst:int-bulk-pseudo}]
     1149\end{cfacode}
    15881150\begin{center}
    1589 \begin{cfa}[xleftmargin=.4\textwidth]
     1151\begin{cfacode}[xleftmargin=.4\textwidth]
    15901152monitor A a;
    15911153monitor B b;
    15921154condition c;
    1593 \end{cfa}
     1155\end{cfacode}
    15941156\end{center}
    15951157\begin{multicols}{2}
    15961158Waiting thread
    1597 \begin{cfa}
     1159\begin{cfacode}
    15981160mutex(a) {
    1599         // Code Section 1
     1161        //Code Section 1
    16001162        mutex(a, b) {
    1601                 // Code Section 2
     1163                //Code Section 2
    16021164                wait(c);
    1603                 // Code Section 3
    1604         }
    1605         // Code Section 4
    1606 }
    1607 \end{cfa}
     1165                //Code Section 3
     1166        }
     1167        //Code Section 4
     1168}
     1169\end{cfacode}
    16081170\columnbreak
    16091171Signalling thread
    1610 \begin{cfa}
     1172\begin{cfacode}
    16111173mutex(a) {
    1612         // Code Section 5
     1174        //Code Section 5
    16131175        mutex(a, b) {
    1614                 // Code Section 6
     1176                //Code Section 6
    16151177                signal(c);
    1616                 // Code Section 7
    1617         }
    1618         // Code Section 8
    1619 }
    1620 \end{cfa}
     1178                //Code Section 7
     1179        }
     1180        //Code Section 8
     1181}
     1182\end{cfacode}
    16211183\end{multicols}
    1622 \begin{cfa}[caption={Equivalent \CFA code for listing \ref{f:int-bulk-cfa}},label={f:int-bulk-cfa}]
    1623 \end{cfa}
     1184\begin{cfacode}[caption={Equivalent \CFA code for listing \ref{lst:int-bulk-pseudo}},label={lst:int-bulk-cfa}]
     1185\end{cfacode}
    16241186\begin{multicols}{2}
    16251187Waiter
    1626 \begin{cfa}[numbers=left]
     1188\begin{pseudo}[numbers=left]
    16271189acquire A
    16281190        acquire A & B
     
    16301192        release A & B
    16311193release A
    1632 \end{cfa}
     1194\end{pseudo}
    16331195
    16341196\columnbreak
    16351197
    16361198Signaller
    1637 \begin{cfa}[numbers=left, firstnumber=6,escapechar=|]
     1199\begin{pseudo}[numbers=left, firstnumber=6,escapechar=|]
    16381200acquire A
    16391201        acquire A & B
    16401202                signal A & B
    16411203        release A & B
    1642         |\label{line:secret}|// Secretly keep B here
     1204        |\label{line:secret}|//Secretly keep B here
    16431205release A
    1644 // Wakeup waiter and transfer A & B
    1645 \end{cfa}
     1206//Wakeup waiter and transfer A & B
     1207\end{pseudo}
    16461208\end{multicols}
    1647 \begin{cfa}[caption={Figure~\ref{f:int-bulk-cfa}, with delayed signalling comments},label={f:int-secret}]
    1648 \end{cfa}
     1209\begin{cfacode}[caption={Listing \ref{lst:int-bulk-pseudo}, with delayed signalling comments},label={lst:int-secret}]
     1210\end{cfacode}
    16491211\end{figure}
    16501212
    1651 The complexity begins at code sections 4 and 8 in listing \ref{f:int-bulk-cfa}, which are where the existing semantics of internal scheduling needs to be extended for multiple monitors.
    1652 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 cfa-code.
    1653 When the signaller thread reaches the location where it should ``release @A & B@'' (listing \ref{f:int-bulk-cfa} line \ref{line:releaseFirst}), it must actually transfer ownership of monitor @B@ to the waiting thread.
    1654 This ownership transfer is required in order to prevent barging into @B@ by another thread, since both the signalling and signalled threads still need monitor @A@.
    1655 There are three options:
     1213The 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:
    16561214
    16571215\subsubsection{Delaying Signals}
    1658 The 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.
    1659 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.
    1660 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.
    1661 This solution releases the monitors once every monitor in a group can be released.
    1662 However, since some monitors are never released (\eg the monitor of a thread), this interpretation means a group might never be released.
    1663 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.
    1664 
    1665 However, listing \ref{f:int-secret} shows this solution can become much more complicated depending on what is executed while secretly holding B at line \ref{line:secret}, while avoiding the need to transfer ownership of a subset of the condition monitors.
    1666 Figure~\ref{f:dependency} shows a slightly different example where a third thread is waiting on monitor @A@, using a different condition variable.
    1667 Because the third thread is signalled when secretly holding @B@, the goal  becomes unreachable.
    1668 Depending on the order of signals (listing \ref{f:dependency} line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen:
    1669 
    1670 \paragraph{Case 1: thread $\alpha$ goes first.} In this case, the problem is that monitor @A@ needs to be passed to thread $\beta$ when thread $\alpha$ is done with it.
    1671 \paragraph{Case 2: thread $\beta$ goes first.} In this case, the problem is that monitor @B@ needs to be retained and passed to thread $\alpha$ along with monitor @A@, which can be done directly or possibly using thread $\beta$ as an intermediate.
     1216The 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.
     1217
     1218However, 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:
     1219
     1220\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.
     1221\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.
    16721222\\
    16731223
    1674 Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order.
    1675 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{f:dependency}.
     1224Note 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}.
    16761225
    16771226In 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.
     
    16831232\begin{multicols}{3}
    16841233Thread $\alpha$
    1685 \begin{cfa}[numbers=left, firstnumber=1]
     1234\begin{pseudo}[numbers=left, firstnumber=1]
    16861235acquire A
    16871236        acquire A & B
     
    16891238        release A & B
    16901239release A
    1691 \end{cfa}
     1240\end{pseudo}
    16921241\columnbreak
    16931242Thread $\gamma$
    1694 \begin{cfa}[numbers=left, firstnumber=6, escapechar=|]
     1243\begin{pseudo}[numbers=left, firstnumber=6, escapechar=|]
    16951244acquire A
    16961245        acquire A & B
     
    16991248        |\label{line:signal-a}|signal A
    17001249|\label{line:release-a}|release A
    1701 \end{cfa}
     1250\end{pseudo}
    17021251\columnbreak
    17031252Thread $\beta$
    1704 \begin{cfa}[numbers=left, firstnumber=12, escapechar=|]
     1253\begin{pseudo}[numbers=left, firstnumber=12, escapechar=|]
    17051254acquire A
    17061255        wait A
    17071256|\label{line:release-aa}|release A
    1708 \end{cfa}
     1257\end{pseudo}
    17091258\end{multicols}
    1710 \begin{cfa}[caption={Pseudo-code for the three thread example.},label={f:dependency}]
    1711 \end{cfa}
     1259\begin{cfacode}[caption={Pseudo-code for the three thread example.},label={lst:dependency}]
     1260\end{cfacode}
    17121261\begin{center}
    17131262\input{dependency}
    17141263\end{center}
    1715 \caption{Dependency graph of the statements in listing \ref{f:dependency}}
     1264\caption{Dependency graph of the statements in listing \ref{lst:dependency}}
    17161265\label{fig:dependency}
    17171266\end{figure}
    17181267
    1719 In listing \ref{f:int-bulk-cfa}, there is a solution that satisfies both barging prevention and mutual exclusion.
    1720 If ownership of both monitors is transferred to the waiter when the signaller releases @A & B@ and then the waiter transfers back ownership of @A@ back to the signaller when it releases it, then the problem is solved (@B@ is no longer in use at this point).
    1721 Dynamically finding the correct order is therefore the second possible solution.
    1722 The problem is effectively resolving a dependency graph of ownership requirements.
    1723 Here even the simplest of code snippets requires two transfers and has a super-linear complexity.
    1724 This complexity can be seen in listing \ref{f:explosion}, which is just a direct extension to three monitors, requires at least three ownership transfer and has multiple solutions.
    1725 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.
     1268In 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.
    17261269\begin{figure}
    17271270\begin{multicols}{2}
    1728 \begin{cfa}
     1271\begin{pseudo}
    17291272acquire A
    17301273        acquire B
     
    17341277        release B
    17351278release A
    1736 \end{cfa}
     1279\end{pseudo}
    17371280
    17381281\columnbreak
    17391282
    1740 \begin{cfa}
     1283\begin{pseudo}
    17411284acquire A
    17421285        acquire B
     
    17461289        release B
    17471290release A
    1748 \end{cfa}
     1291\end{pseudo}
    17491292\end{multicols}
    1750 \begin{cfa}[caption={Extension to three monitors of listing \ref{f:int-bulk-cfa}},label={f:explosion}]
    1751 \end{cfa}
     1293\begin{cfacode}[caption={Extension to three monitors of listing \ref{lst:int-bulk-pseudo}},label={lst:explosion}]
     1294\end{cfacode}
    17521295\end{figure}
    17531296
    1754 Given the three threads example in listing \ref{f:dependency}, figure \ref{fig:dependency} shows the corresponding dependency graph that results, where every node is a statement of one of the three threads, and the arrows the dependency of that statement (\eg $\alpha1$ must happen before $\alpha2$).
    1755 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.
    1756 Resolving dependency graphs being a complex and expensive endeavour, this solution is not the preferred one.
     1297Given 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.
    17571298
    17581299\subsubsection{Partial Signalling} \label{partial-sig}
    1759 Finally, the solution that is chosen for \CFA is to use partial signalling.
    1760 Again using listing \ref{f:int-bulk-cfa}, the partial signalling solution transfers ownership of monitor @B@ at lines \ref{line:signal1} to the waiter but does not wake the waiting thread since it is still using monitor @A@.
    1761 Only when it reaches line \ref{line:lastRelease} does it actually wake up the waiting thread.
    1762 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.
    1763 This solution has a much simpler implementation than a dependency graph solving algorithms, which is why it was chosen.
    1764 Furthermore, after being fully implemented, this solution does not appear to have any significant downsides.
    1765 
    1766 Using partial signalling, listing \ref{f:dependency} can be solved easily:
     1300Finally, 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.
     1301
     1302Using partial signalling, listing \ref{lst:dependency} can be solved easily:
    17671303\begin{itemize}
    1768         \item When thread $\gamma$ reaches line \ref{line:release-ab} it transfers monitor @B@ to thread $\alpha$ and continues to hold monitor @A@.
    1769         \item When thread $\gamma$ reaches line \ref{line:release-a}  it transfers monitor @A@ to thread $\beta$  and wakes it up.
    1770         \item When thread $\beta$  reaches line \ref{line:release-aa} it transfers monitor @A@ to thread $\alpha$ and wakes it up.
     1304        \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}.
     1305        \item When thread $\gamma$ reaches line \ref{line:release-a}  it transfers monitor \code{A} to thread $\beta$  and wakes it up.
     1306        \item When thread $\beta$  reaches line \ref{line:release-aa} it transfers monitor \code{A} to thread $\alpha$ and wakes it up.
    17711307\end{itemize}
    17721308
     
    17781314\begin{table}
    17791315\begin{tabular}{|c|c|}
    1780 @signal@ & @signal_block@ \\
     1316\code{signal} & \code{signal_block} \\
    17811317\hline
    1782 \begin{cfa}[tabsize=3]
    1783 monitor DatingService {
    1784         // compatibility codes
     1318\begin{cfacode}[tabsize=3]
     1319monitor DatingService
     1320{
     1321        //compatibility codes
    17851322        enum{ CCodes = 20 };
    17861323
     
    17931330condition exchange;
    17941331
    1795 int girl(int phoneNo, int cfa) {
    1796         // no compatible boy ?
    1797         if(empty(boys[cfa])) {
    1798                 wait(girls[cfa]);               // wait for boy
    1799                 girlPhoneNo = phoneNo;          // make phone number available
    1800                 signal(exchange);               // wake boy from chair
    1801         } else {
    1802                 girlPhoneNo = phoneNo;          // make phone number available
    1803                 signal(boys[cfa]);              // wake boy
    1804                 wait(exchange);         // sit in chair
     1332int girl(int phoneNo, int ccode)
     1333{
     1334        //no compatible boy ?
     1335        if(empty(boys[ccode]))
     1336        {
     1337                //wait for boy
     1338                wait(girls[ccode]);
     1339
     1340                //make phone number available
     1341                girlPhoneNo = phoneNo;
     1342
     1343                //wake boy from chair
     1344                signal(exchange);
     1345        }
     1346        else
     1347        {
     1348                //make phone number available
     1349                girlPhoneNo = phoneNo;
     1350
     1351                //wake boy
     1352                signal(boys[ccode]);
     1353
     1354                //sit in chair
     1355                wait(exchange);
    18051356        }
    18061357        return boyPhoneNo;
    18071358}
    1808 int boy(int phoneNo, int cfa) {
    1809         // same as above
    1810         // with boy/girl interchanged
    1811 }
    1812 \end{cfa}&\begin{cfa}[tabsize=3]
    1813 monitor DatingService {
    1814 
    1815         enum{ CCodes = 20 };    // compatibility codes
     1359
     1360int boy(int phoneNo, int ccode)
     1361{
     1362        //same as above
     1363        //with boy/girl interchanged
     1364}
     1365\end{cfacode}&\begin{cfacode}[tabsize=3]
     1366monitor DatingService
     1367{
     1368        //compatibility codes
     1369        enum{ CCodes = 20 };
    18161370
    18171371        int girlPhoneNo;
     
    18211375condition girls[CCodes];
    18221376condition boys [CCodes];
    1823 // exchange is not needed
    1824 
    1825 int girl(int phoneNo, int cfa) {
    1826         // no compatible boy ?
    1827         if(empty(boys[cfa])) {
    1828                 wait(girls[cfa]);               // wait for boy
    1829                 girlPhoneNo = phoneNo;          // make phone number available
    1830                 signal(exchange);               // wake boy from chair
    1831         } else {
    1832                 girlPhoneNo = phoneNo;          // make phone number available
    1833                 signal_block(boys[cfa]);                // wake boy
    1834 
    1835                 // second handshake unnecessary
     1377//exchange is not needed
     1378
     1379int girl(int phoneNo, int ccode)
     1380{
     1381        //no compatible boy ?
     1382        if(empty(boys[ccode]))
     1383        {
     1384                //wait for boy
     1385                wait(girls[ccode]);
     1386
     1387                //make phone number available
     1388                girlPhoneNo = phoneNo;
     1389
     1390                //wake boy from chair
     1391                signal(exchange);
     1392        }
     1393        else
     1394        {
     1395                //make phone number available
     1396                girlPhoneNo = phoneNo;
     1397
     1398                //wake boy
     1399                signal_block(boys[ccode]);
     1400
     1401                //second handshake unnecessary
    18361402
    18371403        }
     
    18391405}
    18401406
    1841 int boy(int phoneNo, int cfa) {
    1842         // same as above
    1843         // with boy/girl interchanged
    1844 }
    1845 \end{cfa}
     1407int boy(int phoneNo, int ccode)
     1408{
     1409        //same as above
     1410        //with boy/girl interchanged
     1411}
     1412\end{cfacode}
    18461413\end{tabular}
    1847 \caption{Dating service example using \protect\lstinline|signal| and \protect\lstinline|signal_block|. }
     1414\caption{Dating service example using \code{signal} and \code{signal_block}. }
    18481415\label{tbl:datingservice}
    18491416\end{table}
    1850 An important note is that, until now, signalling a monitor was a delayed operation.
    1851 The ownership of the monitor is transferred only when the monitor would have otherwise been released, not at the point of the @signal@ statement.
    1852 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 @signal_block@ routine.
    1853 
    1854 The example in table \ref{tbl:datingservice} highlights the difference in behaviour.
    1855 As mentioned, @signal@ only transfers ownership once the current critical section exits; this behaviour requires additional synchronization when a two-way handshake is needed.
    1856 To avoid this explicit synchronization, the @condition@ type offers the @signal_block@ routine, which handles the two-way handshake as shown in the example.
    1857 This feature removes the need for a second condition variables and simplifies programming.
    1858 Like every other monitor semantic, @signal_block@ uses barging prevention, which means mutual-exclusion is baton-passed both on the front end and the back end of the call to @signal_block@, meaning no other thread can acquire the monitor either before or after the call.
     1417An 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.
     1418
     1419The 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.
    18591420
    18601421% ======================================================================
     
    18681429Internal Scheduling & External Scheduling & Go\\
    18691430\hline
    1870 \begin{uC++}[tabsize=3]
     1431\begin{ucppcode}[tabsize=3]
    18711432_Monitor Semaphore {
    18721433        condition c;
     
    18831444        }
    18841445}
    1885 \end{uC++}&\begin{uC++}[tabsize=3]
     1446\end{ucppcode}&\begin{ucppcode}[tabsize=3]
    18861447_Monitor Semaphore {
    18871448
     
    18981459        }
    18991460}
    1900 \end{uC++}&\begin{Go}[tabsize=3]
     1461\end{ucppcode}&\begin{gocode}[tabsize=3]
    19011462type MySem struct {
    19021463        inUse bool
     
    19181479        s.inUse = false
    19191480
    1920         // This actually deadlocks
    1921         // when single thread
     1481        //This actually deadlocks
     1482        //when single thread
    19221483        s.c <- false
    19231484}
    1924 \end{Go}
     1485\end{gocode}
    19251486\end{tabular}
    19261487\caption{Different forms of scheduling.}
    19271488\label{tbl:sched}
    19281489\end{table}
    1929 This method is more constrained and explicit, which helps users reduce the non-deterministic nature of concurrency.
    1930 Indeed, as the following examples demonstrate, external scheduling allows users to wait for events from other threads without the concern of unrelated events occurring.
    1931 External scheduling can generally be done either in terms of control flow (\eg Ada with @accept@, \uC with @_Accept@) or in terms of data (\eg Go with channels).
    1932 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.
    1933 Two challenges specific to \CFA arise when trying to add external scheduling with loose object definitions and multiple-monitor routines.
    1934 The previous example shows a simple use @_Accept@ versus @wait@/@signal@ and its advantages.
    1935 Note that while other languages often use @accept@/@select@ as the core external scheduling keyword, \CFA uses @waitfor@ to prevent name collisions with existing socket \textbf{api}s.
    1936 
    1937 For the @P@ member above using internal scheduling, the call to @wait@ only guarantees that @V@ is the last routine to access the monitor, allowing a third routine, say @isInUse()@, acquire mutual exclusion several times while routine @P@ is waiting.
    1938 On the other hand, external scheduling guarantees that while routine @P@ is waiting, no other routine than @V@ can acquire the monitor.
     1490This 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.
     1491
     1492For 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.
    19391493
    19401494% ======================================================================
     
    19431497% ======================================================================
    19441498% ======================================================================
    1945 In \uC, a monitor class declaration includes an exhaustive list of monitor operations.
    1946 Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user:
    1947 
    1948 \begin{cfa}
     1499In \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:
     1500
     1501\begin{cfacode}
    19491502monitor A {};
    19501503
    19511504void f(A & mutex a);
    19521505void g(A & mutex a) {
    1953         waitfor(f); // Obvious which f() to wait for
    1954 }
    1955 
    1956 void f(A & mutex a, int); // New different F added in scope
     1506        waitfor(f); //Obvious which f() to wait for
     1507}
     1508
     1509void f(A & mutex a, int); //New different F added in scope
    19571510void h(A & mutex a) {
    1958         waitfor(f); // Less obvious which f() to wait for
    1959 }
    1960 \end{cfa}
    1961 
    1962 Furthermore, external scheduling is an example where implementation constraints become visible from the interface.
    1963 Here is the cfa-code for the entering phase of a monitor:
     1511        waitfor(f); //Less obvious which f() to wait for
     1512}
     1513\end{cfacode}
     1514
     1515Furthermore, 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:
    19641516\begin{center}
    19651517\begin{tabular}{l}
    1966 \begin{cfa}
     1518\begin{pseudo}
    19671519        if monitor is free
    19681520                enter
     
    19731525        else
    19741526                block
    1975 \end{cfa}
     1527\end{pseudo}
    19761528\end{tabular}
    19771529\end{center}
    1978 For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions.
    1979 However, a fast check for @monitor accepts me@ is much harder to implement depending on the constraints put on the monitors.
    1980 Indeed, monitors are often expressed as an entry queue and some acceptor queue as in Figure~\ref{fig:ClassicalMonitor}.
     1530For 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}.
    19811531
    19821532\begin{figure}
     
    19941544\end{figure}
    19951545
    1996 There are other alternatives to these pictures, but in the case of the left picture, implementing a fast accept check is relatively easy.
    1997 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 (\eg 128) of mutex members.
    1998 This approach requires a unique dense ordering of routines with an upper-bound and that ordering must be consistent across translation units.
    1999 For OO languages these constraints are common, since objects only offer adding member routines consistently across translation units via inheritance.
    2000 However, in \CFA users can extend objects with mutex routines that are only visible in certain translation unit.
    2001 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.
     1546There 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.
    20021547
    20031548The alternative is to alter the implementation as in Figure~\ref{fig:BulkMonitor}.
    2004 Here, the mutex routine called is associated with a thread on the entry queue while a list of acceptable routines is kept separate.
    2005 Generating a mask dynamically means that the storage for the mask information can vary between calls to @waitfor@, allowing for more flexibility and extensions.
    2006 Storing an array of accepted function pointers replaces the single instruction bitmask comparison with dereferencing a pointer followed by a linear search.
    2007 Furthermore, supporting nested external scheduling (\eg listing \ref{f:nest-ext}) may now require additional searches for the @waitfor@ statement to check if a routine is already queued.
     1549Here, 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.
    20081550
    20091551\begin{figure}
    2010 \begin{cfa}[caption={Example of nested external scheduling},label={f:nest-ext}]
     1552\begin{cfacode}[caption={Example of nested external scheduling},label={lst:nest-ext}]
    20111553monitor M {};
    20121554void foo( M & mutex a ) {}
    20131555void bar( M & mutex b ) {
    2014         // Nested in the waitfor(bar, c) call
     1556        //Nested in the waitfor(bar, c) call
    20151557        waitfor(foo, b);
    20161558}
     
    20191561}
    20201562
    2021 \end{cfa}
     1563\end{cfacode}
    20221564\end{figure}
    20231565
    2024 Note 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.
    2025 These details are omitted from the picture for the sake of simplicity.
    2026 
    2027 At this point, a decision must be made between flexibility and performance.
    2028 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.
    2029 Here, however, the cost of flexibility cannot be trivially removed.
    2030 In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be  hard to write.
    2031 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.
     1566Note 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.
     1567
     1568At 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.
    20321569
    20331570% ======================================================================
     
    20371574% ======================================================================
    20381575
    2039 External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax.
    2040 Even in the simplest possible case, some new semantics needs to be established:
    2041 \begin{cfa}
     1576External 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:
     1577\begin{cfacode}
    20421578monitor M {};
    20431579
     
    20451581
    20461582void g(M & mutex b, M & mutex c) {
    2047         waitfor(f); // two monitors M => unknown which to pass to f(M & mutex)
    2048 }
    2049 \end{cfa}
     1583        waitfor(f); //two monitors M => unknown which to pass to f(M & mutex)
     1584}
     1585\end{cfacode}
    20501586The obvious solution is to specify the correct monitor as follows:
    20511587
    2052 \begin{cfa}
     1588\begin{cfacode}
    20531589monitor M {};
    20541590
     
    20561592
    20571593void g(M & mutex a, M & mutex b) {
    2058         // wait for call to f with argument b
     1594        //wait for call to f with argument b
    20591595        waitfor(f, b);
    20601596}
    2061 \end{cfa}
    2062 This syntax is unambiguous.
    2063 Both locks are acquired and kept by @g@.
    2064 When routine @f@ is called, the lock for monitor @b@ is temporarily transferred from @g@ to @f@ (while @g@ still holds lock @a@).
    2065 This behaviour can be extended to the multi-monitor @waitfor@ statement as follows.
    2066 
    2067 \begin{cfa}
     1597\end{cfacode}
     1598This 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.
     1599
     1600\begin{cfacode}
    20681601monitor M {};
    20691602
     
    20711604
    20721605void g(M & mutex a, M & mutex b) {
    2073         // wait for call to f with arguments a and b
     1606        //wait for call to f with arguments a and b
    20741607        waitfor(f, a, b);
    20751608}
    2076 \end{cfa}
    2077 
    2078 Note that the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired in the routine. @waitfor@ used in any other context is undefined behaviour.
     1609\end{cfacode}
     1610
     1611Note 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.
    20791612
    20801613An important behaviour to note is when a set of monitors only match partially:
    20811614
    2082 \begin{cfa}
     1615\begin{cfacode}
    20831616mutex struct A {};
    20841617
     
    20931626
    20941627void foo() {
    2095         g(a1, b); // block on accept
     1628        g(a1, b); //block on accept
    20961629}
    20971630
    20981631void bar() {
    2099         f(a2, b); // fulfill cooperation
    2100 }
    2101 \end{cfa}
    2102 While 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.
    2103 In both cases, partially matching monitor sets does not wakeup the waiting thread.
    2104 It is also important to note that in the case of external scheduling the order of parameters is irrelevant; @waitfor(f,a,b)@ and @waitfor(f,b,a)@ are indistinguishable waiting condition.
    2105 
    2106 % ======================================================================
    2107 % ======================================================================
    2108 \subsection{\protect\lstinline|waitfor| Semantics}
    2109 % ======================================================================
    2110 % ======================================================================
    2111 
    2112 Syntactically, the @waitfor@ statement takes a function identifier and a set of monitors.
    2113 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 @waitfor@ statement.
    2114 It checks that the set of monitors passed in matches the requirements for a function call.
    2115 Figure~\ref{f:waitfor} shows various usages of the waitfor statement and which are acceptable.
    2116 The choice of the function type is made ignoring any non-@mutex@ parameter.
    2117 One limitation of the current implementation is that it does not handle overloading, but overloading is possible.
     1632        f(a2, b); //fulfill cooperation
     1633}
     1634\end{cfacode}
     1635While 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.
     1636
     1637% ======================================================================
     1638% ======================================================================
     1639\subsection{\code{waitfor} Semantics}
     1640% ======================================================================
     1641% ======================================================================
     1642
     1643Syntactically, 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.
    21181644\begin{figure}
    2119 \begin{cfa}[caption={Various correct and incorrect uses of the waitfor statement},label={f:waitfor}]
     1645\begin{cfacode}[caption={Various correct and incorrect uses of the waitfor statement},label={lst:waitfor}]
    21201646monitor A{};
    21211647monitor B{};
     
    21311657        void (*fp)( A & mutex ) = f1;
    21321658
    2133         waitfor(f1, a1);     // Correct : 1 monitor case
    2134         waitfor(f2, a1, b1); // Correct : 2 monitor case
    2135         waitfor(f3, a1);     // Correct : non-mutex arguments are ignored
    2136         waitfor(f1, *ap);    // Correct : expression as argument
    2137 
    2138         waitfor(f1, a1, b1); // Incorrect : Too many mutex arguments
    2139         waitfor(f2, a1);     // Incorrect : Too few mutex arguments
    2140         waitfor(f2, a1, a2); // Incorrect : Mutex arguments don't match
    2141         waitfor(f1, 1);      // Incorrect : 1 not a mutex argument
    2142         waitfor(f9, a1);     // Incorrect : f9 function does not exist
    2143         waitfor(*fp, a1 );   // Incorrect : fp not an identifier
    2144         waitfor(f4, a1);     // Incorrect : f4 ambiguous
    2145 
    2146         waitfor(f2, a1, b2); // Undefined behaviour : b2 not mutex
    2147 }
    2148 \end{cfa}
     1659        waitfor(f1, a1);     //Correct : 1 monitor case
     1660        waitfor(f2, a1, b1); //Correct : 2 monitor case
     1661        waitfor(f3, a1);     //Correct : non-mutex arguments are ignored
     1662        waitfor(f1, *ap);    //Correct : expression as argument
     1663
     1664        waitfor(f1, a1, b1); //Incorrect : Too many mutex arguments
     1665        waitfor(f2, a1);     //Incorrect : Too few mutex arguments
     1666        waitfor(f2, a1, a2); //Incorrect : Mutex arguments don't match
     1667        waitfor(f1, 1);      //Incorrect : 1 not a mutex argument
     1668        waitfor(f9, a1);     //Incorrect : f9 function does not exist
     1669        waitfor(*fp, a1 );   //Incorrect : fp not an identifier
     1670        waitfor(f4, a1);     //Incorrect : f4 ambiguous
     1671
     1672        waitfor(f2, a1, b2); //Undefined behaviour : b2 not mutex
     1673}
     1674\end{cfacode}
    21491675\end{figure}
    21501676
    2151 Finally, for added flexibility, \CFA supports constructing a complex @waitfor@ statement using the @or@, @timeout@ and @else@.
    2152 Indeed, multiple @waitfor@ clauses can be chained together using @or@; this chain forms a single statement that uses baton pass to any function that fits one of the function+monitor set passed in.
    2153 To enable users to tell which accepted function executed, @waitfor@s are followed by a statement (including the null statement @;@) or a compound statement, which is executed after the clause is triggered.
    2154 A @waitfor@ chain can also be followed by a @timeout@, to signify an upper bound on the wait, or an @else@, to signify that the call should be non-blocking, which checks for a matching function call already arrived and otherwise continues.
    2155 Any and all of these clauses can be preceded by a @when@ condition to dynamically toggle the accept clauses on or off based on some current state.
    2156 Figure~\ref{f:waitfor2} demonstrates several complex masks and some incorrect ones.
     1677Finally, 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.
    21571678
    21581679\begin{figure}
    2159 \lstset{language=CFA,deletedelim=**[is][]{`}{`}}
    2160 \begin{cfa}
     1680\begin{cfacode}[caption={Various correct and incorrect uses of the or, else, and timeout clause around a waitfor statement},label={lst:waitfor2}]
    21611681monitor A{};
    21621682
     
    21651685
    21661686void foo( A & mutex a, bool b, int t ) {
    2167         waitfor(f1, a);                                                 $\C{// Correct : blocking case}$
    2168 
    2169         waitfor(f1, a) {                                                $\C{// Correct : block with statement}$
     1687        //Correct : blocking case
     1688        waitfor(f1, a);
     1689
     1690        //Correct : block with statement
     1691        waitfor(f1, a) {
    21701692                sout | "f1" | endl;
    21711693        }
    2172         waitfor(f1, a) {                                                $\C{// Correct : block waiting for f1 or f2}$
     1694
     1695        //Correct : block waiting for f1 or f2
     1696        waitfor(f1, a) {
    21731697                sout | "f1" | endl;
    21741698        } or waitfor(f2, a) {
    21751699                sout | "f2" | endl;
    21761700        }
    2177         waitfor(f1, a); or else;                                $\C{// Correct : non-blocking case}$
    2178 
    2179         waitfor(f1, a) {                                                $\C{// Correct : non-blocking case}$
     1701
     1702        //Correct : non-blocking case
     1703        waitfor(f1, a); or else;
     1704
     1705        //Correct : non-blocking case
     1706        waitfor(f1, a) {
    21801707                sout | "blocked" | endl;
    21811708        } or else {
    21821709                sout | "didn't block" | endl;
    21831710        }
    2184         waitfor(f1, a) {                                                $\C{// Correct : block at most 10 seconds}$
     1711
     1712        //Correct : block at most 10 seconds
     1713        waitfor(f1, a) {
    21851714                sout | "blocked" | endl;
    21861715        } or timeout( 10`s) {
    21871716                sout | "didn't block" | endl;
    21881717        }
    2189         // Correct : block only if b == true if b == false, don't even make the call
     1718
     1719        //Correct : block only if b == true
     1720        //if b == false, don't even make the call
    21901721        when(b) waitfor(f1, a);
    21911722
    2192         // Correct : block only if b == true if b == false, make non-blocking call
     1723        //Correct : block only if b == true
     1724        //if b == false, make non-blocking call
    21931725        waitfor(f1, a); or when(!b) else;
    21941726
    2195         // Correct : block only of t > 1
     1727        //Correct : block only of t > 1
    21961728        waitfor(f1, a); or when(t > 1) timeout(t); or else;
    21971729
    2198         // Incorrect : timeout clause is dead code
     1730        //Incorrect : timeout clause is dead code
    21991731        waitfor(f1, a); or timeout(t); or else;
    22001732
    2201         // Incorrect : order must be waitfor [or waitfor... [or timeout] [or else]]
     1733        //Incorrect : order must be
     1734        //waitfor [or waitfor... [or timeout] [or else]]
    22021735        timeout(t); or waitfor(f1, a); or else;
    22031736}
    2204 \end{cfa}
    2205 \caption{Correct and incorrect uses of the or, else, and timeout clause around a waitfor statement}
    2206 \label{f:waitfor2}
     1737\end{cfacode}
    22071738\end{figure}
    22081739
     
    22121743% ======================================================================
    22131744% ======================================================================
    2214 An interesting use for the @waitfor@ statement is destructor semantics.
    2215 Indeed, the @waitfor@ statement can accept any @mutex@ routine, which includes the destructor (see section \ref{data}).
    2216 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.
    2217 The simplest approach is to disallow @waitfor@ on a destructor.
    2218 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 @mutex@ routine, similarly to how a condition is signalled.
     1745An 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.
    22191746\begin{figure}
    2220 \begin{cfa}[caption={Example of an executor which executes action in series until the destructor is called.},label={f:dtor-order}]
     1747\begin{cfacode}[caption={Example of an executor which executes action in series until the destructor is called.},label={lst:dtor-order}]
    22211748monitor Executer {};
    22221749struct  Action;
     
    22321759        }
    22331760}
    2234 \end{cfa}
     1761\end{cfacode}
    22351762\end{figure}
    2236 For example, listing \ref{f:dtor-order} shows an example of an executor with an infinite loop, which waits for the destructor to break out of this loop.
    2237 Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction.
     1763For 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.
    22381764
    22391765
     
    22461772% #       #     # #     # #     # ####### ####### ####### ####### ###  #####  #     #
    22471773\section{Parallelism}
    2248 Historically, computer performance was about processor speeds and instruction counts.
    2249 However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}.
    2250 In this decade, it is no longer reasonable to create a high-performance application without caring about parallelism.
    2251 Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization.
    2252 The lowest-level approach of parallelism is to use \textbf{kthread} in combination with semantics like @fork@, @join@, \etc.
    2253 However, since these have significant costs and limitations, \textbf{kthread} are now mostly used as an implementation tool rather than a user oriented one.
    2254 There are several alternatives to solve these issues that all have strengths and weaknesses.
    2255 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.
     1774Historically, 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.
    22561775
    22571776\section{Paradigms}
    22581777\subsection{User-Level Threads}
    2259 A direct improvement on the \textbf{kthread} approach is to use \textbf{uthread}.
    2260 These threads offer most of the same features that the operating system already provides but can be used on a much larger scale.
    2261 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.
    2262 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.
    2263 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.
     1778A 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.
    22641779
    22651780Examples of languages that support \textbf{uthread} are Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
    22661781
    22671782\subsection{Fibers : User-Level Threads Without Preemption} \label{fibers}
    2268 A popular variant of \textbf{uthread} is what is often referred to as \textbf{fiber}.
    2269 However, \textbf{fiber} do not present meaningful semantic differences with \textbf{uthread}.
    2270 The significant difference between \textbf{uthread} and \textbf{fiber} is the lack of \textbf{preemption} in the latter.
    2271 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.
    2272 Therefore this proposal largely ignores fibers.
     1783A 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.
    22731784
    22741785An example of a language that uses fibers is Go~\cite{Go}
    22751786
    22761787\subsection{Jobs and Thread Pools}
    2277 An approach on the opposite end of the spectrum is to base parallelism on \textbf{pool}.
    2278 Indeed, \textbf{pool} offer limited flexibility but at the benefit of a simpler user interface.
    2279 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.
    2280 This approach means users need not worry about concurrency but significantly limit the interaction that can occur among jobs.
    2281 Indeed, any \textbf{job} that blocks also block the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably.
    2282 It can be argued that a solution to this problem is to use more workers than available cores.
    2283 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.
     1788An 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.
    22841789
    22851790The gold standard of this implementation is Intel's TBB library~\cite{TBB}.
    22861791
    22871792\subsection{Paradigm Performance}
    2288 While 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.
    2289 Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload.
    2290 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 (\ie no thread stack per job).
    2291 However, interactions among jobs can easily exacerbate contention.
    2292 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.
    2293 Finally, if the units of uninterrupted work are large, enough the paradigm choice is largely amortized by the actual work done.
     1793While 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.
    22941794
    22951795\section{The \protect\CFA\ Kernel : Processors, Clusters and Threads}\label{kernel}
    2296 A \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}.
    2297 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.
    2298 A \textbf{cfacluster} also offers a pluggable scheduler that can optimize the workload generated by the \textbf{uthread}.
    2299 
    2300 \textbf{cfacluster} have not been fully implemented in the context of this paper.
    2301 Currently \CFA only supports one \textbf{cfacluster}, the initial one.
     1796A \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}.
     1797
     1798\textbf{cfacluster} have not been fully implemented in the context of this paper. Currently \CFA only supports one \textbf{cfacluster}, the initial one.
    23021799
    23031800\subsection{Future Work: Machine Setup}\label{machine}
    2304 While this was not done in the context of this paper, another important aspect of clusters is affinity.
    2305 While many common desktop and laptop PCs have homogeneous CPUs, other devices often have more heterogeneous setups.
    2306 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.
    2307 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.
     1801While this was not done in the context of this paper, 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.
    23081802
    23091803\subsection{Paradigms}\label{cfaparadigms}
    2310 Given these building blocks, it is possible to reproduce all three of the popular paradigms.
    2311 Indeed, \textbf{uthread} is the default paradigm in \CFA.
    2312 However, disabling \textbf{preemption} on the \textbf{cfacluster} means \textbf{cfathread} effectively become \textbf{fiber}.
    2313 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.
    2314 Finally, it is possible to build executors for thread pools from \textbf{uthread} or \textbf{fiber}, which includes specialized jobs like actors~\cite{Actors}.
     1804Given 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}.
    23151805
    23161806
    23171807
    23181808\section{Behind the Scenes}
    2319 There are several challenges specific to \CFA when implementing concurrency.
    2320 These challenges are a direct result of \textbf{bulk-acq} and loose object definitions.
    2321 These two constraints are the root cause of most design decisions in the implementation.
    2322 Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs.
    2323 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.
    2324 This extra goal means that memory management is a constant concern in the design of the system.
    2325 
    2326 The main memory concern for concurrency is queues.
    2327 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.
    2328 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.
    2329 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.
    2330 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.
    2331 The threads and the condition both have a fixed amount of memory, while @mutex@ routines and blocking calls allow for an unbound amount, within the stack size.
     1809There 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.
     1810
     1811The 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.
    23321812
    23331813Note that since the major contributions of this paper are extending monitor semantics to \textbf{bulk-acq} and loose object definitions, any challenges that are not resulting of these characteristics of \CFA are considered as solved problems and therefore not discussed.
     
    23391819% ======================================================================
    23401820
    2341 The first step towards the monitor implementation is simple @mutex@ routines.
    2342 In the single monitor case, mutual-exclusion is done using the entry/exit procedure in listing \ref{f:entry1}.
    2343 The entry/exit procedures do not have to be extended to support multiple monitors.
    2344 Indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlock~\cite{Havender68}.
    2345 In \CFA, ordering of monitor acquisition relies on memory ordering.
    2346 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.
    2347 When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer array and sorted based on pointer values.
    2348 This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively.
     1821The 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.
    23491822\begin{figure}
    23501823\begin{multicols}{2}
    23511824Entry
    2352 \begin{cfa}
     1825\begin{pseudo}
    23531826if monitor is free
    23541827        enter
     
    23581831        block
    23591832increment recursions
    2360 \end{cfa}
     1833\end{pseudo}
    23611834\columnbreak
    23621835Exit
    2363 \begin{cfa}
     1836\begin{pseudo}
    23641837decrement recursion
    23651838if recursion == 0
    23661839        if entry queue not empty
    23671840                wake-up thread
    2368 \end{cfa}
     1841\end{pseudo}
    23691842\end{multicols}
    2370 \begin{cfa}[caption={Initial entry and exit routine for monitors},label={f:entry1}]
    2371 \end{cfa}
     1843\begin{pseudo}[caption={Initial entry and exit routine for monitors},label={lst:entry1}]
     1844\end{pseudo}
    23721845\end{figure}
    23731846
    23741847\subsection{Details: Interaction with polymorphism}
    2375 Depending 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.
    2376 However, it is shown that entry-point locking solves most of the issues.
    2377 
    2378 First of all, interaction between @otype@ polymorphism (see Section~\ref{s:ParametricPolymorphism}) and monitors is impossible since monitors do not support copying.
    2379 Therefore, the main question is how to support @dtype@ polymorphism.
    2380 It is important to present the difference between the two acquiring options: \textbf{callsite-locking} and entry-point locking, \ie acquiring the monitors before making a mutex routine-call or as the first operation of the mutex routine-call.
    2381 For example:
    2382 \begin{table}
     1848Depending 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.
     1849
     1850First 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:
     1851\begin{table}[H]
    23831852\begin{center}
    23841853\begin{tabular}{|c|c|c|}
    23851854Mutex & \textbf{callsite-locking} & \textbf{entry-point-locking} \\
    2386 call & cfa-code & cfa-code \\
     1855call & pseudo-code & pseudo-code \\
    23871856\hline
    2388 \begin{cfa}[tabsize=3]
     1857\begin{cfacode}[tabsize=3]
    23891858void foo(monitor& mutex a){
    23901859
    2391         // Do Work
     1860        //Do Work
    23921861        //...
    23931862
     
    24001869
    24011870}
    2402 \end{cfa} & \begin{cfa}[tabsize=3]
     1871\end{cfacode} & \begin{pseudo}[tabsize=3]
    24031872foo(& a) {
    24041873
    2405         // Do Work
     1874        //Do Work
    24061875        //...
    24071876
     
    24141883        release(a);
    24151884}
    2416 \end{cfa} & \begin{cfa}[tabsize=3]
     1885\end{pseudo} & \begin{pseudo}[tabsize=3]
    24171886foo(& a) {
    24181887        acquire(a);
    2419         // Do Work
     1888        //Do Work
    24201889        //...
    24211890        release(a);
     
    24281897
    24291898}
    2430 \end{cfa}
     1899\end{pseudo}
    24311900\end{tabular}
    24321901\end{center}
     
    24351904\end{table}
    24361905
    2437 Note the @mutex@ keyword relies on the type system, which means that in cases where a generic monitor-routine is desired, writing the mutex routine is possible with the proper trait, \eg:
    2438 \begin{cfa}
    2439 // Incorrect: T may not be monitor
     1906Note 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.:
     1907\begin{cfacode}
     1908//Incorrect: T may not be monitor
    24401909forall(dtype T)
    24411910void foo(T * mutex t);
    24421911
    2443 // Correct: this function only works on monitors (any monitor)
     1912//Correct: this function only works on monitors (any monitor)
    24441913forall(dtype T | is_monitor(T))
    24451914void bar(T * mutex t));
    2446 \end{cfa}
    2447 
    2448 Both entry point and \textbf{callsite-locking} are feasible implementations.
    2449 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.
    2450 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, \ie the function body.
    2451 For example, the monitor call can appear in the middle of an expression.
    2452 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.
     1915\end{cfacode}
     1916
     1917Both 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.
    24531918
    24541919% ======================================================================
     
    24581923% ======================================================================
    24591924
    2460 Figure \ref{fig:system1} shows a high-level picture if the \CFA runtime system in regards to concurrency.
    2461 Each component of the picture is explained in detail in the flowing sections.
     1925Figure \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.
    24621926
    24631927\begin{figure}
     
    24701934
    24711935\subsection{Processors}
    2472 Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically @pthread@s in the current implementation of \CFA.
    2473 Indeed, any parallelism must go through operating-system libraries.
    2474 However, \textbf{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism.
    2475 Indeed, processor \textbf{kthread} simply fetch a \textbf{uthread} from the scheduler and run it; they are effectively executers for user-threads.
    2476 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.
    2477 Processors internally use coroutines to take advantage of the existing context-switching semantics.
     1936Parallelism 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.
    24781937
    24791938\subsection{Stack Management}
    2480 One of the challenges of this system is to reduce the footprint as much as possible.
    2481 Specifically, all @pthread@s created also have a stack created with them, which should be used as much as possible.
    2482 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.
    2483 The exception to this rule is the Main Processor, \ie the initial \textbf{kthread} that is given to any program.
    2484 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.
     1939One 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.
    24851940
    24861941\subsection{Context Switching}
    2487 As 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.
    2488 To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific function call.
    2489 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.
    2490 Note that the instruction pointer can be left untouched since the context-switch is always inside the same function.
    2491 Threads, however, do not context-switch between each other directly.
    2492 They context-switch to the scheduler.
    2493 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.
    2494 Obviously, this doubles the context-switch cost because threads must context-switch to an intermediate stack.
    2495 The alternative 1-step context-switch uses the stack of the ``from'' thread to schedule and then context-switches directly to the ``to'' thread.
    2496 However, the performance of the 2-step context-switch is still superior to a @pthread_yield@ (see section \ref{results}).
    2497 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 @SwitchToFiber@~\cite{switchToWindows} routine).
    2498 This option is not currently present in \CFA, but the changes required to add it are strictly additive.
     1942As 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.
    24991943
    25001944\subsection{Preemption} \label{preemption}
    2501 Finally, an important aspect for any complete threading system is preemption.
    2502 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.
    2503 Indeed, preemption is desirable because it adds a degree of isolation among threads.
    2504 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.
    2505 Obviously, preemption is not optimal for every workload.
    2506 However any preemptive system can become a cooperative system by making the time slices extremely large.
    2507 Therefore, \CFA uses a preemptive threading system.
    2508 
    2509 Preemption in \CFA\footnote{Note that the implementation of preemption is strongly tied with the underlying threading system.
    2510 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.
    2511 Every processor keeps track of the current time and registers an expiration time with the preemption system.
    2512 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.
    2513 These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread.
    2514 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, \ie:
     1945Finally, 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.
     1946
     1947Preemption 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.:
    25151948\begin{quote}
    2516 A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
    2517 If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
     1949A 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.
    25181950SIGNAL(7) - Linux Programmer's Manual
    25191951\end{quote}
    25201952For 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.
    25211953
    2522 Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread.
    2523 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.
    2524 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.
    2525 As a result, a signal handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread).
    2526 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.
    2527 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.}.
    2528 However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel-alarm thread can cause deadlocks.
    2529 For this reason, the alarm thread is in a tight loop around a system call to @sigwaitinfo@, requiring very little CPU time for preemption.
    2530 One final detail about the alarm thread is how to wake it when additional communication is required (\eg on thread termination).
    2531 This unblocking is also done using {\tt SIGALRM}, but sent through the @pthread_sigqueue@.
    2532 Indeed, @sigwait@ can differentiate signals sent from @pthread_sigqueue@ from signals sent from alarms or the kernel.
     1954Now 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.
    25331955
    25341956\subsection{Scheduler}
    2535 Finally, an aspect that was not mentioned yet is the scheduling algorithm.
    2536 Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling.
    2537 Further discussion on scheduling is present in section \ref{futur:sched}.
     1957Finally, 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}.
    25381958
    25391959% ======================================================================
     
    25441964The following figure is the traditional illustration of a monitor (repeated from page~\pageref{fig:ClassicalMonitor} for convenience):
    25451965
    2546 \begin{figure}
     1966\begin{figure}[H]
    25471967\begin{center}
    25481968{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
     
    25511971\end{figure}
    25521972
    2553 This picture has several components, the two most important being the entry queue and the AS-stack.
    2554 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.
    2555 
    2556 For \CFA, this picture does not have support for blocking multiple monitors on a single condition.
    2557 To support \textbf{bulk-acq} two changes to this picture are required.
    2558 First, it is no longer helpful to attach the condition to \emph{a single} monitor.
    2559 Secondly, the thread waiting on the condition has to be separated across multiple monitors, seen in figure \ref{fig:monitor_cfa}.
    2560 
    2561 \begin{figure}
     1973This 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.
     1974
     1975For \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}.
     1976
     1977\begin{figure}[H]
    25621978\begin{center}
    25631979{\resizebox{0.8\textwidth}{!}{\input{int_monitor}}}
     
    25671983\end{figure}
    25681984
    2569 This picture and the proper entry and leave algorithms (see listing \ref{f:entry2}) is the fundamental implementation of internal scheduling.
    2570 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.
    2571 The thread is woken up when all the pieces have popped from the AS-stacks and made active.
    2572 In this picture, the threads are split into halves but this is only because there are two monitors.
    2573 For a specific signalling operation every monitor needs a piece of thread on its AS-stack.
    2574 
    2575 \begin{figure}
     1985This 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.
     1986
     1987\begin{figure}[b]
    25761988\begin{multicols}{2}
    25771989Entry
    2578 \begin{cfa}
     1990\begin{pseudo}
    25791991if monitor is free
    25801992        enter
     
    25851997increment recursion
    25861998
    2587 \end{cfa}
     1999\end{pseudo}
    25882000\columnbreak
    25892001Exit
    2590 \begin{cfa}
     2002\begin{pseudo}
    25912003decrement recursion
    25922004if recursion == 0
     
    25982010        if entry queue not empty
    25992011                wake-up thread
    2600 \end{cfa}
     2012\end{pseudo}
    26012013\end{multicols}
    2602 \begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling},label={f:entry2}]
    2603 \end{cfa}
     2014\begin{pseudo}[caption={Entry and exit routine for monitors with internal scheduling},label={lst:entry2}]
     2015\end{pseudo}
    26042016\end{figure}
    26052017
    2606 The solution discussed in \ref{intsched} can be seen in the exit routine of listing \ref{f:entry2}.
    2607 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.
    2608 This solution is deadlock safe as well as preventing any potential barging.
    2609 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 @wait@ and @signal_block@ routines.
    2610 
    2611 \begin{figure}
     2018The 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.
     2019
     2020\begin{figure}[H]
    26122021\begin{center}
    26132022{\resizebox{0.8\textwidth}{!}{\input{monitor_structs.pstex_t}}}
     
    26172026\end{figure}
    26182027
    2619 Figure \ref{fig:structs} shows a high-level representation of these data structures.
    2620 The main idea behind them is that, a thread cannot contain an arbitrary number of intrusive ``next'' pointers for linking onto monitors.
    2621 The @condition node@ is the data structure that is queued onto a condition variable and, when signalled, the condition queue is popped and each @condition criterion@ is moved to the AS-stack.
    2622 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{f:entry2}.
     2028Figure \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}.
    26232029
    26242030% ======================================================================
     
    26272033% ======================================================================
    26282034% ======================================================================
    2629 Similarly 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}.
    2630 For internal scheduling, these queues are part of condition variables, which are still unique for a given scheduling operation (\ie no signal statement uses multiple conditions).
    2631 However, in the case of external scheduling, there is no equivalent object which is associated with @waitfor@ statements.
    2632 This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired.
    2633 These monitors being the only objects that have sufficient lifetime and are available on both sides of the @waitfor@ statement.
    2634 This requires an algorithm to choose which monitor holds the relevant queue.
    2635 It is also important that said algorithm be independent of the order in which users list parameters.
    2636 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.
    2637 This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint.
     2035Similarly 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.
    26382036
    26392037This algorithm choice has two consequences:
    26402038\begin{itemize}
    2641         \item The queue of the monitor with the lowest address is no longer a true FIFO queue because threads can be moved to the front of the queue.
    2642 These queues need to contain a set of monitors for each of the waiting threads.
    2643 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.
    2644         \item The queue of the lowest priority monitor is both required and potentially unused.
    2645 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.
     2039        \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.
     2040        \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.
    26462041\end{itemize}
    26472042Therefore, the following modifications need to be made to support external scheduling:
    26482043\begin{itemize}
    2649         \item The threads waiting on the entry queue need to keep track of which routine they are trying to enter, and using which set of monitors.
    2650 The @mutex@ routine already has all the required information on its stack, so the thread only needs to keep a pointer to that information.
    2651         \item The monitors need to keep a mask of acceptable routines.
    2652 This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it.
    2653 It also needs storage to keep track of which routine was accepted.
    2654 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.
    2655 Note that if a thread has acquired two monitors but executes a @waitfor@ with only one monitor as a parameter, setting the mask of acceptable routines to both monitors will not cause any problems since the extra monitor will not change ownership regardless.
    2656 This becomes relevant when @when@ clauses affect the number of monitors passed to a @waitfor@ statement.
    2657         \item The entry/exit routines need to be updated as shown in listing \ref{f:entry3}.
     2044        \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.
     2045        \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.
     2046        \item The entry/exit routines need to be updated as shown in listing \ref{lst:entry3}.
    26582047\end{itemize}
    26592048
    26602049\subsection{External Scheduling - Destructors}
    2661 Finally, to support the ordering inversion of destructors, the code generation needs to be modified to use a special entry routine.
    2662 This routine is needed because of the storage requirements of the call order inversion.
    2663 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.
    2664 For regular @waitfor@ statements, the call stack of the routine itself matches this requirement but it is no longer the case when waiting for the destructor since it is pushed on to the AS-stack for later.
    2665 The @waitfor@ semantics can then be adjusted correspondingly, as seen in listing \ref{f:entry-dtor}
     2050Finally, 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}
    26662051
    26672052\begin{figure}
    26682053\begin{multicols}{2}
    26692054Entry
    2670 \begin{cfa}
     2055\begin{pseudo}
    26712056if monitor is free
    26722057        enter
     
    26792064        block
    26802065increment recursion
    2681 \end{cfa}
     2066\end{pseudo}
    26822067\columnbreak
    26832068Exit
    2684 \begin{cfa}
     2069\begin{pseudo}
    26852070decrement recursion
    26862071if recursion == 0
     
    26952080                wake-up thread
    26962081        endif
    2697 \end{cfa}
     2082\end{pseudo}
    26982083\end{multicols}
    2699 \begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling and external scheduling},label={f:entry3}]
    2700 \end{cfa}
     2084\begin{pseudo}[caption={Entry and exit routine for monitors with internal scheduling and external scheduling},label={lst:entry3}]
     2085\end{pseudo}
    27012086\end{figure}
    27022087
     
    27042089\begin{multicols}{2}
    27052090Destructor Entry
    2706 \begin{cfa}
     2091\begin{pseudo}
    27072092if monitor is free
    27082093        enter
     
    27182103        wait
    27192104increment recursion
    2720 \end{cfa}
     2105\end{pseudo}
    27212106\columnbreak
    27222107Waitfor
    2723 \begin{cfa}
     2108\begin{pseudo}
    27242109if matching thread is already there
    27252110        if found destructor
     
    27412126block
    27422127return
    2743 \end{cfa}
     2128\end{pseudo}
    27442129\end{multicols}
    2745 \begin{cfa}[caption={Pseudo code for the \protect\lstinline|waitfor| routine and the \protect\lstinline|mutex| entry routine for destructors},label={f:entry-dtor}]
    2746 \end{cfa}
     2130\begin{pseudo}[caption={Pseudo code for the \code{waitfor} routine and the \code{mutex} entry routine for destructors},label={lst:entry-dtor}]
     2131\end{pseudo}
    27472132\end{figure}
    27482133
     
    27562141
    27572142\section{Threads As Monitors}
    2758 As it was subtly alluded in section \ref{threads}, @thread@s in \CFA are in fact monitors, which means that all monitor features are available when using threads.
    2759 For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine:
    2760 \begin{figure}
    2761 \begin{cfa}[caption={Toy simulator using \protect\lstinline|thread|s and \protect\lstinline|monitor|s.},label={f:engine-v1}]
     2143As 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:
     2144\begin{figure}[H]
     2145\begin{cfacode}[caption={Toy simulator using \code{thread}s and \code{monitor}s.},label={lst:engine-v1}]
    27622146// Visualization declaration
    27632147thread Renderer {} renderer;
     
    27862170        }
    27872171}
    2788 \end{cfa}
     2172\end{cfacode}
    27892173\end{figure}
    2790 One 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.
    2791 Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner:
    2792 \begin{figure}
    2793 \begin{cfa}[caption={Same toy simulator with proper termination condition.},label={f:engine-v2}]
     2174One 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:
     2175\begin{figure}[H]
     2176\begin{cfacode}[caption={Same toy simulator with proper termination condition.},label={lst:engine-v2}]
    27942177// Visualization declaration
    27952178thread Renderer {} renderer;
     
    28292212// Call destructor for simulator once simulator finishes
    28302213// Call destructor for renderer to signify shutdown
    2831 \end{cfa}
     2214\end{cfacode}
    28322215\end{figure}
    28332216
    28342217\section{Fibers \& Threads}
    2835 As mentioned in section \ref{preemption}, \CFA uses preemptive threads by default but can use fibers on demand.
    2836 Currently, using fibers is done by adding the following line of code to the program~:
    2837 \begin{cfa}
     2218As 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~:
     2219\begin{cfacode}
    28382220unsigned int default_preemption() {
    28392221        return 0;
    28402222}
    2841 \end{cfa}
    2842 This function is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice, \ie no preemption.
    2843 However, once clusters are fully implemented, it will be possible to create fibers and \textbf{uthread} in the same system, as in listing \ref{f:fiber-uthread}
     2223\end{cfacode}
     2224This 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}
    28442225\begin{figure}
    2845 \lstset{language=CFA,deletedelim=**[is][]{`}{`}}
    2846 \begin{cfa}[caption={Using fibers and \textbf{uthread} side-by-side in \CFA},label={f:fiber-uthread}]
    2847 // Cluster forward declaration
     2226\begin{cfacode}[caption={Using fibers and \textbf{uthread} side-by-side in \CFA},label={lst:fiber-uthread}]
     2227//Cluster forward declaration
    28482228struct cluster;
    28492229
    2850 // Processor forward declaration
     2230//Processor forward declaration
    28512231struct processor;
    28522232
    2853 // Construct clusters with a preemption rate
     2233//Construct clusters with a preemption rate
    28542234void ?{}(cluster& this, unsigned int rate);
    2855 // Construct processor and add it to cluster
     2235//Construct processor and add it to cluster
    28562236void ?{}(processor& this, cluster& cluster);
    2857 // Construct thread and schedule it on cluster
     2237//Construct thread and schedule it on cluster
    28582238void ?{}(thread& this, cluster& cluster);
    28592239
    2860 // Declare two clusters
    2861 cluster thread_cluster = { 10`ms };                     // Preempt every 10 ms
    2862 cluster fibers_cluster = { 0 };                         // Never preempt
    2863 
    2864 // Construct 4 processors
     2240//Declare two clusters
     2241cluster thread_cluster = { 10`ms };                     //Preempt every 10 ms
     2242cluster fibers_cluster = { 0 };                         //Never preempt
     2243
     2244//Construct 4 processors
    28652245processor processors[4] = {
    28662246        //2 for the thread cluster
     
    28722252};
    28732253
    2874 // Declares thread
     2254//Declares thread
    28752255thread UThread {};
    28762256void ?{}(UThread& this) {
    2877         // Construct underlying thread to automatically
    2878         // be scheduled on the thread cluster
     2257        //Construct underlying thread to automatically
     2258        //be scheduled on the thread cluster
    28792259        (this){ thread_cluster }
    28802260}
     
    28822262void main(UThread & this);
    28832263
    2884 // Declares fibers
     2264//Declares fibers
    28852265thread Fiber {};
    28862266void ?{}(Fiber& this) {
    2887         // Construct underlying thread to automatically
    2888         // be scheduled on the fiber cluster
     2267        //Construct underlying thread to automatically
     2268        //be scheduled on the fiber cluster
    28892269        (this.__thread){ fibers_cluster }
    28902270}
    28912271
    28922272void main(Fiber & this);
    2893 \end{cfa}
     2273\end{cfacode}
    28942274\end{figure}
    28952275
     
    29012281% ======================================================================
    29022282\section{Machine Setup}
    2903 Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks.
    2904 All tests were made on this machine.
    2905 \begin{table}
     2283Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks. All tests were made on this machine.
     2284\begin{table}[H]
    29062285\begin{center}
    29072286\begin{tabular}{| l | r | l | r |}
     
    29352314
    29362315\section{Micro Benchmarks}
    2937 All benchmarks are run using the same harness to produce the results, seen as the @BENCH()@ macro in the following examples.
    2938 This macro uses the following logic to benchmark the code:
    2939 \begin{cfa}
     2316All 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:
     2317\begin{pseudo}
    29402318#define BENCH(run, result) \
    29412319        before = gettime(); \
     
    29432321        after  = gettime(); \
    29442322        result = (after - before) / N;
    2945 \end{cfa}
    2946 The method used to get time is @clock_gettime(CLOCK_THREAD_CPUTIME_ID);@.
    2947 Each benchmark is using many iterations of a simple call to measure the cost of the call.
    2948 The specific number of iterations depends on the specific benchmark.
     2323\end{pseudo}
     2324The 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.
    29492325
    29502326\subsection{Context-Switching}
    2951 The first interesting benchmark is to measure how long context-switches take.
    2952 The simplest approach to do this is to yield on a thread, which executes a 2-step context switch.
    2953 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).
    2954 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.
    2955 Figure~\ref{f:ctx-switch} shows the code for coroutines and threads with the results in table \ref{tab:ctx-switch}.
    2956 All omitted tests are functionally identical to one of these tests.
    2957 The difference between coroutines and threads can be attributed to the cost of scheduling.
     2327The 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.
    29582328\begin{figure}
    29592329\begin{multicols}{2}
    29602330\CFA Coroutines
    2961 \begin{cfa}
     2331\begin{cfacode}
    29622332coroutine GreatSuspender {};
    29632333void main(GreatSuspender& this) {
     
    29752345        printf("%llu\n", result);
    29762346}
    2977 \end{cfa}
     2347\end{cfacode}
    29782348\columnbreak
    29792349\CFA Threads
    2980 \begin{cfa}
     2350\begin{cfacode}
    29812351
    29822352
     
    29942364        printf("%llu\n", result);
    29952365}
    2996 \end{cfa}
     2366\end{cfacode}
    29972367\end{multicols}
    2998 \begin{cfa}[caption={\CFA benchmark code used to measure context-switches for coroutines and threads.},label={f:ctx-switch}]
    2999 \end{cfa}
     2368\begin{cfacode}[caption={\CFA benchmark code used to measure context-switches for coroutines and threads.},label={lst:ctx-switch}]
     2369\end{cfacode}
    30002370\end{figure}
    30012371
     
    30162386\end{tabular}
    30172387\end{center}
    3018 \caption{Context Switch comparison.
    3019 All numbers are in nanoseconds(\si{\nano\second})}
     2388\caption{Context Switch comparison. All numbers are in nanoseconds(\si{\nano\second})}
    30202389\label{tab:ctx-switch}
    30212390\end{table}
    30222391
    30232392\subsection{Mutual-Exclusion}
    3024 The next interesting benchmark is to measure the overhead to enter/leave a critical-section.
    3025 For monitors, the simplest approach is to measure how long it takes to enter and leave a monitor routine.
    3026 Figure~\ref{f:mutex} shows the code for \CFA.
    3027 To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a @pthread_mutex@ lock is also measured.
    3028 The results can be shown in table \ref{tab:mutex}.
     2393The 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}.
    30292394
    30302395\begin{figure}
    3031 \begin{cfa}[caption={\CFA benchmark code used to measure mutex routines.},label={f:mutex}]
     2396\begin{cfacode}[caption={\CFA benchmark code used to measure mutex routines.},label={lst:mutex}]
    30322397monitor M {};
    30332398void __attribute__((noinline)) call( M & mutex m /*, m2, m3, m4*/ ) {}
     
    30432408        printf("%llu\n", result);
    30442409}
    3045 \end{cfa}
     2410\end{cfacode}
    30462411\end{figure}
    30472412
     
    30552420FetchAdd + FetchSub                             & 26            & 26            & 0    \\
    30562421Pthreads Mutex Lock                             & 31            & 31.86 & 0.99 \\
    3057 \uC @monitor@ member routine            & 30            & 30            & 0    \\
    3058 \CFA @mutex@ routine, 1 argument        & 41            & 41.57 & 0.9  \\
    3059 \CFA @mutex@ routine, 2 argument        & 76            & 76.96 & 1.57 \\
    3060 \CFA @mutex@ routine, 4 argument        & 145           & 146.68        & 3.85 \\
     2422\uC \code{monitor} member routine               & 30            & 30            & 0    \\
     2423\CFA \code{mutex} routine, 1 argument   & 41            & 41.57 & 0.9  \\
     2424\CFA \code{mutex} routine, 2 argument   & 76            & 76.96 & 1.57 \\
     2425\CFA \code{mutex} routine, 4 argument   & 145           & 146.68        & 3.85 \\
    30612426Java synchronized routine                       & 27            & 28.57 & 2.6  \\
    30622427\hline
    30632428\end{tabular}
    30642429\end{center}
    3065 \caption{Mutex routine comparison.
    3066 All numbers are in nanoseconds(\si{\nano\second})}
     2430\caption{Mutex routine comparison. All numbers are in nanoseconds(\si{\nano\second})}
    30672431\label{tab:mutex}
    30682432\end{table}
    30692433
    30702434\subsection{Internal Scheduling}
    3071 The internal-scheduling benchmark measures the cost of waiting on and signalling a condition variable.
    3072 Figure~\ref{f:int-sched} shows the code for \CFA, with results table \ref{tab:int-sched}.
    3073 As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
     2435The 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.
    30742436
    30752437\begin{figure}
    3076 \begin{cfa}[caption={Benchmark code for internal scheduling},label={f:int-sched}]
     2438\begin{cfacode}[caption={Benchmark code for internal scheduling},label={lst:int-sched}]
    30772439volatile int go = 0;
    30782440condition c;
     
    31042466        return do_wait(m1);
    31052467}
    3106 \end{cfa}
     2468\end{cfacode}
    31072469\end{figure}
    31082470
     
    31142476\hline
    31152477Pthreads Condition Variable                     & 5902.5        & 6093.29       & 714.78 \\
    3116 \uC @signal@                                    & 322           & 323   & 3.36   \\
    3117 \CFA @signal@, 1 @monitor@      & 352.5 & 353.11        & 3.66   \\
    3118 \CFA @signal@, 2 @monitor@      & 430           & 430.29        & 8.97   \\
    3119 \CFA @signal@, 4 @monitor@      & 594.5 & 606.57        & 18.33  \\
    3120 Java @notify@                           & 13831.5       & 15698.21      & 4782.3 \\
     2478\uC \code{signal}                                       & 322           & 323   & 3.36   \\
     2479\CFA \code{signal}, 1 \code{monitor}    & 352.5 & 353.11        & 3.66   \\
     2480\CFA \code{signal}, 2 \code{monitor}    & 430           & 430.29        & 8.97   \\
     2481\CFA \code{signal}, 4 \code{monitor}    & 594.5 & 606.57        & 18.33  \\
     2482Java \code{notify}                              & 13831.5       & 15698.21      & 4782.3 \\
    31212483\hline
    31222484\end{tabular}
    31232485\end{center}
    3124 \caption{Internal scheduling comparison.
    3125 All numbers are in nanoseconds(\si{\nano\second})}
     2486\caption{Internal scheduling comparison. All numbers are in nanoseconds(\si{\nano\second})}
    31262487\label{tab:int-sched}
    31272488\end{table}
    31282489
    31292490\subsection{External Scheduling}
    3130 The Internal scheduling benchmark measures the cost of the @waitfor@ statement (@_Accept@ in \uC).
    3131 Figure~\ref{f:ext-sched} shows the code for \CFA, with results in table \ref{tab:ext-sched}.
    3132 As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
     2491The 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.
    31332492
    31342493\begin{figure}
    3135 \begin{cfa}[caption={Benchmark code for external scheduling},label={f:ext-sched}]
     2494\begin{cfacode}[caption={Benchmark code for external scheduling},label={lst:ext-sched}]
    31362495volatile int go = 0;
    31372496monitor M {};
     
    31622521        return do_wait(m1);
    31632522}
    3164 \end{cfa}
     2523\end{cfacode}
    31652524\end{figure}
    31662525
     
    31712530\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
    31722531\hline
    3173 \uC @Accept@                                    & 350           & 350.61        & 3.11  \\
    3174 \CFA @waitfor@, 1 @monitor@     & 358.5 & 358.36        & 3.82  \\
    3175 \CFA @waitfor@, 2 @monitor@     & 422           & 426.79        & 7.95  \\
    3176 \CFA @waitfor@, 4 @monitor@     & 579.5 & 585.46        & 11.25 \\
     2532\uC \code{Accept}                                       & 350           & 350.61        & 3.11  \\
     2533\CFA \code{waitfor}, 1 \code{monitor}   & 358.5 & 358.36        & 3.82  \\
     2534\CFA \code{waitfor}, 2 \code{monitor}   & 422           & 426.79        & 7.95  \\
     2535\CFA \code{waitfor}, 4 \code{monitor}   & 579.5 & 585.46        & 11.25 \\
    31772536\hline
    31782537\end{tabular}
    31792538\end{center}
    3180 \caption{External scheduling comparison.
    3181 All numbers are in nanoseconds(\si{\nano\second})}
     2539\caption{External scheduling comparison. All numbers are in nanoseconds(\si{\nano\second})}
    31822540\label{tab:ext-sched}
    31832541\end{table}
    31842542
    3185 
    31862543\subsection{Object Creation}
    3187 Finally, the last benchmark measures the cost of creation for concurrent objects.
    3188 Figure~\ref{f:creation} shows the code for @pthread@s and \CFA threads, with results shown in table \ref{tab:creation}.
    3189 As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
    3190 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.
     2544Finally, 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.
    31912545
    31922546\begin{figure}
    31932547\begin{center}
    3194 @pthread@
    3195 \begin{cfa}
     2548\texttt{pthread}
     2549\begin{ccode}
    31962550int main() {
    31972551        BENCH(
     
    32122566        printf("%llu\n", result);
    32132567}
    3214 \end{cfa}
     2568\end{ccode}
    32152569
    32162570
    32172571
    32182572\CFA Threads
    3219 \begin{cfa}
     2573\begin{cfacode}
    32202574int main() {
    32212575        BENCH(
     
    32272581        printf("%llu\n", result);
    32282582}
    3229 \end{cfa}
     2583\end{cfacode}
    32302584\end{center}
    3231 \caption{Benchmark code for \protect\lstinline|pthread|s and \CFA to measure object creation}
    3232 \label{f:creation}
     2585\begin{cfacode}[caption={Benchmark code for \texttt{pthread}s and \CFA to measure object creation},label={lst:creation}]
     2586\end{cfacode}
    32332587\end{figure}
    32342588
     
    32502604\end{tabular}
    32512605\end{center}
    3252 \caption{Creation comparison.
    3253 All numbers are in nanoseconds(\si{\nano\second}).}
     2606\caption{Creation comparison. All numbers are in nanoseconds(\si{\nano\second}).}
    32542607\label{tab:creation}
    32552608\end{table}
     
    32582611
    32592612\section{Conclusion}
    3260 This paper has achieved a minimal concurrency \textbf{api} that is simple, efficient and usable as the basis for higher-level features.
    3261 The approach presented is based on a lightweight thread-system for parallelism, which sits on top of clusters of processors.
    3262 This M:N model is judged to be both more efficient and allow more flexibility for users.
    3263 Furthermore, this document introduces monitors as the main concurrency tool for users.
    3264 This paper also offers a novel approach allowing multiple monitors to be accessed simultaneously without running into the Nested Monitor Problem~\cite{Lister77}.
    3265 It also offers a full implementation of the concurrency runtime written entirely in \CFA, effectively the largest \CFA code base to date.
     2613This paper 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 paper 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.
    32662614
    32672615
     
    32732621
    32742622\subsection{Performance} \label{futur:perf}
    3275 This paper presents a first implementation of the \CFA concurrency runtime.
    3276 Therefore, there is still significant work to improve performance.
    3277 Many of the data structures and algorithms may change in the future to more efficient versions.
    3278 For example, the number of monitors in a single \textbf{bulk-acq} is only bound by the stack size, this is probably unnecessarily generous.
    3279 It may be possible that limiting the number helps increase performance.
    3280 However, it is not obvious that the benefit would be significant.
     2623This paper 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.
    32812624
    32822625\subsection{Flexible Scheduling} \label{futur:sched}
    3283 An important part of concurrency is scheduling.
    3284 Different scheduling algorithms can affect performance (both in terms of average and variation).
    3285 However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
    3286 One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted to the requirements of the workload.
    3287 However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms.
    3288 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.
    3289 This path of flexible schedulers will be explored for \CFA.
     2626An 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.
    32902627
    32912628\subsection{Non-Blocking I/O} \label{futur:nbio}
    3292 While 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).
    3293 These types of workloads often require significant engineering around amortizing costs of blocking IO operations.
    3294 At its core, non-blocking I/O is an operating system level feature that allows queuing IO operations (\eg network operations) and registering for notifications instead of waiting for requests to complete.
    3295 In this context, the role of the language makes Non-Blocking IO easily available and with low overhead.
    3296 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.
    3297 However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear.
     2629While 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.
    32982630
    32992631\subsection{Other Concurrency Tools} \label{futur:tools}
    3300 While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
    3301 Examples of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, executors and actors.
    3302 These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
     2632While 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.
    33032633
    33042634\subsection{Implicit Threading} \label{futur:implcit}
    3305 Simpler applications can benefit greatly from having implicit parallelism.
    3306 That is, parallelism that does not rely on the user to write concurrency.
    3307 This type of parallelism can be achieved both at the language level and at the library level.
    3308 The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithms~\cite{uC++book}.
    3309 Table \ref{f:parfor} shows three different code examples that accomplish point-wise sums of large arrays.
    3310 Note that none of these examples explicitly declare any concurrency or parallelism objects.
     2635Simpler 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.
    33112636
    33122637\begin{table}
     
    33142639\begin{tabular}[t]{|c|c|c|}
    33152640Sequential & Library Parallel & Language Parallel \\
    3316 \begin{cfa}[tabsize=3]
     2641\begin{cfacode}[tabsize=3]
    33172642void big_sum(
    33182643        int* a, int* b,
     
    33382663//... fill in a & b
    33392664big_sum(a,b,c,10000);
    3340 \end{cfa} &\begin{cfa}[tabsize=3]
     2665\end{cfacode} &\begin{cfacode}[tabsize=3]
    33412666void big_sum(
    33422667        int* a, int* b,
     
    33622687//... fill in a & b
    33632688big_sum(a,b,c,10000);
    3364 \end{cfa}&\begin{cfa}[tabsize=3]
     2689\end{cfacode}&\begin{cfacode}[tabsize=3]
    33652690void big_sum(
    33662691        int* a, int* b,
     
    33862711//... fill in a & b
    33872712big_sum(a,b,c,10000);
    3388 \end{cfa}
     2713\end{cfacode}
    33892714\end{tabular}
    33902715\end{center}
    33912716\caption{For loop to sum numbers: Sequential, using library parallelism and language parallelism.}
    3392 \label{f:parfor}
     2717\label{lst:parfor}
    33932718\end{table}
    33942719
    3395 Implicit parallelism is a restrictive solution and therefore has its limitations.
    3396 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.
     2720Implicit 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.
    33972721
    33982722
     
    34072731% B I B L I O G R A P H Y
    34082732% -----------------------------
    3409 %\bibliographystyle{plain}
     2733\bibliographystyle{plain}
    34102734\bibliography{pl,local}
    34112735
Note: See TracChangeset for help on using the changeset viewer.