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