source: doc/papers/concurrency/Paper.tex @ 1ecee81

arm-ehcleanup-dtorsjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-expr
Last change on this file since 1ecee81 was 1ecee81, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

update title/introduction

  • Property mode set to 100644
File size: 131.8 KB
Line 
1\documentclass[AMA,STIX1COL]{WileyNJD-v2}
2
3\articletype{RESEARCH ARTICLE}%
4
5\received{XXXXX}
6\revised{XXXXX}
7\accepted{XXXXX}
8
9\raggedbottom
10
11%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
12
13% Latex packages used in the document.
14
15\usepackage{epic,eepic}
16\usepackage{xspace}
17\usepackage{comment}
18\usepackage{upquote}                                            % switch curled `'" to straight
19\usepackage{listings}                                           % format program code
20\usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig}
21\renewcommand{\thesubfigure}{(\Alph{subfigure})}
22\captionsetup{justification=raggedright,singlelinecheck=false}
23\usepackage{dcolumn}                                            % align decimal points in tables
24\usepackage{capt-of}
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
31\usepackage[pagewise]{lineno}
32\renewcommand{\linenumberfont}{\scriptsize\sffamily}
33
34\renewcommand{\topfraction}{0.8}                        % float must be greater than X of the page before it is forced onto its own page
35\renewcommand{\bottomfraction}{0.8}                     % float must be greater than X of the page before it is forced onto its own page
36\renewcommand{\floatpagefraction}{0.8}          % float must be greater than X of the page before it is forced onto its own page
37\renewcommand{\textfraction}{0.0}                       % the entire page maybe devoted to floats with no text on the page at all
38
39\lefthyphenmin=3                                                        % hyphen only after 4 characters
40\righthyphenmin=3
41
42%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
43
44% Names used in the document.
45
46\newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
47\newcommand{\CFA}{\protect\CFAIcon}             % safe for section/caption
48\newcommand{\CFL}{\textrm{Cforall}\xspace}      % Cforall symbolic name
49\newcommand{\Celeven}{\textrm{C11}\xspace}      % C11 symbolic name
50\newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
51\newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
52\newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
53\newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
54\newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name
55\newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name
56
57%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
58
59\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
60\newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}}
61\newcommand{\uC}{$\mu$\CC}
62\newcommand{\TODO}[1]{{\Textbf{#1}}}
63
64%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
65
66% Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
67% removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
68% AFTER HYPERREF.
69%\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}
70\renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}
71
72\renewcommand*{\thefootnote}{\Alph{footnote}} % hack because fnsymbol does not work
73%\renewcommand*{\thefootnote}{\fnsymbol{footnote}}
74
75\makeatletter
76% parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
77% use rather than use \parident directly.
78\newlength{\parindentlnth}
79\setlength{\parindentlnth}{\parindent}
80
81\newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{\lst@basicstyle{#1}}}}
82\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
83\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
84
85\newlength{\gcolumnposn}                                        % temporary hack because lstlisting does not handle tabs correctly
86\newlength{\columnposn}
87\setlength{\gcolumnposn}{3.5in}
88\setlength{\columnposn}{\gcolumnposn}
89
90\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}}}}
91\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
92
93% Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
94% The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
95% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
96\newcommand{\newtermFontInline}{\emph}
97\newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
98\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
99\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
100
101% Latin abbreviation
102\newcommand{\abbrevFont}{\textit}                       % set empty for no italics
103\@ifundefined{eg}{
104\newcommand{\EG}{\abbrevFont{e}\abbrevFont{g}}
105\newcommand*{\eg}{%
106        \@ifnextchar{,}{\EG}%
107                {\@ifnextchar{:}{\EG}%
108                        {\EG,\xspace}}%
109}}{}%
110\@ifundefined{ie}{
111\newcommand{\IE}{\abbrevFont{i}\abbrevFont{e}}
112\newcommand*{\ie}{%
113        \@ifnextchar{,}{\IE}%
114                {\@ifnextchar{:}{\IE}%
115                        {\IE,\xspace}}%
116}}{}%
117\@ifundefined{etc}{
118\newcommand{\ETC}{\abbrevFont{etc}}
119\newcommand*{\etc}{%
120        \@ifnextchar{.}{\ETC}%
121        {\ETC.\xspace}%
122}}{}%
123\@ifundefined{etal}{
124\newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}}
125\newcommand*{\etal}{%
126        \@ifnextchar{.}{\protect\ETAL}%
127                {\protect\ETAL.\xspace}%
128}}{}%
129\@ifundefined{viz}{
130\newcommand{\VIZ}{\abbrevFont{viz}}
131\newcommand*{\viz}{%
132        \@ifnextchar{.}{\VIZ}%
133                {\VIZ.\xspace}%
134}}{}%
135\makeatother
136
137\newenvironment{cquote}
138               {\list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
139                \item\relax}
140               {\endlist}
141
142%\newenvironment{cquote}{%
143%\list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
144%\item\relax%
145%}{%
146%\endlist%
147%}% cquote
148
149% CFA programming language, based on ANSI C (with some gcc additions)
150\lstdefinelanguage{CFA}[ANSI]{C}{
151        morekeywords={
152                _Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, __attribute, __attribute__,
153                auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__, __const, __const__,
154                coroutine, disable, dtype, enable, exception, __extension__, fallthrough, fallthru, finally,
155                __float80, float80, __float128, float128, forall, ftype, _Generic, _Imaginary, __imag, __imag__,
156                inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
157                otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread,
158                _Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
159                virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
160        moredirectives={defined,include_next}%
161}
162
163\lstset{
164language=CFA,
165columns=fullflexible,
166basicstyle=\linespread{0.9}\sf,                                                 % reduce line spacing and use sanserif font
167stringstyle=\tt,                                                                                % use typewriter font
168tabsize=5,                                                                                              % N space tabbing
169xleftmargin=\parindentlnth,                                                             % indent code to paragraph indentation
170%mathescape=true,                                                                               % LaTeX math escape in CFA code $...$
171escapechar=\$,                                                                                  % LaTeX escape in CFA code
172keepspaces=true,                                                                                %
173showstringspaces=false,                                                                 % do not show spaces with cup
174showlines=true,                                                                                 % show blank lines at end of code
175aboveskip=4pt,                                                                                  % spacing above/below code block
176belowskip=3pt,
177% replace/adjust listing characters that look bad in sanserif
178literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
179        {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
180        {<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
181        {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex{\textrm{\textgreater}}}2,
182moredelim=**[is][\color{red}]{`}{`},
183}% lstset
184
185% uC++ programming language, based on ANSI C++
186\lstdefinelanguage{uC++}[ANSI]{C++}{
187        morekeywords={
188                _Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _CatchResume, _Cormonitor, _Coroutine, _Disable,
189                _Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
190                _Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
191}
192\lstdefinelanguage{Golang}{
193        morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
194        morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
195                bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
196        morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
197        morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
198        morekeywords=[5]{Println,Printf,Error,},
199        sensitive=true,
200        morecomment=[l]{//},
201        morecomment=[s]{/*}{*/},
202        morestring=[b]',
203        morestring=[b]",
204        morestring=[s]{`}{`},
205}
206
207\lstnewenvironment{cfa}[1][]
208{\lstset{#1}}
209{}
210\lstnewenvironment{C++}[1][]                            % use C++ style
211{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
212{}
213\lstnewenvironment{uC++}[1][]
214{\lstset{#1}}
215{}
216\lstnewenvironment{Go}[1][]
217{\lstset{#1}}
218{}
219
220% inline code @...@
221\lstMakeShortInline@%
222
223\let\OLDthebibliography\thebibliography
224\renewcommand\thebibliography[1]{
225  \OLDthebibliography{#1}
226  \setlength{\parskip}{0pt}
227  \setlength{\itemsep}{4pt plus 0.3ex}
228}
229
230\title{\texorpdfstring{Advanced Control-flow and Concurrency in \protect\CFA}{Advanced Control-flow in Cforall}}
231
232\author[1]{Thierry Delisle}
233\author[1]{Peter A. Buhr*}
234\authormark{DELISLE \textsc{et al.}}
235
236\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}
237
238\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}}
239
240\fundingInfo{Natural Sciences and Engineering Research Council of Canada}
241
242\abstract[Summary]{
243\CFA is a modern, polymorphic, non-object-oriented, backwards-compatible extension of the C programming language.
244This paper discusses some advanced control-flow and concurrency/parallelism features in \CFA, along with the supporting runtime.
245These features are created from scratch because they do not exist in ISO C, or are low-level and/or unimplemented, so C programmers continue to rely on library features, like C pthreads.
246\CFA introduces language-level control-flow mechanisms, like coroutines, user-level threading, and monitors for mutual exclusion and synchronization.
247A unique contribution of this work is allowing multiple monitors to be safely acquired \emph{simultaneously} (deadlock free), while integrating this capability with monitor synchronization mechanisms.
248These features also integrate with the \CFA polymorphic type-system and exception handling, while respecting the expectations and style of C programmers.
249Experimental results show comparable performance of the new features with similar mechanisms in other concurrent programming-languages.
250}%
251
252\keywords{coroutines, concurrency, parallelism, threads, monitors, runtime, C, \CFA (Cforall)}
253
254
255\begin{document}
256\linenumbers                                            % comment out to turn off line numbering
257
258\maketitle
259
260
261\section{Introduction}
262
263This paper discusses the design of language-level control-flow and concurrency/parallelism extensions in \CFA and its runtime.
264\CFA is a modern, polymorphic, non-object-oriented\footnote{
265\CFA has features often associated with object-oriented programming languages, such as constructors, destructors, virtuals and simple inheritance.
266However, functions \emph{cannot} be nested in structures, so there is no lexical binding between a structure and set of functions (member/method) implemented by an implicit \lstinline@this@ (receiver) parameter.},
267backwards-compatible extension of the C programming language~\cite{Moss18}.
268Within the \CFA framework, new control-flow features are created from scratch.
269ISO \Celeven defines only a subset of the \CFA extensions.
270The overlapping features are concurrency~\cite[\S~7.26]{C11};
271however, \Celeven concurrency is largely wrappers for a subset of the pthreads library~\cite{Butenhof97,Pthreads}.
272Furthermore, \Celeven and pthreads concurrency is basic, based on thread fork/join in a function and a few locks, which is low-level and error prone;
273no high-level language concurrency features are defined.
274Interestingly, almost a decade after publication of the \Celeven standard, neither gcc-8, clang-8 nor msvc-19 (most recent versions) support the \Celeven include @threads.h@, indicating little interest in the C11 concurrency approach.
275Finally, while the \Celeven standard does not state a concurrent threading-model, the historical association with pthreads suggests implementations would adopt kernel-level threading (1:1)~\cite{ThreadModel}.
276
277In contrast, there has been a renewed interest during the past decade in user-level (M:N, green) threading in old and new programming languages.
278As multi-core hardware became available in the 1980/90s, both user and kernel threading were examined.
279Kernel threading was chosen, largely because of its simplicity and fit with the simpler operating systems and hardware architectures at the time, which gave it a performance advantage~\cite{Drepper03}.
280Libraries like pthreads were developed for C, and the Solaris operating-system switched from user (JDK 1.1~\cite{JDK1.1}) to kernel threads.
281As a result, languages like Java, Scala~\cite{Scala}, Objective-C~\cite{obj-c-book}, \CCeleven~\cite{C11}, and C\#~\cite{Csharp} adopted the 1:1 kernel-threading model, with a variety of presentation mechanisms.
282From 2000 onwards, languages like Go~\cite{Go}, Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, D~\cite{D}, and \uC~\cite{uC++,uC++book} have championed the M:N user-threading model, and many user-threading libraries have appeared~\cite{Qthreads,MPC,BoostThreads}, including putting green threads back into Java~\cite{Quasar}.
283The main argument for user-level threading is that they are lighter weight than kernel threads (locking and context switching do not cross the kernel boundary), so there is less restriction on programming styles that encourage large numbers of threads performing smaller work-units to facilitate load balancing by the runtime~\cite{Verch12}.
284As well, user-threading facilitates a simpler concurrency approach using thread objects that leverage sequential patterns versus events with call-backs~\cite{vonBehren03}.
285Finally, performant user-threading implementations (both time and space) are largely competitive with direct kernel-threading implementations, while achieving the programming advantages of high concurrency levels and safety.
286
287A further effort over the past decade is the development of language memory-models to deal with the conflict between certain language features and compiler/hardware optimizations.
288This issue can be rephrased as: some language features are pervasive (language and runtime) and cannot be safely added via a library to prevent invalidation by sequential optimizations~\cite{Buhr95a,Boehm05}.
289The consequence is that a language must be cognizant of these features and provide sufficient tools to program around any safety issues.
290For example, C created the @volatile@ qualifier to provide correct execution for @setjmp@/@logjmp@ (concurrency came later).
291The common solution is to provide a handful of complex qualifiers and functions (e.g., @volatile@ and atomics) allowing programmers to write consistent/race-free programs, often in the sequentially-consistent memory-model~\cite{Boehm12}.
292
293While having a sufficient memory-model allows sound libraries to be constructed, writing these libraries can quickly become awkward and error prone, and using these low-level libraries has the same issues.
294Essentially, using low-level explicit locks is the concurrent equivalent of assembler programming.
295Just as most assembler programming is replaced with programming in a high-level language, explicit locks can be replaced with high-level concurrency constructs in a programming language.
296Then the goal is for the compiler to check for correct usage and follow any complex coding conventions implicitly.
297The drawback is that language constructs may preclude certain specialized techniques, therefore introducing inefficiency or inhibiting concurrency.
298For most concurrent programs, these drawbacks are insignificant in comparison to the speed of composition, and subsequent reliability and maintainability of the high-level concurrent program.
299(The same is true for high-level programming versus assembler programming.)
300Only very rarely should it be necessary to drop down to races and/or explicit locks to apply a specialized technique to achieve maximum speed or concurrency.
301As stated, this observation applies to non-concurrent forms of complex control-flow, like exception handling and coroutines.
302
303Adapting the programming language to these features also allows matching the control-flow model with the programming-language style, versus adopting one general (sound) library/paradigm.
304For example, it is possible to provide exceptions, coroutines, monitors, and tasks as specialized types in an object-oriented language, integrating these constructs to allow leveraging the type-system (static type-checking) and all other object-oriented capabilities~\cite{uC++}.
305It is also possible to leverage call/return for blocking communication via new control structures, versus switching to alternative communication paradigms, like channels or message passing.
306As well, user threading is often a complementary feature, allowing light-weight threading to match with low-cost objects, while hiding the application/kernel boundary.
307User threading also allows layering of implicit concurrency models (no explicit thread creation), such executors, data-flow, actors, into a single language, so programmers can chose the model that best fits an algorithm.\footnote{
308All implicit concurrency models have explicit threading in their implementation, and hence, can be build from explicit threading;
309however, the reverse is seldom true, i.e., given implicit concurrency, e.g., actors, it is virtually impossible to create explicit concurrency, e.g., blocking thread objects.}
310Finally, with extended language features and user-level threading it is possible to discretely fold locking and non-blocking I/O multiplexing into the language's I/O libraries, so threading implicitly dovetails with the I/O subsystem.
311
312\CFA embraces language extensions and user-level threading to provide advanced control-flow (exception handling\footnote{
313\CFA exception handling will be presented in a separate paper.
314The key feature that dovetails with this paper is non-local exceptions allowing exceptions to be raised across stacks, with synchronous exceptions raised among coroutines and asynchronous exceptions raised among threads, similar to that in \uC~\cite[\S~5]{uC++}
315} and coroutines) and concurrency.
316We show the \CFA language extensions are demonstrably better than those proposed for \Celeven, \CC and other concurrent, imperative programming languages, and that the \CFA runtime is competitive with other similar extensions.
317The contributions of this work are:
318\begin{itemize}
319\item
320allowing multiple monitors to be safely acquired \emph{simultaneously} (deadlock free), while seamlessly integrating this capability with all monitor synchronization mechanisms.
321\item
322all control-flow features respect the expectations of C programmers, with statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features.
323\item
324experimental results show comparable performance of the new features with similar mechanisms in other concurrent programming-languages.
325\end{itemize}
326
327\begin{comment}
328This paper provides a minimal concurrency \newterm{Application Program Interface} (API) that is simple, efficient and can be used to build other concurrency features.
329While the simplest concurrency system is a thread and a lock, this low-level approach is hard to master.
330An easier approach for programmers is to support higher-level constructs as the basis of concurrency.
331Indeed, for highly-productive concurrent-programming, high-level approaches are much more popular~\cite{Hochstein05}.
332Examples of high-level approaches are jobs (thread pool)~\cite{TBB}, implicit threading~\cite{OpenMP}, monitors~\cite{Java}, channels~\cite{CSP,Go}, and message passing~\cite{Erlang,MPI}.
333
334The following terminology is used.
335A \newterm{thread} is a fundamental unit of execution that runs a sequence of code and requires a stack to maintain state.
336Multiple simultaneous threads give rise to \newterm{concurrency}, which requires locking to ensure access to shared data and safe communication.
337\newterm{Locking}, and by extension \newterm{locks}, are defined as a mechanism to prevent progress of threads to provide safety.
338\newterm{Parallelism} is running multiple threads simultaneously.
339Parallelism implies \emph{actual} simultaneous execution, where concurrency only requires \emph{apparent} simultaneous execution.
340As such, parallelism only affects performance, which is observed through differences in space and/or time at runtime.
341Hence, there are two problems to be solved: concurrency and parallelism.
342While these two concepts are often combined, they are distinct, requiring different tools~\cite[\S~2]{Buhr05a}.
343Concurrency tools handle mutual exclusion and synchronization, while parallelism tools handle performance, cost, and resource utilization.
344
345The proposed concurrency API is implemented in a dialect of C, called \CFA (pronounced C-for-all).
346The paper discusses how the language features are added to the \CFA translator with respect to parsing, semantics, and type checking, and the corresponding high-performance runtime-library to implement the concurrent features.
347\end{comment}
348
349
350\begin{comment}
351\section{\CFA Overview}
352
353The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency.
354Extended versions and explanation of the following code examples are available at the \CFA website~\cite{Cforall} or in Moss~\etal~\cite{Moss18}.
355
356\CFA is a non-object-oriented extension of ISO-C, and hence, supports all C paradigms.
357Like C, the building blocks of \CFA are structures and routines.
358Virtually all of the code generated by the \CFA translator respects C memory layouts and calling conventions.
359While \CFA is not object oriented, lacking the concept of a receiver (\eg @this@) and nominal inheritance-relationships, C has a notion of objects: ``region of data storage in the execution environment, the contents of which can represent values''~\cite[3.15]{C11}.
360While some object-oriented features appear in \CFA, they are independent capabilities, allowing \CFA to adopt them while maintaining a procedural paradigm.
361
362
363\subsection{References}
364
365\CFA provides multi-level rebindable references, as an alternative to pointers, which significantly reduces syntactic noise.
366\begin{cfa}
367int x = 1, y = 2, z = 3;
368int * p1 = &x, ** p2 = &p1,  *** p3 = &p2,      $\C{// pointers to x}$
369    `&` r1 = x,   `&&` r2 = r1,   `&&&` r3 = r2;        $\C{// references to x}$
370int * p4 = &z, `&` r4 = z;
371
372*p1 = 3; **p2 = 3; ***p3 = 3;       // change x
373r1 =  3;     r2 = 3;      r3 = 3;        // change x: implicit dereferences *r1, **r2, ***r3
374**p3 = &y; *p3 = &p4;                // change p1, p2
375`&`r3 = &y; `&&`r3 = &`&`r4;             // change r1, r2: cancel implicit dereferences (&*)**r3, (&(&*)*)*r3, &(&*)r4
376\end{cfa}
377A reference is a handle to an object, like a pointer, but is automatically dereferenced the specified number of levels.
378Referencing (address-of @&@) a reference variable cancels one of the implicit dereferences, until there are no more implicit references, after which normal expression behaviour applies.
379
380
381\subsection{\texorpdfstring{\protect\lstinline{with} Statement}{with Statement}}
382\label{s:WithStatement}
383
384Heterogeneous data is aggregated into a structure/union.
385To reduce syntactic noise, \CFA provides a @with@ statement (see Pascal~\cite[\S~4.F]{Pascal}) to elide aggregate field-qualification by opening a scope containing the field identifiers.
386\begin{cquote}
387\vspace*{-\baselineskip}%???
388\lstDeleteShortInline@%
389\begin{cfa}
390struct S { char c; int i; double d; };
391struct T { double m, n; };
392// multiple aggregate parameters
393\end{cfa}
394\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
395\begin{cfa}
396void f( S & s, T & t ) {
397        `s.`c; `s.`i; `s.`d;
398        `t.`m; `t.`n;
399}
400\end{cfa}
401&
402\begin{cfa}
403void f( S & s, T & t ) `with ( s, t )` {
404        c; i; d;                // no qualification
405        m; n;
406}
407\end{cfa}
408\end{tabular}
409\lstMakeShortInline@%
410\end{cquote}
411Object-oriented programming languages only provide implicit qualification for the receiver.
412
413In detail, the @with@-statement syntax is:
414\begin{cfa}
415$\emph{with-statement}$:
416        'with' '(' $\emph{expression-list}$ ')' $\emph{compound-statement}$
417\end{cfa}
418and may appear as the body of a routine or nested within a routine body.
419Each expression in the expression-list provides a type and object.
420The type must be an aggregate type.
421(Enumerations are already opened.)
422The object is the implicit qualifier for the open structure-fields.
423All expressions in the expression list are opened in parallel within the compound statement, which is different from Pascal, which nests the openings from left to right.
424
425
426\subsection{Overloading}
427
428\CFA maximizes the ability to reuse names via overloading to aggressively address the naming problem.
429Both variables and routines may be overloaded, where selection is based on number and types of returns and arguments (as in Ada~\cite{Ada}).
430\newpage
431\vspace*{-2\baselineskip}%???
432\begin{cquote}
433\begin{cfa}
434// selection based on type
435\end{cfa}
436\lstDeleteShortInline@%
437\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
438\begin{cfa}
439const short int `MIN` = -32768;
440const int `MIN` = -2147483648;
441const long int `MIN` = -9223372036854775808L;
442\end{cfa}
443&
444\begin{cfa}
445short int si = `MIN`;
446int i = `MIN`;
447long int li = `MIN`;
448\end{cfa}
449\end{tabular}
450\begin{cfa}
451// selection based on type and number of parameters
452\end{cfa}
453\begin{tabular}{@{}l@{\hspace{2.7\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
454\begin{cfa}
455void `f`( void );
456void `f`( char );
457void `f`( int, double );
458\end{cfa}
459&
460\begin{cfa}
461`f`();
462`f`( 'a' );
463`f`( 3, 5.2 );
464\end{cfa}
465\end{tabular}
466\begin{cfa}
467// selection based on type and number of returns
468\end{cfa}
469\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
470\begin{cfa}
471char `f`( int );
472double `f`( int );
473[char, double] `f`( int );
474\end{cfa}
475&
476\begin{cfa}
477char c = `f`( 3 );
478double d = `f`( 3 );
479[d, c] = `f`( 3 );
480\end{cfa}
481\end{tabular}
482\lstMakeShortInline@%
483\end{cquote}
484Overloading is important for \CFA concurrency since the runtime system relies on creating different types to represent concurrency objects.
485Therefore, overloading eliminates long prefixes and other naming conventions to prevent name clashes.
486As seen in Section~\ref{s:Concurrency}, routine @main@ is heavily overloaded.
487As another example, variable overloading is useful in the parallel semantics of the @with@ statement for fields with the same name:
488\begin{cfa}
489struct S { int `i`; int j; double m; } s;
490struct T { int `i`; int k; int m; } t;
491with ( s, t ) {
492        j + k;                                                                  $\C{// unambiguous, s.j + t.k}$
493        m = 5.0;                                                                $\C{// unambiguous, s.m = 5.0}$
494        m = 1;                                                                  $\C{// unambiguous, t.m = 1}$
495        int a = m;                                                              $\C{// unambiguous, a = t.m }$
496        double b = m;                                                   $\C{// unambiguous, b = s.m}$
497        int c = `s.i` + `t.i`;                                  $\C{// unambiguous, qualification}$
498        (double)m;                                                              $\C{// unambiguous, cast s.m}$
499}
500\end{cfa}
501For parallel semantics, both @s.i@ and @t.i@ are visible with the same type, so only @i@ is ambiguous without qualification.
502
503
504\subsection{Operators}
505
506Overloading also extends to operators.
507Operator-overloading syntax creates a routine name with an operator symbol and question marks for the operands:
508\begin{cquote}
509\lstDeleteShortInline@%
510\begin{tabular}{@{}ll@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
511\begin{cfa}
512int ++?(int op);
513int ?++(int op);
514int `?+?`(int op1, int op2);
515int ?<=?(int op1, int op2);
516int ?=? (int & op1, int op2);
517int ?+=?(int & op1, int op2);
518\end{cfa}
519&
520\begin{cfa}
521// unary prefix increment
522// unary postfix increment
523// binary plus
524// binary less than
525// binary assignment
526// binary plus-assignment
527\end{cfa}
528&
529\begin{cfa}
530struct S { int i, j; };
531S `?+?`( S op1, S op2) { // add two structures
532        return (S){op1.i + op2.i, op1.j + op2.j};
533}
534S s1 = {1, 2}, s2 = {2, 3}, s3;
535s3 = s1 `+` s2;         // compute sum: s3 == {2, 5}
536\end{cfa}
537\end{tabular}
538\lstMakeShortInline@%
539\end{cquote}
540
541
542\subsection{Constructors / Destructors}
543
544Object lifetime is a challenge in non-managed programming languages.
545\CFA responds with \CC-like constructors and destructors, using a different operator-overloading syntax.
546\begin{cfa}
547struct VLA { int len, * data; };                        $\C{// variable length array of integers}$
548void ?{}( VLA & vla ) with ( vla ) { len = 10;  data = alloc( len ); }  $\C{// default constructor}$
549void ?{}( VLA & vla, int size, char fill ) with ( vla ) { len = size;  data = alloc( len, fill ); } // initialization
550void ?{}( VLA & vla, VLA other ) { vla.len = other.len;  vla.data = other.data; } $\C{// copy, shallow}$
551void ^?{}( VLA & vla ) with ( vla ) { free( data ); } $\C{// destructor}$
552{
553        VLA  x,            y = { 20, 0x01 },     z = y; $\C{// z points to y}$
554        // $\LstCommentStyle{\color{red}\ \ \ x\{\};\ \ \ \ \ \ \ \ \ y\{ 20, 0x01 \};\ \ \ \ \ \ \ \ \ \ z\{ z, y \};\ \ \ \ \ \ \ implicit calls}$
555        ^x{};                                                                   $\C{// deallocate x}$
556        x{};                                                                    $\C{// reallocate x}$
557        z{ 5, 0xff };                                                   $\C{// reallocate z, not pointing to y}$
558        ^y{};                                                                   $\C{// deallocate y}$
559        y{ x };                                                                 $\C{// reallocate y, points to x}$
560        x{};                                                                    $\C{// reallocate x, not pointing to y}$
561}       //  $\LstCommentStyle{\color{red}\^{}z\{\};\ \ \^{}y\{\};\ \ \^{}x\{\};\ \ \ implicit calls}$
562\end{cfa}
563Like \CC, construction is implicit on allocation (stack/heap) and destruction is implicit on deallocation.
564The object and all their fields are constructed/destructed.
565\CFA also provides @new@ and @delete@ as library routines, which behave like @malloc@ and @free@, in addition to constructing and destructing objects:
566\begin{cfa}
567{
568        ... struct S s = {10}; ...                              $\C{// allocation, call constructor}$
569}                                                                                       $\C{// deallocation, call destructor}$
570struct S * s = new();                                           $\C{// allocation, call constructor}$
571...
572delete( s );                                                            $\C{// deallocation, call destructor}$
573\end{cfa}
574\CFA concurrency uses object lifetime as a means of mutual exclusion and/or synchronization.
575
576
577\subsection{Parametric Polymorphism}
578\label{s:ParametricPolymorphism}
579
580The signature feature of \CFA is parametric-polymorphic routines~\cite{Cforall} with routines generalized using a @forall@ clause (giving the language its name), which allow separately compiled routines to support generic usage over multiple types.
581For example, the following sum routine works for any type that supports construction from 0 and addition:
582\begin{cfa}
583forall( otype T | { void `?{}`( T *, zero_t ); T `?+?`( T, T ); } ) // constraint type, 0 and +
584T sum( T a[$\,$], size_t size ) {
585        `T` total = { `0` };                                    $\C{// initialize by 0 constructor}$
586        for ( size_t i = 0; i < size; i += 1 )
587                total = total `+` a[i];                         $\C{// select appropriate +}$
588        return total;
589}
590S sa[5];
591int i = sum( sa, 5 );                                           $\C{// use S's 0 construction and +}$
592\end{cfa}
593Type variables can be @otype@ or @dtype@.
594@otype@ refers to a \emph{complete type}, \ie, a type with size, alignment, default constructor, copy constructor, destructor, and assignment operator.
595@dtype@ refers to an \emph{incomplete type}, \eg, void or a forward-declared type.
596The builtin types @zero_t@ and @one_t@ overload constant 0 and 1 for a new types, where both 0 and 1 have special meaning in C.
597
598\CFA provides \newterm{traits} to name a group of type assertions, where the trait name allows specifying the same set of assertions in multiple locations, preventing repetition mistakes at each routine declaration:
599\begin{cfa}
600trait `sumable`( otype T ) {
601        void `?{}`( T &, zero_t );                              $\C{// 0 literal constructor}$
602        T `?+?`( T, T );                                                $\C{// assortment of additions}$
603        T ?+=?( T &, T );
604        T ++?( T & );
605        T ?++( T & );
606};
607forall( otype T `| sumable( T )` )                      $\C{// use trait}$
608T sum( T a[$\,$], size_t size );
609\end{cfa}
610
611Using the return type for overload discrimination, it is possible to write a type-safe @alloc@ based on the C @malloc@:
612\begin{cfa}
613forall( dtype T | sized(T) ) T * alloc( void ) { return (T *)malloc( sizeof(T) ); }
614int * ip = alloc();                                                     $\C{// select type and size from left-hand side}$
615double * dp = alloc();
616struct S {...} * sp = alloc();
617\end{cfa}
618where the return type supplies the type/size of the allocation, which is impossible in most type systems.
619\end{comment}
620
621
622\section{Coroutines: A Stepping Stone}\label{coroutine}
623
624Advanced controlWhile the focus of this discussion is concurrency and parallelism, it is important to address coroutines, which are a significant building block of a concurrency system (but not concurrent among themselves).
625Coroutines are generalized routines allowing execution to be temporarily suspended and later resumed.
626Hence, unlike a normal routine, a coroutine may not terminate when it returns to its caller, allowing it to be restarted with the values and execution location present at the point of suspension.
627This capability is accomplished via the coroutine's stack, where suspend/resume context switch among stacks.
628Because threading design-challenges are present in coroutines, their design effort is relevant, and this effort can be easily exposed to programmers giving them a useful new programming paradigm because a coroutine handles the class of problems that need to retain state between calls, \eg plugins, device drivers, and finite-state machines.
629Therefore, the two fundamental features of the core \CFA coroutine-API are independent call-stacks and @suspend@/@resume@ operations.
630
631For example, a problem made easier with coroutines is unbounded generators, \eg generating an infinite sequence of Fibonacci numbers
632\begin{displaymath}
633\mathsf{fib}(n) = \left \{
634\begin{array}{ll}
6350                                       & n = 0         \\
6361                                       & n = 1         \\
637\mathsf{fib}(n-1) + \mathsf{fib}(n-2)   & n \ge 2       \\
638\end{array}
639\right.
640\end{displaymath}
641where Figure~\ref{f:C-fibonacci} shows conventional approaches for writing a Fibonacci generator in C.
642Figure~\ref{f:GlobalVariables} illustrates the following problems: unique unencapsulated global variables necessary to retain state between calls, only one Fibonacci generator, and execution state must be explicitly retained via explicit state variables.
643Figure~\ref{f:ExternalState} addresses these issues: unencapsulated program global variables become encapsulated structure variables, unique global variables are replaced by multiple Fibonacci objects, and explicit execution state is removed by precomputing the first two Fibonacci numbers and returning $\mathsf{fib}(n-2)$.
644
645\begin{figure}
646\centering
647\newbox\myboxA
648\begin{lrbox}{\myboxA}
649\begin{cfa}[aboveskip=0pt,belowskip=0pt]
650`int f1, f2, state = 1;`   // single global variables
651int fib() {
652        int fn;
653        `switch ( state )` {  // explicit execution state
654          case 1: fn = 0;  f1 = fn;  state = 2;  break;
655          case 2: fn = 1;  f2 = f1;  f1 = fn;  state = 3;  break;
656          case 3: fn = f1 + f2;  f2 = f1;  f1 = fn;  break;
657        }
658        return fn;
659}
660int main() {
661
662        for ( int i = 0; i < 10; i += 1 ) {
663                printf( "%d\n", fib() );
664        }
665}
666\end{cfa}
667\end{lrbox}
668
669\newbox\myboxB
670\begin{lrbox}{\myboxB}
671\begin{cfa}[aboveskip=0pt,belowskip=0pt]
672#define FIB_INIT `{ 0, 1 }`
673typedef struct { int f2, f1; } Fib;
674int fib( Fib * f ) {
675
676        int ret = f->f2;
677        int fn = f->f1 + f->f2;
678        f->f2 = f->f1; f->f1 = fn;
679
680        return ret;
681}
682int main() {
683        Fib f1 = FIB_INIT, f2 = FIB_INIT;
684        for ( int i = 0; i < 10; i += 1 ) {
685                printf( "%d %d\n", fib( &f1 ), fib( &f2 ) );
686        }
687}
688\end{cfa}
689\end{lrbox}
690
691\subfloat[3 States: global variables]{\label{f:GlobalVariables}\usebox\myboxA}
692\qquad
693\subfloat[1 State: external variables]{\label{f:ExternalState}\usebox\myboxB}
694\caption{C Fibonacci Implementations}
695\label{f:C-fibonacci}
696
697\bigskip
698
699\newbox\myboxA
700\begin{lrbox}{\myboxA}
701\begin{cfa}[aboveskip=0pt,belowskip=0pt]
702`coroutine` Fib { int fn; };
703void main( Fib & fib ) with( fib ) {
704        int f1, f2;
705        fn = 0;  f1 = fn;  `suspend()`;
706        fn = 1;  f2 = f1;  f1 = fn;  `suspend()`;
707        for ( ;; ) {
708                fn = f1 + f2;  f2 = f1;  f1 = fn;  `suspend()`;
709        }
710}
711int next( Fib & fib ) with( fib ) {
712        `resume( fib );`
713        return fn;
714}
715int main() {
716        Fib f1, f2;
717        for ( int i = 1; i <= 10; i += 1 ) {
718                sout | next( f1 ) | next( f2 );
719        }
720}
721\end{cfa}
722\end{lrbox}
723\newbox\myboxB
724\begin{lrbox}{\myboxB}
725\begin{cfa}[aboveskip=0pt,belowskip=0pt]
726`coroutine` Fib { int ret; };
727void main( Fib & f ) with( fib ) {
728        int fn, f1 = 1, f2 = 0;
729        for ( ;; ) {
730                ret = f2;
731
732                fn = f1 + f2;  f2 = f1;  f1 = fn; `suspend();`
733        }
734}
735int next( Fib & fib ) with( fib ) {
736        `resume( fib );`
737        return ret;
738}
739
740
741
742
743
744
745\end{cfa}
746\end{lrbox}
747\subfloat[3 States, internal variables]{\label{f:Coroutine3States}\usebox\myboxA}
748\qquad\qquad
749\subfloat[1 State, internal variables]{\label{f:Coroutine1State}\usebox\myboxB}
750\caption{\CFA Coroutine Fibonacci Implementations}
751\label{f:cfa-fibonacci}
752\end{figure}
753
754Using a coroutine, it is possible to express the Fibonacci formula directly without any of the C problems.
755Figure~\ref{f:Coroutine3States} creates a @coroutine@ type, @`coroutine` Fib { int fn; }@, which provides communication, @fn@, for the \newterm{coroutine main}, @main@, which runs on the coroutine stack, and possibly multiple interface routines, \eg @next@.
756Like the structure in Figure~\ref{f:ExternalState}, the coroutine type allows multiple instances, where instances of this type are passed to the (overloaded) coroutine main.
757The coroutine main's stack holds the state for the next generation, @f1@ and @f2@, and the code represents the three states in the Fibonacci formula via the three suspend points, to context switch back to the caller's @resume@.
758The interface routine @next@, takes a Fibonacci instance and context switches to it using @resume@;
759on restart, the Fibonacci field, @fn@, contains the next value in the sequence, which is returned.
760The first @resume@ is special because it allocates the coroutine stack and cocalls its coroutine main on that stack;
761when the coroutine main returns, its stack is deallocated.
762Hence, @Fib@ is an object at creation, transitions to a coroutine on its first resume, and transitions back to an object when the coroutine main finishes.
763Figure~\ref{f:Coroutine1State} shows the coroutine version of the C version in Figure~\ref{f:ExternalState}.
764Coroutine generators are called \newterm{output coroutines} because values are only returned.
765
766Figure~\ref{f:CFAFmt} shows an \newterm{input coroutine}, @Format@, for restructuring text into groups of characters of fixed-size blocks.
767For example, the input of the left is reformatted into the output on the right.
768\begin{quote}
769\tt
770\begin{tabular}{@{}l|l@{}}
771\multicolumn{1}{c|}{\textbf{\textrm{input}}} & \multicolumn{1}{c}{\textbf{\textrm{output}}} \\
772abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
773&
774\begin{tabular}[t]{@{}lllll@{}}
775abcd    & efgh  & ijkl  & mnop  & qrst  \\
776uvwx    & yzab  & cdef  & ghij  & klmn  \\
777opqr    & stuv  & wxyz  &               &
778\end{tabular}
779\end{tabular}
780\end{quote}
781The example takes advantage of resuming a coroutine in the constructor to prime the loops so the first character sent for formatting appears inside the nested loops.
782The destructor provides a newline, if formatted text ends with a full line.
783Figure~\ref{f:CFmt} shows the C equivalent formatter, where the loops of the coroutine are flattened (linearized) and rechecked on each call because execution location is not retained between calls.
784(Linearized code is the bane of device drivers.)
785
786\begin{figure}
787\centering
788\newbox\myboxA
789\begin{lrbox}{\myboxA}
790\begin{cfa}[aboveskip=0pt,belowskip=0pt]
791`coroutine` Format {
792        char ch;   // used for communication
793        int g, b;  // global because used in destructor
794};
795void main( Format & fmt ) with( fmt ) {
796        for ( ;; ) {
797                for ( g = 0; g < 5; g += 1 ) {      // group
798                        for ( b = 0; b < 4; b += 1 ) { // block
799                                `suspend();`
800                                sout | ch;              // separator
801                        }
802                        sout | "  ";               // separator
803                }
804                sout | nl;
805        }
806}
807void ?{}( Format & fmt ) { `resume( fmt );` }
808void ^?{}( Format & fmt ) with( fmt ) {
809        if ( g != 0 || b != 0 ) sout | nl;
810}
811void format( Format & fmt ) {
812        `resume( fmt );`
813}
814int main() {
815        Format fmt;
816        eof: for ( ;; ) {
817                sin | fmt.ch;
818          if ( eof( sin ) ) break eof;
819                format( fmt );
820        }
821}
822\end{cfa}
823\end{lrbox}
824
825\newbox\myboxB
826\begin{lrbox}{\myboxB}
827\begin{cfa}[aboveskip=0pt,belowskip=0pt]
828struct Format {
829        char ch;
830        int g, b;
831};
832void format( struct Format * fmt ) {
833        if ( fmt->ch != -1 ) {      // not EOF ?
834                printf( "%c", fmt->ch );
835                fmt->b += 1;
836                if ( fmt->b == 4 ) {  // block
837                        printf( "  " );      // separator
838                        fmt->b = 0;
839                        fmt->g += 1;
840                }
841                if ( fmt->g == 5 ) {  // group
842                        printf( "\n" );     // separator
843                        fmt->g = 0;
844                }
845        } else {
846                if ( fmt->g != 0 || fmt->b != 0 ) printf( "\n" );
847        }
848}
849int main() {
850        struct Format fmt = { 0, 0, 0 };
851        for ( ;; ) {
852                scanf( "%c", &fmt.ch );
853          if ( feof( stdin ) ) break;
854                format( &fmt );
855        }
856        fmt.ch = -1;
857        format( &fmt );
858}
859\end{cfa}
860\end{lrbox}
861\subfloat[\CFA Coroutine]{\label{f:CFAFmt}\usebox\myboxA}
862\qquad
863\subfloat[C Linearized]{\label{f:CFmt}\usebox\myboxB}
864\caption{Formatting text into lines of 5 blocks of 4 characters.}
865\label{f:fmt-line}
866\end{figure}
867
868The previous examples are \newterm{asymmetric (semi) coroutine}s because one coroutine always calls a resuming routine for another coroutine, and the resumed coroutine always suspends back to its last resumer, similar to call/return for normal routines.
869However, @resume@ and @suspend@ context switch among existing stack-frames, rather than create new ones so there is no stack growth.
870\newterm{Symmetric (full) coroutine}s have a coroutine call to a resuming routine for another coroutine, and its coroutine main calls another resuming routine, which eventually forms a resuming-call cycle.
871(The trivial cycle is a coroutine resuming itself.)
872This control flow is similar to recursion for normal routines, but again there is no stack growth from the context switch.
873
874\begin{figure}
875\centering
876\lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $
877\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
878\begin{cfa}
879`coroutine` Prod {
880        Cons & c;
881        int N, money, receipt;
882};
883void main( Prod & prod ) with( prod ) {
884        // 1st resume starts here
885        for ( int i = 0; i < N; i += 1 ) {
886                int p1 = random( 100 ), p2 = random( 100 );
887                sout | p1 | " " | p2;
888                int status = delivery( c, p1, p2 );
889                sout | " $" | money | nl | status;
890                receipt += 1;
891        }
892        stop( c );
893        sout | "prod stops";
894}
895int payment( Prod & prod, int money ) {
896        prod.money = money;
897        `resume( prod );`
898        return prod.receipt;
899}
900void start( Prod & prod, int N, Cons &c ) {
901        &prod.c = &c;
902        prod.[N, receipt] = [N, 0];
903        `resume( prod );`
904}
905int main() {
906        Prod prod;
907        Cons cons = { prod };
908        start( prod, 5, cons );
909}
910\end{cfa}
911&
912\begin{cfa}
913`coroutine` Cons {
914        Prod & p;
915        int p1, p2, status;
916        _Bool done;
917};
918void ?{}( Cons & cons, Prod & p ) {
919        &cons.p = &p;
920        cons.[status, done ] = [0, false];
921}
922void ^?{}( Cons & cons ) {}
923void main( Cons & cons ) with( cons ) {
924        // 1st resume starts here
925        int money = 1, receipt;
926        for ( ; ! done; ) {
927                sout | p1 | " " | p2 | nl | " $" | money;
928                status += 1;
929                receipt = payment( p, money );
930                sout | " #" | receipt;
931                money += 1;
932        }
933        sout | "cons stops";
934}
935int delivery( Cons & cons, int p1, int p2 ) {
936        cons.[p1, p2] = [p1, p2];
937        `resume( cons );`
938        return cons.status;
939}
940void stop( Cons & cons ) {
941        cons.done = true;
942        `resume( cons );`
943}
944\end{cfa}
945\end{tabular}
946\caption{Producer / consumer: resume-resume cycle, bi-directional communication}
947\label{f:ProdCons}
948\end{figure}
949
950Figure~\ref{f:ProdCons} shows a producer/consumer symmetric-coroutine performing bi-directional communication.
951Since the solution involves a full-coroutining cycle, the program main creates one coroutine in isolation, passes this coroutine to its partner, and closes the cycle at the call to @start@.
952The @start@ routine communicates both the number of elements to be produced and the consumer into the producer's coroutine-structure.
953Then the @resume@ to @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
954@prod@'s coroutine main starts, creates local variables that are retained between coroutine activations, and executes $N$ iterations, each generating two random values, calling the consumer to deliver the values, and printing the status returned from the consumer.
955
956The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
957For the first resume, @cons@'s stack is initialized, creating local variables retained between subsequent activations of the coroutine.
958The consumer iterates until the @done@ flag is set, prints the values delivered by the producer, increments status, and calls back to the producer via @payment@, and on return from @payment@, prints the receipt from the producer and increments @money@ (inflation).
959The call from the consumer to @payment@ introduces the cycle between producer and consumer.
960When @payment@ is called, the consumer copies values into the producer's communication variable and a resume is executed.
961The context switch restarts the producer at the point where it last context switched, so it continues in @delivery@ after the resume.
962
963@delivery@ returns the status value in @prod@'s coroutine main, where the status is printed.
964The loop then repeats calling @delivery@, where each call resumes the consumer coroutine.
965The context switch to the consumer continues in @payment@.
966The consumer increments and returns the receipt to the call in @cons@'s coroutine main.
967The loop then repeats calling @payment@, where each call resumes the producer coroutine.
968
969After iterating $N$ times, the producer calls @stop@.
970The @done@ flag is set to stop the consumer's execution and a resume is executed.
971The context switch restarts @cons@ in @payment@ and it returns with the last receipt.
972The consumer terminates its loops because @done@ is true, its @main@ terminates, so @cons@ transitions from a coroutine back to an object, and @prod@ reactivates after the resume in @stop@.
973@stop@ returns and @prod@'s coroutine main terminates.
974The program main restarts after the resume in @start@.
975@start@ returns and the program main terminates.
976
977
978\subsection{Coroutine Implementation}
979
980A significant implementation challenge for coroutines (and threads, see Section~\ref{threads}) is adding extra fields and executing code after/before the coroutine constructor/destructor and coroutine main to create/initialize/de-initialize/destroy extra fields and the stack.
981There are several solutions to this problem and the chosen option forced the \CFA coroutine design.
982
983Object-oriented inheritance provides extra fields and code in a restricted context, but it requires programmers to explicitly perform the inheritance:
984\begin{cfa}[morekeywords={class,inherits}]
985class mycoroutine inherits baseCoroutine { ... }
986\end{cfa}
987and the programming language (and possibly its tool set, \eg debugger) may need to understand @baseCoroutine@ because of the stack.
988Furthermore, the execution of constructors/destructors is in the wrong order for certain operations.
989For example, for threads if the thread is implicitly started, it must start \emph{after} all constructors, because the thread relies on a completely initialized object, but the inherited constructor runs \emph{before} the derived.
990
991An alternative is composition:
992\begin{cfa}
993struct mycoroutine {
994        ... // declarations
995        baseCoroutine dummy; // composition, last declaration
996}
997\end{cfa}
998which also requires an explicit declaration that must be the last one to ensure correct initialization order.
999However, there is nothing preventing wrong placement or multiple declarations.
1000
1001For coroutines as for threads, many implementations are based on routine pointers or routine objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
1002For example, Boost implements coroutines in terms of four functor object-types:
1003\begin{cfa}
1004asymmetric_coroutine<>::pull_type
1005asymmetric_coroutine<>::push_type
1006symmetric_coroutine<>::call_type
1007symmetric_coroutine<>::yield_type
1008\end{cfa}
1009Similarly, the canonical threading paradigm is often based on routine pointers, \eg @pthreads@~\cite{Butenhof97}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}.
1010However, the generic thread-handle (identifier) is limited (few operations), unless it is wrapped in a custom type.
1011\begin{cfa}
1012void mycor( coroutine_t cid, void * arg ) {
1013        int * value = (int *)arg;                               $\C{// type unsafe, pointer-size only}$
1014        // Coroutine body
1015}
1016int main() {
1017        int input = 0, output;
1018        coroutine_t cid = coroutine_create( &mycor, (void *)&input ); $\C{// type unsafe, pointer-size only}$
1019        coroutine_resume( cid, (void *)input, (void **)&output ); $\C{// type unsafe, pointer-size only}$
1020}
1021\end{cfa}
1022Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda-based coroutines adds very little.
1023
1024Note, the type @coroutine_t@ must be an abstract handle to the coroutine, because the coroutine descriptor and its stack are non-copyable.
1025Copying the coroutine descriptor results in copies being out of date with the current state of the stack.
1026Correspondingly, copying the stack results is copies being out of date with the coroutine descriptor, and pointers in the stack being out of date to data on the stack.
1027(There is no mechanism in C to find all stack-specific pointers and update them as part of a copy.)
1028
1029The selected approach is to use language support by introducing a new kind of aggregate (structure):
1030\begin{cfa}
1031coroutine Fibonacci {
1032        int fn; // communication variables
1033};
1034\end{cfa}
1035The @coroutine@ keyword means the compiler (and tool set) can find and inject code where needed.
1036The downside of this approach is that it makes coroutine a special case in the language.
1037Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language.
1038Furthermore, implementing coroutines without language supports also displays the power of a programming language.
1039While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can still be constructed without language support.
1040The reserved keyword simply eases use for the common case.
1041
1042Part of the mechanism to generalize coroutines is using a \CFA trait, which defines a coroutine as anything satisfying the trait @is_coroutine@, and this trait restricts the available set of coroutine-manipulation routines:
1043\begin{cfa}
1044trait is_coroutine( `dtype` T ) {
1045        void main( T & );
1046        coroutine_desc * get_coroutine( T & );
1047};
1048forall( `dtype` T | is_coroutine(T) ) void suspend( T & );
1049forall( `dtype` T | is_coroutine(T) ) void resume( T & );
1050\end{cfa}
1051The @dtype@ property provides no implicit copying operations and the @is_coroutine@ trait provides no explicit copying operations, so all coroutines must be passed by reference (pointer).
1052The routine definitions ensures there is a statically-typed @main@ routine that is the starting point (first stack frame) of a coroutine, and a mechanism to get (read) the currently executing coroutine handle.
1053The @main@ routine has no return value or additional parameters because the coroutine type allows an arbitrary number of interface routines with corresponding arbitrary typed input/output values versus fixed ones.
1054The advantage of this approach is that users can easily create different types of coroutines, \eg changing the memory layout of a coroutine is trivial when implementing the @get_coroutine@ routine, and possibly redefining @suspend@ and @resume@.
1055The \CFA keyword @coroutine@ implicitly implements the getter and forward declarations required for implementing the coroutine main:
1056\begin{cquote}
1057\begin{tabular}{@{}ccc@{}}
1058\begin{cfa}
1059coroutine MyCor {
1060        int value;
1061
1062};
1063\end{cfa}
1064&
1065{\Large $\Rightarrow$}
1066&
1067\begin{tabular}{@{}ccc@{}}
1068\begin{cfa}
1069struct MyCor {
1070        int value;
1071        coroutine_desc cor;
1072};
1073\end{cfa}
1074&
1075\begin{cfa}
1076static inline coroutine_desc *
1077get_coroutine( MyCor & this ) {
1078        return &this.cor;
1079}
1080\end{cfa}
1081&
1082\begin{cfa}
1083void main( MyCor * this );
1084
1085
1086
1087\end{cfa}
1088\end{tabular}
1089\end{tabular}
1090\end{cquote}
1091The combination of these two approaches allows an easy and concise specification to coroutining (and concurrency) for normal users, while more advanced users have tighter control on memory layout and initialization.
1092
1093
1094\section{Concurrency}
1095\label{s:Concurrency}
1096
1097At its core, concurrency is based on multiple call-stacks and scheduling threads executing on these stacks.
1098Multiple call stacks (or contexts) and a single thread of execution, called \newterm{coroutining}~\cite{Conway63,Marlin80}, does \emph{not} imply concurrency~\cite[\S~2]{Buhr05a}.
1099In coroutining, the single thread is self-scheduling across the stacks, so execution is deterministic, \ie the execution path from input to output is fixed and predictable.
1100A \newterm{stackless} coroutine executes on the caller's stack~\cite{Python} but this approach is restrictive, \eg preventing modularization and supporting only iterator/generator-style programming;
1101a \newterm{stackful} coroutine executes on its own stack, allowing full generality.
1102Only stackful coroutines are a stepping stone to concurrency.
1103
1104The transition to concurrency, even for execution with a single thread and multiple stacks, occurs when coroutines also context switch to a \newterm{scheduling oracle}, introducing non-determinism from the coroutine perspective~\cite[\S~3]{Buhr05a}.
1105Therefore, a minimal concurrency system is possible using coroutines (see Section \ref{coroutine}) in conjunction with a scheduler to decide where to context switch next.
1106The resulting execution system now follows a cooperative threading-model, called \newterm{non-preemptive scheduling}.
1107
1108Because the scheduler is special, it can either be a stackless or stackful coroutine.
1109For stackless, the scheduler performs scheduling on the stack of the current coroutine and switches directly to the next coroutine, so there is one context switch.
1110For stackful, the current coroutine switches to the scheduler, which performs scheduling, and it then switches to the next coroutine, so there are two context switches.
1111A stackful scheduler is often used for simplicity and security.
1112
1113Regardless of the approach used, a subset of concurrency related challenges start to appear.
1114For the complete set of concurrency challenges to occur, the missing feature is \newterm{preemption}, where context switching occurs randomly between any two instructions, often based on a timer interrupt, called \newterm{preemptive scheduling}.
1115While a scheduler introduces uncertainty in the order of execution, preemption introduces uncertainty about where context switches occur.
1116Interestingly, uncertainty is necessary for the runtime (operating) system to give the illusion of parallelism on a single processor and increase performance on multiple processors.
1117The reason is that only the runtime has complete knowledge about resources and how to best utilized them.
1118However, the introduction of unrestricted non-determinism results in the need for \newterm{mutual exclusion} and \newterm{synchronization} to restrict non-determinism for correctness;
1119otherwise, it is impossible to write meaningful programs.
1120Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows.
1121
1122An important missing feature in C is threading\footnote{While the C11 standard defines a \protect\lstinline@threads.h@ header, it is minimal and defined as optional.
1123As such, library support for threading is far from widespread.
1124At the time of writing the paper, neither \protect\lstinline@gcc@ nor \protect\lstinline@clang@ support \protect\lstinline@threads.h@ in their standard libraries.}.
1125In modern programming languages, a lack of threading is unacceptable~\cite{Sutter05, Sutter05b}, and therefore existing and new programming languages must have tools for writing efficient concurrent programs to take advantage of parallelism.
1126As 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.
1127Furthermore, because C is a system-level language, programmers expect to choose precisely which features they need and which cost they are willing to pay.
1128Hence, concurrent programs should be written using high-level mechanisms, and only step down to lower-level mechanisms when performance bottlenecks are encountered.
1129
1130
1131\subsection{Thread Interface}
1132\label{threads}
1133
1134Both user and kernel threads are supported, where user threads provide concurrency and kernel threads provide parallelism.
1135Like coroutines and for the same design reasons, the selected approach for user threads is to use language support by introducing a new kind of aggregate (structure) and a \CFA trait:
1136\begin{cquote}
1137\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
1138\begin{cfa}
1139thread myThread {
1140        // communication variables
1141};
1142
1143
1144\end{cfa}
1145&
1146\begin{cfa}
1147trait is_thread( `dtype` T ) {
1148      void main( T & );
1149      thread_desc * get_thread( T & );
1150      void ^?{}( T & `mutex` );
1151};
1152\end{cfa}
1153\end{tabular}
1154\end{cquote}
1155(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitor}.)
1156Like a coroutine, the statically-typed @main@ routine is the starting point (first stack frame) of a user thread.
1157The difference is that a coroutine borrows a thread from its caller, so the first thread resuming a coroutine creates an instance of @main@;
1158whereas, a user thread receives its own thread from the runtime system, which starts in @main@ as some point after the thread constructor is run.\footnote{
1159The \lstinline@main@ routine is already a special routine in C, \ie where the program's initial thread begins, so it is a natural extension of this semantics to use overloading to declare \lstinline@main@s for user coroutines and threads.}
1160No return value or additional parameters are necessary for this routine because the task type allows an arbitrary number of interface routines with corresponding arbitrary typed input/output values.
1161
1162\begin{comment} % put in appendix with coroutine version ???
1163As such the @main@ routine of a thread can be defined as
1164\begin{cfa}
1165thread foo {};
1166
1167void main(foo & this) {
1168        sout | "Hello World!";
1169}
1170\end{cfa}
1171
1172In 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.
1173With the static semantics it is trivial to write a thread type that takes a routine pointer as a parameter and executes it on its stack asynchronously.
1174\begin{cfa}
1175typedef void (*voidRtn)(int);
1176
1177thread RtnRunner {
1178        voidRtn func;
1179        int arg;
1180};
1181
1182void ?{}(RtnRunner & this, voidRtn inRtn, int arg) {
1183        this.func = inRtn;
1184        this.arg  = arg;
1185}
1186
1187void main(RtnRunner & this) {
1188        // thread starts here and runs the routine
1189        this.func( this.arg );
1190}
1191
1192void hello(/*unused*/ int) {
1193        sout | "Hello World!";
1194}
1195
1196int main() {
1197        RtnRunner f = {hello, 42};
1198        return 0?
1199}
1200\end{cfa}
1201A 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}.
1202\end{comment}
1203
1204For user threads to be useful, it must be possible to start and stop the underlying thread, and wait for it to complete execution.
1205While using an API such as @fork@ and @join@ is relatively common, such an interface is awkward and unnecessary.
1206A simple approach is to use allocation/deallocation principles, and have threads implicitly @fork@ after construction and @join@ before destruction.
1207\begin{cfa}
1208thread World {};
1209void main( World & this ) {
1210        sout | "World!";
1211}
1212int main() {
1213        World w`[10]`;                                                  $\C{// implicit forks after creation}$
1214        sout | "Hello ";                                        $\C{// "Hello " and 10 "World!" printed concurrently}$
1215}                                                                                       $\C{// implicit joins before destruction}$
1216\end{cfa}
1217This semantics ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
1218This tree-structure (lattice) create/delete from C block-structure is generalized 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.
1219\begin{cfa}
1220int main() {
1221        MyThread * heapLive;
1222        {
1223                MyThread blockLive;                                     $\C{// fork block-based thread}$
1224                heapLive = `new`( MyThread );           $\C{// fork heap-based thread}$
1225                ...
1226        }                                                                               $\C{// join block-based thread}$
1227        ...
1228        `delete`( heapLive );                                   $\C{// join heap-based thread}$
1229}
1230\end{cfa}
1231The heap-based approach allows arbitrary thread-creation topologies, with respect to fork/join-style concurrency.
1232
1233Figure~\ref{s:ConcurrentMatrixSummation} shows concurrently adding the rows of a matrix and then totalling the subtotals sequentially, after all the row threads have terminated.
1234The program uses heap-based threads because each thread needs different constructor values.
1235(Python provides a simple iteration mechanism to initialize array elements to different values allowing stack allocation.)
1236The allocation/deallocation pattern appears unusual because allocated objects are immediately deallocated without any intervening code.
1237However, for threads, the deletion provides implicit synchronization, which is the intervening code.
1238While the subtotals are added in linear order rather than completion order, which slightly inhibits concurrency, the computation is restricted by the critical-path thread (\ie the thread that takes the longest), and so any inhibited concurrency is very small as totalling the subtotals is trivial.
1239
1240\begin{figure}
1241\begin{cfa}
1242`thread` Adder { int * row, cols, & subtotal; } $\C{// communication variables}$
1243void ?{}( Adder & adder, int row[], int cols, int & subtotal ) {
1244    adder.[ row, cols, &subtotal ] = [ row, cols, &subtotal ];
1245}
1246void main( Adder & adder ) with( adder ) {
1247    subtotal = 0;
1248    for ( int c = 0; c < cols; c += 1 ) { subtotal += row[c]; }
1249}
1250int main() {
1251    const int rows = 10, cols = 1000;
1252    int matrix[rows][cols], subtotals[rows], total = 0;
1253    // read matrix
1254    Adder * adders[rows];
1255    for ( int r = 0; r < rows; r += 1 ) {       $\C{// start threads to sum rows}$
1256                adders[r] = `new( matrix[r], cols, &subtotals[r] );`
1257    }
1258    for ( int r = 0; r < rows; r += 1 ) {       $\C{// wait for threads to finish}$
1259                `delete( adders[r] );`                          $\C{// termination join}$
1260                total += subtotals[r];                          $\C{// total subtotal}$
1261    }
1262    sout | total;
1263}
1264\end{cfa}
1265\caption{Concurrent Matrix Summation}
1266\label{s:ConcurrentMatrixSummation}
1267\end{figure}
1268
1269
1270\section{Mutual Exclusion / Synchronization}
1271
1272Uncontrolled non-deterministic execution is meaningless.
1273To reestablish meaningful execution requires mechanisms to reintroduce determinism, \ie restrict non-determinism, called mutual exclusion and synchronization, where mutual exclusion is an access-control mechanism on data shared by threads, and synchronization is a timing relationship among threads~\cite[\S~4]{Buhr05a}.
1274Since many deterministic challenges appear with the use of mutable shared state, some languages/libraries disallow it, \eg Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, Akka~\cite{Akka} (Scala).
1275In these paradigms, interaction among concurrent objects is performed by stateless message-passing~\cite{Thoth,Harmony,V-Kernel} or other paradigms closely related to networking concepts, \eg channels~\cite{CSP,Go}.
1276However, in call/return-based languages, these approaches force a clear distinction, \ie introduce a new programming paradigm between regular and concurrent computation, \eg routine call versus message passing.
1277Hence, a programmer must learn and manipulate two sets of design patterns.
1278While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
1279In contrast, approaches based on stateful models more closely resemble the standard call/return programming-model, resulting in a single programming paradigm.
1280
1281At the lowest level, concurrent control is implemented by atomic operations, upon which different kinds of locking mechanisms are constructed, \eg semaphores~\cite{Dijkstra68b}, barriers, and path expressions~\cite{Campbell74}.
1282However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}.
1283A newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
1284While this approach is pursued in hardware~\cite{Nakaike15} and system languages, like \CC~\cite{Cpp-Transactions}, the performance and feature set is still too restrictive to be the main concurrency paradigm for system languages, which is why it is rejected as the core paradigm for concurrency in \CFA.
1285
1286One of the most natural, elegant, and efficient mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor}.
1287First proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}, many concurrent programming-languages provide monitors as an explicit language construct: \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}.
1288In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as mutex locks or semaphores to simulate monitors.
1289For these reasons, \CFA selected monitors as the core high-level concurrency-construct, upon which higher-level approaches can be easily constructed.
1290
1291
1292\subsection{Mutual Exclusion}
1293
1294A group of instructions manipulating a specific instance of shared data that must be performed atomically is called an (individual) \newterm{critical-section}~\cite{Dijkstra65}.
1295The generalization is called a \newterm{group critical-section}~\cite{Joung00}, where multiple tasks with the same session may use the resource simultaneously, but different sessions may not use the resource simultaneously.
1296The readers/writer problem~\cite{Courtois71} is an instance of a group critical-section, where readers have the same session and all writers have a unique session.
1297\newterm{Mutual exclusion} enforces that the correct kind and number of threads are using a critical section.
1298
1299However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
1300Methods range from low-level locks, which are fast and flexible but require significant attention for correctness, to higher-level concurrency techniques, which sacrifice some performance to improve ease of use.
1301Ease of use comes by either guaranteeing some problems cannot occur, \eg deadlock free, or by offering a more explicit coupling between shared data and critical section.
1302For example, the \CC @std::atomic<T>@ offers an easy way to express mutual-exclusion on a restricted set of operations, \eg reading/writing, for numerical types.
1303However, a significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock.
1304Easing composability is another feature higher-level mutual-exclusion mechanisms can offer.
1305
1306
1307\subsection{Synchronization}
1308
1309Synchronization enforces relative ordering of execution, and synchronization tools provide numerous mechanisms to establish these timing relationships.
1310Low-level synchronization primitives offer good performance and flexibility at the cost of ease of use;
1311higher-level mechanisms often simplify usage by adding better coupling between synchronization and data, \eg message passing, or offering a simpler solution to otherwise involved challenges, \eg barrier lock.
1312Often synchronization is used to order access to a critical section, \eg ensuring a reader thread is the next kind of thread to enter a critical section.
1313If a writer thread is scheduled for next access, but another reader thread acquires the critical section first, that reader \newterm{barged}.
1314Barging can result in staleness/freshness problems, where a reader barges ahead of a writer and reads temporally stale data, or a writer barges ahead of another writer overwriting data with a fresh value preventing the previous value from ever being read (lost computation).
1315Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
1316This challenge is often split into two different approaches: barging avoidance and barging prevention.
1317Algorithms that allow a barger, but divert it until later using current synchronization state (flags), are avoiding the barger;
1318algorithms that preclude a barger from entering during synchronization in the critical section prevent barging completely.
1319Techniques like baton-passing locks~\cite{Andrews89} between threads instead of unconditionally releasing locks is an example of barging prevention.
1320
1321
1322\section{Monitor}
1323\label{s:Monitor}
1324
1325A \textbf{monitor} is a set of routines that ensure mutual exclusion when accessing shared state.
1326More precisely, a monitor is a programming technique that binds mutual exclusion to routine scope, as opposed to locks, where mutual-exclusion is defined by acquire/release calls, independent of lexical context (analogous to block and heap storage allocation).
1327The strong association with the call/return paradigm eases programmability, readability and maintainability, at a slight cost in flexibility and efficiency.
1328
1329Note, like coroutines/threads, both locks and monitors require an abstract handle to reference them, because at their core, both mechanisms are manipulating non-copyable shared-state.
1330Copying a lock is insecure because it is possible to copy an open lock and then use the open copy when the original lock is closed to simultaneously access the shared data.
1331Copying a monitor is secure because both the lock and shared data are copies, but copying the shared data is meaningless because it no longer represents a unique entity.
1332As for coroutines/tasks, the @dtype@ property provides no implicit copying operations and the @is_monitor@ trait provides no explicit copying operations, so all locks/monitors must be passed by reference (pointer).
1333\begin{cfa}
1334trait is_monitor( `dtype` T ) {
1335        monitor_desc * get_monitor( T & );
1336        void ^?{}( T & mutex );
1337};
1338\end{cfa}
1339
1340
1341\subsection{Mutex Acquisition}
1342\label{s:MutexAcquisition}
1343
1344While correctness implies a monitor's mutual exclusion is acquired and released, there are implementation options about when and where the locking/unlocking occurs.
1345(Much of this discussion also applies to basic locks.)
1346For example, a monitor may need to be passed through multiple helper routines before it becomes necessary to acquire the monitor mutual-exclusion.
1347\begin{cfa}[morekeywords=nomutex]
1348monitor Aint { int cnt; };                                      $\C{// atomic integer counter}$
1349void ?{}( Aint & `nomutex` this ) with( this ) { cnt = 0; } $\C{// constructor}$
1350int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions}$
1351void ?{}( int & this, Aint & `mutex`$\(_{opt}\)$ v ) { this = v.cnt; }
1352int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; }
1353int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$
1354\end{cfa}
1355The @Aint@ constructor, @?{}@, uses the \lstinline[morekeywords=nomutex]@nomutex@ qualifier indicating mutual exclusion is unnecessary during construction because an object is inaccessible (private) until after it is initialized.
1356(While a constructor may publish its address into a global variable, doing so generates a race-condition.)
1357The conversion operators for initializing and assigning with a normal integer only need @mutex@, if reading/writing the implementation type is not atomic.
1358Finally, the prefix increment operato, @++?@, is normally @mutex@ to protect the incrementing from race conditions, unless there is an atomic increment instruction for the implementation type.
1359
1360The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics, which is similar to the \CC template @std::atomic@.
1361\begin{cfa}
1362Aint x, y, z;
1363++x; ++y; ++z;                                                          $\C{// safe increment by multiple threads}$
1364x = 2; y = 2; z = 2;                                            $\C{// conversions}$
1365int i = x, j = y, k = z;
1366i = x; j = y; k = z;
1367\end{cfa}
1368
1369For maximum usability, monitors have \newterm{multi-acquire} semantics allowing a thread to acquire it multiple times without deadlock.
1370\begin{cfa}
1371monitor M { ... } m;
1372void foo( M & mutex m ) { ... }                         $\C{// acquire mutual exclusion}$
1373void bar( M & mutex m ) {                                       $\C{// acquire mutual exclusion}$
1374        ... `foo( m );` ...                                             $\C{// reacquire mutual exclusion}$
1375}
1376`bar( m );`                                                                     $\C{// nested monitor call}$
1377\end{cfa}
1378
1379The benefit of mandatory monitor qualifiers is self-documentation, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameters is redundant.
1380Instead, the semantics have one qualifier as the default, and the other required.
1381For example, make the safe @mutex@ qualifier the default because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
1382Alternatively, make the unsafe \lstinline[morekeywords=nomutex]@nomutex@ qualifier the default because it is the \emph{normal} parameter semantics while @mutex@ parameters are rare.
1383Providing a default qualifier implies knowing whether a parameter is a monitor.
1384Since \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.
1385For this reason, \CFA requires programmers to identify the kind of parameter with the @mutex@ keyword and uses no keyword to mean \lstinline[morekeywords=nomutex]@nomutex@.
1386
1387The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@.
1388Given:
1389\begin{cfa}
1390monitor M { ... }
1391int f1( M & mutex m );
1392int f2( M * mutex m );
1393int f3( M * mutex m[] );
1394int f4( stack( M * ) & mutex m );
1395\end{cfa}
1396the issue is that some of these parameter types are composed of multiple objects.
1397For @f1@, there is only a single parameter object.
1398Adding indirection in @f2@ still identifies a single object.
1399However, the matrix in @f3@ introduces multiple objects.
1400While shown shortly, multiple acquisition is possible;
1401however array lengths are often unknown in C.
1402This issue is exacerbated in @f4@, where the data structure must be safely traversed to acquire all of its elements.
1403
1404To make the issue tractable, \CFA only acquires one monitor per parameter with at most one level of indirection.
1405However, there is an ambiguity in the C type-system with respects to arrays.
1406Is the argument for @f2@ a single object or an array of objects?
1407If it is an array, only the first element of the array is acquired, which seems unsafe;
1408hence, @mutex@ is disallowed for array parameters.
1409\begin{cfa}
1410int f1( M & mutex m );                                          $\C{// allowed: recommended case}$
1411int f2( M * mutex m );                                          $\C{// disallowed: could be an array}$
1412int f3( M mutex m[$\,$] );                                      $\C{// disallowed: array length unknown}$
1413int f4( M ** mutex m );                                         $\C{// disallowed: could be an array}$
1414int f5( M * mutex m[$\,$] );                            $\C{// disallowed: array length unknown}$
1415\end{cfa}
1416% Note, not all array routines have distinct types: @f2@ and @f3@ have the same type, as do @f4@ and @f5@.
1417% However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
1418
1419For object-oriented monitors, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
1420\CFA has no receiver, and hence, must use an explicit mechanism to specify which object acquires mutual exclusion.
1421A positive consequence of this design decision is the ability to support multi-monitor routines.
1422\begin{cfa}
1423int f( M & mutex x, M & mutex y );              $\C{// multiple monitor parameter of any type}$
1424M m1, m2;
1425f( m1, m2 );
1426\end{cfa}
1427(While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.)
1428In practice, writing multi-locking routines that do not deadlock is tricky.
1429Having language support for such a feature is therefore a significant asset for \CFA.
1430
1431The capability to acquire multiple locks before entering a critical section is called \newterm{bulk acquire} (see Section~\ref{s:Implementation} for implementation details).
1432In the previous example, \CFA guarantees the order of acquisition is consistent across calls to different routines using the same monitors as arguments.
1433This consistent ordering means acquiring multiple monitors is safe from deadlock.
1434However, users can force the acquiring order.
1435For example, notice the use of @mutex@/\lstinline[morekeywords=nomutex]@nomutex@ and how this affects the acquiring order:
1436\begin{cfa}
1437void foo( M & mutex m1, M & mutex m2 );         $\C{// acquire m1 and m2}$
1438void bar( M & mutex m1, M & /* nomutex */ m2 ) { $\C{// acquire m1}$
1439        ... foo( m1, m2 ); ...                                  $\C{// acquire m2}$
1440}
1441void baz( M & /* nomutex */ m1, M & mutex m2 ) { $\C{// acquire m2}$
1442        ... foo( m1, m2 ); ...                                  $\C{// acquire m1}$
1443}
1444\end{cfa}
1445The multi-acquire semantics allows @bar@ or @baz@ to acquire a monitor lock and reacquire it in @foo@.
1446In the calls to @bar@ and @baz@, the monitors are acquired in opposite order.
1447
1448However, such use leads to lock acquiring order problems resulting in deadlock~\cite{Lister77}, where detecting it requires dynamic tracking of monitor calls, and dealing with it requires rollback semantics~\cite{Dice10}.
1449In \CFA, a safety aid is provided by using bulk acquire of all monitors to shared objects, whereas other monitor systems provide no aid.
1450While \CFA provides only a partial solution, it handles many useful cases, \eg:
1451\begin{cfa}
1452monitor BankAccount { ... };
1453void deposit( BankAccount & `mutex` b, int deposit );
1454void transfer( BankAccount & `mutex` my, BankAccount & `mutex` your, int me2you ) {
1455        deposit( my, `-`me2you );                               $\C{// debit}$
1456        deposit( your, me2you );                                $\C{// credit}$
1457}
1458\end{cfa}
1459This example shows a trivial solution to the bank-account transfer problem.
1460Without multi- and bulk acquire, the solution to this problem requires careful engineering.
1461
1462
1463\subsection{\protect\lstinline@mutex@ statement}
1464\label{mutex-stmt}
1465
1466The monitor call-semantics associate all locking semantics to routines.
1467Like Java, \CFA offers an alternative @mutex@ statement to reduce refactoring and naming.
1468\begin{cquote}
1469\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
1470\begin{cfa}
1471monitor M { ... };
1472void foo( M & mutex m1, M & mutex m2 ) {
1473        // critical section
1474}
1475void bar( M & m1, M & m2 ) {
1476        foo( m1, m2 );
1477}
1478\end{cfa}
1479&
1480\begin{cfa}
1481
1482void bar( M & m1, M & m2 ) {
1483        mutex( m1, m2 ) {       // remove refactoring and naming
1484                // critical section
1485        }
1486}
1487
1488\end{cfa}
1489\\
1490\multicolumn{1}{c}{\textbf{routine call}} & \multicolumn{1}{c}{\lstinline@mutex@ \textbf{statement}}
1491\end{tabular}
1492\end{cquote}
1493
1494
1495\section{Scheduling}
1496\label{s:Scheduling}
1497
1498While monitor mutual-exclusion provides safe access to shared data, the monitor data may indicate that a thread accessing it cannot proceed.
1499For example, Figure~\ref{f:GenericBoundedBuffer} shows a bounded buffer that may be full/empty so produce/consumer threads must block.
1500Leaving the monitor and trying again (busy waiting) is impractical for high-level programming.
1501Monitors eliminate busy waiting by providing synchronization to schedule threads needing access to the shared data, where threads block versus spinning.
1502Synchronization is generally achieved with internal~\cite{Hoare74} or external~\cite[\S~2.9.2]{uC++} scheduling, where \newterm{scheduling} defines which thread acquires the critical section next.
1503\newterm{Internal scheduling} is characterized by each thread entering the monitor and making an individual decision about proceeding or blocking, while \newterm{external scheduling} is characterized by an entering thread making a decision about proceeding for itself and on behalf of other threads attempting entry.
1504
1505Figure~\ref{f:BBInt} shows a \CFA generic bounded-buffer with internal scheduling, where producers/consumers enter the monitor, see the buffer is full/empty, and block on an appropriate condition lock, @full@/@empty@.
1506The @wait@ routine atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the routine's parameter list.
1507The appropriate condition lock is signalled to unblock an opposite kind of thread after an element is inserted/removed from the buffer.
1508Signalling is unconditional, because signalling an empty condition lock does nothing.
1509
1510Signalling semantics cannot have the signaller and signalled thread in the monitor simultaneously, which means:
1511\begin{enumerate}
1512\item
1513The signalling thread returns immediately, and the signalled thread continues.
1514\item
1515The signalling thread continues and the signalled thread is marked for urgent unblocking at the next scheduling point (exit/wait).
1516\item
1517The signalling thread blocks but is marked for urgrent unblocking at the next scheduling point and the signalled thread continues.
1518\end{enumerate}
1519The first approach is too restrictive, as it precludes solving a reasonable class of problems, \eg dating service (see Figure~\ref{f:DatingService}).
1520\CFA supports the next two semantics as both are useful.
1521Finally, while it is common to store a @condition@ as a field of the monitor, in \CFA, a @condition@ variable can be created/stored independently.
1522Furthermore, a condition variable is tied to a \emph{group} of monitors on first use, called \newterm{branding}, which means that using internal scheduling with distinct sets of monitors requires one condition variable per set of monitors.
1523
1524\begin{figure}
1525\centering
1526\newbox\myboxA
1527\begin{lrbox}{\myboxA}
1528\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1529forall( otype T ) { // distribute forall
1530        monitor Buffer {
1531                `condition` full, empty;
1532                int front, back, count;
1533                T elements[10];
1534        };
1535        void ?{}( Buffer(T) & buffer ) with(buffer) {
1536                [front, back, count] = 0;
1537        }
1538
1539        void insert( Buffer(T) & mutex buffer, T elem )
1540                                with(buffer) {
1541                if ( count == 10 ) `wait( empty )`;
1542                // insert elem into buffer
1543                `signal( full )`;
1544        }
1545        T remove( Buffer(T) & mutex buffer ) with(buffer) {
1546                if ( count == 0 ) `wait( full )`;
1547                // remove elem from buffer
1548                `signal( empty )`;
1549                return elem;
1550        }
1551}
1552\end{cfa}
1553\end{lrbox}
1554
1555\newbox\myboxB
1556\begin{lrbox}{\myboxB}
1557\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1558forall( otype T ) { // distribute forall
1559        monitor Buffer {
1560
1561                int front, back, count;
1562                T elements[10];
1563        };
1564        void ?{}( Buffer(T) & buffer ) with(buffer) {
1565                [front, back, count] = 0;
1566        }
1567        T remove( Buffer(T) & mutex buffer ); // forward
1568        void insert( Buffer(T) & mutex buffer, T elem )
1569                                with(buffer) {
1570                if ( count == 10 ) `waitfor( remove, buffer )`;
1571                // insert elem into buffer
1572
1573        }
1574        T remove( Buffer(T) & mutex buffer ) with(buffer) {
1575                if ( count == 0 ) `waitfor( insert, buffer )`;
1576                // remove elem from buffer
1577
1578                return elem;
1579        }
1580}
1581\end{cfa}
1582\end{lrbox}
1583
1584\subfloat[Internal Scheduling]{\label{f:BBInt}\usebox\myboxA}
1585%\qquad
1586\subfloat[External Scheduling]{\label{f:BBExt}\usebox\myboxB}
1587\caption{Generic Bounded-Buffer}
1588\label{f:GenericBoundedBuffer}
1589\end{figure}
1590
1591Figure~\ref{f:BBExt} shows a \CFA generic bounded-buffer with external scheduling, where producers/consumers detecting a full/empty buffer block and prevent more producers/consumers from entering the monitor until there is a free/empty slot in the buffer.
1592External scheduling is controlled by the @waitfor@ statement, which atomically blocks the calling thread, releases the monitor lock, and restricts the routine calls that can next acquire mutual exclusion.
1593If the buffer is full, only calls to @remove@ can acquire the buffer, and if the buffer is empty, only calls to @insert@ can acquire the buffer.
1594Threads making calls to routines that are currently excluded, block outside of (external to) the monitor on a calling queue, versus blocking on condition queues inside of (internal to) the monitor.
1595External scheduling allows users to wait for events from other threads without concern of unrelated events occurring.
1596The mechnaism can be done in terms of control flow, \eg Ada @accept@ or \uC @_Accept@, or in terms of data, \eg Go channels.
1597While both mechanisms have strengths and weaknesses, this project uses a control-flow mechanism to stay consistent with other language semantics.
1598Two challenges specific to \CFA for external scheduling are loose object-definitions (see Section~\ref{s:LooseObjectDefinitions}) and multiple-monitor routines (see Section~\ref{s:Multi-MonitorScheduling}).
1599
1600For internal scheduling, non-blocking signalling (as in the producer/consumer example) is used when the signaller is providing the cooperation for a waiting thread;
1601the signaller enters the monitor and changes state, detects a waiting threads that can use the state, performs a non-blocking signal on the condition queue for the waiting thread, and exits the monitor to run concurrently.
1602The waiter unblocks next from the urgent queue, uses/takes the state, and exits the monitor.
1603Blocking signalling is the reverse, where the waiter is providing the cooperation for the signalling thread;
1604the signaller enters the monitor, detects a waiting thread providing the necessary state, performs a blocking signal to place it on the urgent queue and unblock the waiter.
1605The waiter changes state and exits the monitor, and the signaller unblocks next from the urgent queue to use/take the state.
1606
1607Figure~\ref{f:DatingService} shows a dating service demonstrating non-blocking and blocking signalling.
1608The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers.
1609A thread blocks until an appropriate partner arrives.
1610The complexity is exchanging phone numbers in the monitor because of the mutual-exclusion property.
1611For signal scheduling, the @exchange@ condition is necessary to block the thread finding the match, while the matcher unblocks to take the opposite number, post its phone number, and unblock the partner.
1612For signal-block scheduling, the implicit urgent-queue replaces the explict @exchange@-condition and @signal_block@ puts the finding thread on the urgent condition and unblocks the matcher.
1613
1614The dating service is an example of a monitor that cannot be written using external scheduling because it requires knowledge of calling parameters to make scheduling decisions, and parameters of waiting threads are unavailable;
1615as well, an arriving thread may not find a partner and must wait, which requires a condition variable, and condition variables imply internal scheduling.
1616
1617\begin{figure}
1618\centering
1619\newbox\myboxA
1620\begin{lrbox}{\myboxA}
1621\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1622enum { CCodes = 20 };
1623monitor DS {
1624        int GirlPhNo, BoyPhNo;
1625        condition Girls[CCodes], Boys[CCodes];
1626        condition exchange;
1627};
1628int girl( DS & mutex ds, int phNo, int ccode ) {
1629        if ( is_empty( Boys[ccode] ) ) {
1630                wait( Girls[ccode] );
1631                GirlPhNo = phNo;
1632                `signal( exchange );`
1633        } else {
1634                GirlPhNo = phNo;
1635                `signal( Boys[ccode] );`
1636                `wait( exchange );`
1637        } // if
1638        return BoyPhNo;
1639}
1640int boy( DS & mutex ds, int phNo, int ccode ) {
1641        // as above with boy/girl interchanged
1642}
1643\end{cfa}
1644\end{lrbox}
1645
1646\newbox\myboxB
1647\begin{lrbox}{\myboxB}
1648\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1649
1650monitor DS {
1651        int GirlPhNo, BoyPhNo;
1652        condition Girls[CCodes], Boys[CCodes];
1653
1654};
1655int girl( DS & mutex ds, int phNo, int ccode ) {
1656        if ( is_empty( Boys[ccode] ) ) { // no compatible
1657                wait( Girls[ccode] ); // wait for boy
1658                GirlPhNo = phNo; // make phone number available
1659
1660        } else {
1661                GirlPhNo = phNo; // make phone number available
1662                `signal_block( Boys[ccode] );` // restart boy
1663
1664        } // if
1665        return BoyPhNo;
1666}
1667int boy( DS & mutex ds, int phNo, int ccode ) {
1668        // as above with boy/girl interchanged
1669}
1670\end{cfa}
1671\end{lrbox}
1672
1673\subfloat[\lstinline@signal@]{\label{f:DatingSignal}\usebox\myboxA}
1674\qquad
1675\subfloat[\lstinline@signal_block@]{\label{f:DatingSignalBlock}\usebox\myboxB}
1676\caption{Dating service. }
1677\label{f:DatingService}
1678\end{figure}
1679
1680Both internal and external scheduling extend to multiple monitors in a natural way.
1681\begin{cquote}
1682\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
1683\begin{cfa}
1684monitor M { `condition e`; ... };
1685void foo( M & mutex m1, M & mutex m2 ) {
1686        ... wait( `e` ); ...   // wait( e, m1, m2 )
1687        ... wait( `e, m1` ); ...
1688        ... wait( `e, m2` ); ...
1689}
1690\end{cfa}
1691&
1692\begin{cfa}
1693void rtn$\(_1\)$( M & mutex m1, M & mutex m2 );
1694void rtn$\(_2\)$( M & mutex m1 );
1695void bar( M & mutex m1, M & mutex m2 ) {
1696        ... waitfor( `rtn` ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\), m1, m2 )}$
1697        ... waitfor( `rtn, m1` ); ... // $\LstCommentStyle{waitfor( rtn\(_2\), m1 )}$
1698}
1699\end{cfa}
1700\end{tabular}
1701\end{cquote}
1702For @wait( e )@, the default semantics is to atomically block the signaller and release all acquired mutex types in the parameter list, \ie @wait( e, m1, m2 )@.
1703To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
1704Wait statically verifies the released monitors are the acquired mutex-parameters so unconditional release is safe.
1705Finally, a signaller,
1706\begin{cfa}
1707void baz( M & mutex m1, M & mutex m2 ) {
1708        ... signal( e ); ...
1709}
1710\end{cfa}
1711must have acquired at least the same locks as the waiting thread signalled from the condition queue.
1712
1713Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex types in the parameter list, \ie @waitfor( rtn, m1, m2 )@.
1714To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn, m1 )@.
1715@waitfor@ statically verifies the released monitors are the same as the acquired mutex-parameters of the given routine or routine pointer.
1716To statically verify the released monitors match with the accepted routine's mutex parameters, the routine (pointer) prototype must be accessible.
1717% When an overloaded routine appears in an @waitfor@ statement, calls to any routine with that name are accepted.
1718% The rationale is that members with the same name should perform a similar function, and therefore, all should be eligible to accept a call.
1719Overloaded routines can be disambiguated using a cast:
1720\begin{cfa}
1721void rtn( M & mutex m );
1722`int` rtn( M & mutex m );
1723waitfor( (`int` (*)( M & mutex ))rtn, m );
1724\end{cfa}
1725
1726The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock.
1727\begin{cfa}
1728void foo( M & mutex m1, M & mutex m2 ) {
1729        ... wait( `e, m1` ); ...                                $\C{// release m1, keeping m2 acquired )}$
1730void bar( M & mutex m1, M & mutex m2 ) {        $\C{// must acquire m1 and m2 )}$
1731        ... signal( `e` ); ...
1732\end{cfa}
1733The @wait@ only releases @m1@ so the signalling thread cannot acquire both @m1@ and @m2@ to  enter @bar@ to get to the @signal@.
1734While deadlock issues can occur with multiple/nesting acquisition, this issue results from the fact that locks, and by extension monitors, are not perfectly composable.
1735
1736Finally, an important aspect of monitor implementation is barging, \ie can calling threads barge ahead of signalled threads?
1737If barging is allowed, synchronization between a signaller and signallee is difficult, often requiring multiple unblock/block cycles (looping around a wait rechecking if a condition is met).
1738In fact, signals-as-hints is completely opposite from that proposed by Hoare in the seminal paper on monitors:
1739\begin{quote}
1740However, we decree that a signal operation be followed immediately by resumption of a waiting program, without possibility of an intervening procedure call from yet a third program.
1741It is only in this way that a waiting program has an absolute guarantee that it can acquire the resource just released by the signalling program without any danger that a third program will interpose a monitor entry and seize the resource instead.~\cite[p.~550]{Hoare74}
1742\end{quote}
1743\CFA scheduling \emph{precludes} barging, which simplifies synchronization among threads in the monitor and increases correctness.
1744Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implict form of barging.
1745For example, there are no loops in either bounded buffer solution in Figure~\ref{f:GenericBoundedBuffer}.
1746Supporting 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.
1747
1748
1749\subsection{Barging Prevention}
1750
1751Figure~\ref{f:BargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signalling semantics.
1752The complexity begins at the end of the inner @mutex@ statement, where the semantics of internal scheduling need to be extended for multiple monitors.
1753The problem is that bulk acquire is used in the inner @mutex@ statement where one of the monitors is already acquired.
1754When the signalling thread reaches the end of the inner @mutex@ statement, it should transfer ownership of @m1@ and @m2@ to the waiting threads to prevent barging into the outer @mutex@ statement by another thread.
1755However, both the signalling and waiting thread W1 still need monitor @m1@.
1756
1757\begin{figure}
1758\newbox\myboxA
1759\begin{lrbox}{\myboxA}
1760\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1761monitor M m1, m2;
1762condition c;
1763mutex( m1 ) { // $\LstCommentStyle{\color{red}outer}$
1764        ...
1765        mutex( m1, m2 ) { // $\LstCommentStyle{\color{red}inner}$
1766                ... `signal( c )`; ...
1767                // m1, m2 acquired
1768        } // $\LstCommentStyle{\color{red}release m2}$
1769        // m1 acquired
1770} // release m1
1771\end{cfa}
1772\end{lrbox}
1773
1774\newbox\myboxB
1775\begin{lrbox}{\myboxB}
1776\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1777
1778
1779mutex( m1 ) {
1780        ...
1781        mutex( m1, m2 ) {
1782                ... `wait( c )`; // block and release m1, m2
1783                // m1, m2 acquired
1784        } // $\LstCommentStyle{\color{red}release m2}$
1785        // m1 acquired
1786} // release m1
1787\end{cfa}
1788\end{lrbox}
1789
1790\newbox\myboxC
1791\begin{lrbox}{\myboxC}
1792\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1793
1794
1795mutex( m2 ) {
1796        ... `wait( c )`; ...
1797        // m2 acquired
1798} // $\LstCommentStyle{\color{red}release m2}$
1799
1800
1801
1802
1803\end{cfa}
1804\end{lrbox}
1805
1806\begin{cquote}
1807\subfloat[Signalling Thread]{\label{f:SignallingThread}\usebox\myboxA}
1808\hspace{2\parindentlnth}
1809\subfloat[Waiting Thread (W1)]{\label{f:WaitingThread}\usebox\myboxB}
1810\hspace{2\parindentlnth}
1811\subfloat[Waiting Thread (W2)]{\label{f:OtherWaitingThread}\usebox\myboxC}
1812\end{cquote}
1813\caption{Barging Prevention}
1814\label{f:BargingPrevention}
1815\end{figure}
1816
1817One scheduling solution is for the signaller to keep ownership of all locks until the last lock is ready to be transferred, because this semantics fits most closely to the behaviour of single-monitor scheduling.
1818However, Figure~\ref{f:OtherWaitingThread} shows this solution is complex depending on other waiters, resulting in options when the signaller finishes the inner mutex-statement.
1819The signaller can retain @m2@ until completion of the outer mutex statement and pass the locks to waiter W1, or it can pass @m2@ to waiter W2 after completing the inner mutex-statement, while continuing to hold @m1@.
1820In the latter case, waiter W2 must eventually pass @m2@ to waiter W1, which is complex because W1 may have waited before W2, so W2 is unaware of it.
1821Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
1822
1823While a number of approaches were examined~\cite[\S~4.3]{Delisle18}, the solution chosen for \CFA is a novel techique called \newterm{partial signalling}.
1824Signalled threads are moved to the urgent queue and the waiter at the front defines the set of monitors necessary for it to unblock.
1825Partial signalling transfers ownership of monitors to the front waiter.
1826When the signaller thread exits or waits in the monitor, the front waiter is unblocked if all its monitors are released.
1827The benefit is encapsulating complexity into only two actions: passing monitors to the next owner when they should be released and conditionally waking threads if all conditions are met.
1828
1829
1830\subsection{Loose Object Definitions}
1831\label{s:LooseObjectDefinitions}
1832
1833In an object-oriented programming-language, a class includes an exhaustive list of operations.
1834However, new members can be added via static inheritance or dynamic members, \eg JavaScript~\cite{JavaScript}.
1835Similarly, monitor routines can be added at any time in \CFA, making it less clear for programmers and more difficult to implement.
1836\begin{cfa}
1837monitor M { ... };
1838void `f`( M & mutex m );
1839void g( M & mutex m ) { waitfor( `f` ); }       $\C{// clear which f}$
1840void `f`( M & mutex m, int );                           $\C{// different f}$
1841void h( M & mutex m ) { waitfor( `f` ); }       $\C{// unclear which f}$
1842\end{cfa}
1843Hence, the cfa-code for entering a monitor looks like:
1844\begin{cfa}
1845if ( $\textrm{\textit{monitor is free}}$ ) $\LstCommentStyle{// \color{red}enter}$
1846else if ( $\textrm{\textit{already own monitor}}$ ) $\LstCommentStyle{// \color{red}continue}$
1847else if ( $\textrm{\textit{monitor accepts me}}$ ) $\LstCommentStyle{// \color{red}enter}$
1848else $\LstCommentStyle{// \color{red}block}$
1849\end{cfa}
1850For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions.
1851However, a fast check for \emph{monitor accepts me} is much harder to implement depending on the constraints put on the monitors.
1852Figure~\ref{fig:ClassicalMonitor} shows monitors are often expressed as an entry (calling) queue, some acceptor queues, and an urgent stack/queue.
1853
1854\begin{figure}
1855\centering
1856\subfloat[Classical monitor] {
1857\label{fig:ClassicalMonitor}
1858{\resizebox{0.45\textwidth}{!}{\input{monitor.pstex_t}}}
1859}% subfloat
1860\quad
1861\subfloat[Bulk acquire monitor] {
1862\label{fig:BulkMonitor}
1863{\resizebox{0.45\textwidth}{!}{\input{ext_monitor.pstex_t}}}
1864}% subfloat
1865\caption{Monitor Implementation}
1866\label{f:MonitorImplementation}
1867\end{figure}
1868
1869For a fixed (small) number of mutex routines (\eg 128), the accept check reduces to a bitmask of allowed callers, which can be checked with a single instruction.
1870This approach requires a unique dense ordering of routines with a small upper-bound and the ordering must be consistent across translation units.
1871For object-oriented languages these constraints are common, but \CFA mutex routines can be added in any scope and are only visible in certain translation unit, precluding program-wide dense-ordering among mutex routines.
1872
1873Figure~\ref{fig:BulkMonitor} shows the \CFA monitor implementation.
1874The mutex routine called is associated with each thread on the entry queue, while a list of acceptable routines is kept separately.
1875The accepted list is a variable-sized array of accepted routine pointers, so the single instruction bitmask comparison is replaced by dereferencing a pointer followed by a (usually short) linear search.
1876
1877
1878\subsection{Multi-Monitor Scheduling}
1879\label{s:Multi-MonitorScheduling}
1880
1881External scheduling, like internal scheduling, becomes significantly more complex for multi-monitor semantics.
1882Even in the simplest case, new semantics needs to be established.
1883\newpage
1884\begin{cfa}
1885monitor M { ... };
1886void f( M & mutex m1 );
1887void g( M & mutex m1, M & mutex m2 ) {
1888        waitfor( f );                                                   $\C{\color{red}// pass m1 or m2 to f?}$
1889}
1890\end{cfa}
1891The solution is for the programmer to disambiguate:
1892\begin{cfa}
1893        waitfor( f, m2 );                                               $\C{\color{red}// wait for call to f with argument m2}$
1894\end{cfa}
1895Both locks are acquired by routine @g@, so when routine @f@ is called, the lock for monitor @m2@ is passed from @g@ to @f@, while @g@ still holds lock @m1@.
1896This behaviour can be extended to the multi-monitor @waitfor@ statement.
1897\begin{cfa}
1898monitor M { ... };
1899void f( M & mutex m1, M & mutex m2 );
1900void g( M & mutex m1, M & mutex m2 ) {
1901        waitfor( f, m1, m2 );                                   $\C{\color{red}// wait for call to f with arguments m1 and m2}$
1902}
1903\end{cfa}
1904Again, the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired by the accepting routine.
1905Also, the order of the monitors in a @waitfor@ statement is unimportant.
1906
1907Figure~\ref{f:UnmatchedMutexSets} shows an example where, for internal and external scheduling with multiple monitors, a signalling or accepting thread must match exactly, \ie partial matching results in waiting.
1908For both examples, the set of monitors is disjoint so unblocking is impossible.
1909
1910\begin{figure}
1911\lstDeleteShortInline@%
1912\begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
1913\begin{cfa}
1914monitor M1 {} m11, m12;
1915monitor M2 {} m2;
1916condition c;
1917void f( M1 & mutex m1, M2 & mutex m2 ) {
1918        signal( c );
1919}
1920void g( M1 & mutex m1, M2 & mutex m2 ) {
1921        wait( c );
1922}
1923g( `m11`, m2 ); // block on wait
1924f( `m12`, m2 ); // cannot fulfil
1925\end{cfa}
1926&
1927\begin{cfa}
1928monitor M1 {} m11, m12;
1929monitor M2 {} m2;
1930
1931void f( M1 & mutex m1, M2 & mutex m2 ) {
1932
1933}
1934void g( M1 & mutex m1, M2 & mutex m2 ) {
1935        waitfor( f, m1, m2 );
1936}
1937g( `m11`, m2 ); // block on accept
1938f( `m12`, m2 ); // cannot fulfil
1939\end{cfa}
1940\end{tabular}
1941\lstMakeShortInline@%
1942\caption{Unmatched \protect\lstinline@mutex@ sets}
1943\label{f:UnmatchedMutexSets}
1944\end{figure}
1945
1946
1947\subsection{Extended \protect\lstinline@waitfor@}
1948
1949Figure~\ref{f:ExtendedWaitfor} show the extended form of the @waitfor@ statement to conditionally accept one of a group of mutex routines, with a specific action to be performed \emph{after} the mutex routine finishes.
1950For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding member(s) must exist.
1951The \emph{conditional-expression} of a @when@ may call a routine, but the routine must not block or context switch.
1952If there are multiple acceptable mutex calls, selection occurs top-to-bottom (prioritized) in the @waitfor@ clauses, whereas some programming languages with similar mechanisms accept non-deterministically for this case, \eg Go \lstinline[morekeywords=select]@select@.
1953If some accept guards are true and there are no outstanding calls to these members, the acceptor is accept-blocked until a call to one of these members is made.
1954If all the accept guards are false, the statement does nothing, unless there is a terminating @else@ clause with a true guard, which is executed instead.
1955Hence, the terminating @else@ clause allows a conditional attempt to accept a call without blocking.
1956If there is a @timeout@ clause, it provides an upper bound on waiting.
1957If both a @timeout@ clause and an @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered.
1958In all cases, the statement following is executed \emph{after} a clause is executed to know which of the clauses executed.
1959
1960\begin{figure}
1961\begin{cfa}
1962`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
1963        waitfor( $\emph{mutex-member-name}$ )
1964                $\emph{statement}$                                      $\C{// action after call}$
1965`or` `when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
1966        waitfor( $\emph{mutex-member-name}$ )
1967                $\emph{statement}$                                      $\C{// action after call}$
1968`or`    ...                                                                     $\C{// list of waitfor clauses}$
1969`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
1970        `timeout`                                                               $\C{// optional terminating timeout clause}$
1971                $\emph{statement}$                                      $\C{// action after timeout}$
1972`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
1973        `else`                                                                  $\C{// optional terminating clause}$
1974                $\emph{statement}$                                      $\C{// action when no immediate calls}$
1975\end{cfa}
1976\caption{Extended \protect\lstinline@waitfor@}
1977\label{f:ExtendedWaitfor}
1978\end{figure}
1979
1980Note, a group of conditional @waitfor@ clauses is \emph{not} the same as a group of @if@ statements, e.g.:
1981\begin{cfa}
1982if ( C1 ) waitfor( mem1 );                       when ( C1 ) waitfor( mem1 );
1983else if ( C2 ) waitfor( mem2 );         or when ( C2 ) waitfor( mem2 );
1984\end{cfa}
1985The left example accepts only @mem1@ if @C1@ is true or only @mem2@ if @C2@ is true.
1986The right example accepts either @mem1@ or @mem2@ if @C1@ and @C2@ are true.
1987
1988An interesting use of @waitfor@ is accepting the @mutex@ destructor to know when an object is deallocated.
1989\begin{cfa}
1990void insert( Buffer(T) & mutex buffer, T elem ) with( buffer ) {
1991        if ( count == 10 )
1992                waitfor( remove, buffer ) {
1993                        // insert elem into buffer
1994                } or `waitfor( ^?{}, buffer )` throw insertFail;
1995}
1996\end{cfa}
1997When the buffer is deallocated, the current waiter is unblocked and informed, so it can perform an appropriate action.
1998However, the basic @waitfor@ semantics do not support this functionality, since using an object after its destructor is called is undefined.
1999Therefore, to make this useful capability work, the semantics for accepting the destructor is the same as @signal@, \ie the call to the destructor is placed on the urgent queue and the acceptor continues execution, which throws an exception to the acceptor and then the caller is unblocked from the urgent queue to deallocate the object.
2000Accepting the destructor is an idiomatic way to terminate a thread in \CFA.
2001
2002
2003\subsection{\protect\lstinline@mutex@ Threads}
2004
2005Threads in \CFA are monitors to allow direct communication among threads, \ie threads can have mutex routines that are called by other threads.
2006Hence, all monitor features are available when using threads.
2007The following shows an example of two threads directly calling each other and accepting calls from each other in a cycle.
2008\begin{cfa}
2009thread Ping {} pi;
2010thread Pong {} po;
2011void ping( Ping & mutex ) {}
2012void pong( Pong & mutex ) {}
2013int main() {}
2014\end{cfa}
2015\vspace{-0.8\baselineskip}
2016\begin{cquote}
2017\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
2018\begin{cfa}
2019void main( Ping & pi ) {
2020        for ( int i = 0; i < 10; i += 1 ) {
2021                `waitfor( ping, pi );`
2022                `pong( po );`
2023        }
2024}
2025\end{cfa}
2026&
2027\begin{cfa}
2028void main( Pong & po ) {
2029        for ( int i = 0; i < 10; i += 1 ) {
2030                `ping( pi );`
2031                `waitfor( pong, po );`
2032        }
2033}
2034\end{cfa}
2035\end{tabular}
2036\end{cquote}
2037% \lstMakeShortInline@%
2038% \caption{Threads ping/pong using external scheduling}
2039% \label{f:pingpong}
2040% \end{figure}
2041Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start (and possibly complete) before the program main starts.
2042
2043
2044\subsection{Low-level Locks}
2045
2046For completeness and efficiency, \CFA provides a standard set of low-level locks: recursive mutex, condition, semaphore, barrier, \etc, and atomic instructions: @fetchAssign@, @fetchAdd@, @testSet@, @compareSet@, \etc.
2047
2048
2049\section{Parallelism}
2050
2051Historically, computer performance was about processor speeds.
2052However, with heat dissipation being a direct consequence of speed increase, parallelism is the new source for increased performance~\cite{Sutter05, Sutter05b}.
2053Now, high-performance applications must care about parallelism, which requires concurrency.
2054The lowest-level approach of parallelism is to use \newterm{kernel threads} in combination with semantics like @fork@, @join@, \etc.
2055However, kernel threads are better as an implementation tool because of complexity and higher cost.
2056Therefore, different abstractions are often layered onto kernel threads to simplify them, \eg pthreads.
2057
2058
2059\subsection{User Threads with Preemption}
2060
2061A direct improvement on kernel threads is user threads, \eg Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
2062This approach provides an interface that matches the language paradigms, more control over concurrency by the language runtime, and an abstract (and portable) interface to the underlying kernel threads across operating systems.
2063In many cases, user threads can be used on a much larger scale (100,000 threads).
2064Like kernel threads, user threads support preemption, which maximizes nondeterminism, but introduces the same concurrency errors: race, livelock, starvation, and deadlock.
2065\CFA adopts user-threads as they represent the truest realization of concurrency and can build any other concurrency approach, \eg thread pools and actors~\cite{Actors}.
2066
2067
2068\subsection{User Threads without Preemption (Fiber)}
2069\label{s:fibers}
2070
2071A variant of user thread is \newterm{fibers}, which removes preemption, \eg Go~\cite{Go} @goroutine@s.
2072Like functional programming, which removes mutation and its associated problems, removing preemption from concurrency reduces nondeterminism, making race and deadlock errors more difficult to generate.
2073However, preemption is necessary for concurrency that relies on spinning, so there are a class of problems that cannot be programmed without preemption.
2074
2075
2076\subsection{Thread Pools}
2077
2078In contrast to direct threading is indirect \newterm{thread pools}, where small jobs (work units) are inserted into a work pool for execution.
2079If the jobs are dependent, \ie interact, there is an implicit/explicit dependency graph that ties them together.
2080While removing direct concurrency, and hence the amount of context switching, thread pools significantly limit the interaction that can occur among jobs.
2081Indeed, jobs should not block because that also blocks the underlying thread, which effectively means the CPU utilization, and therefore throughput, suffers.
2082While it is possible to tune the thread pool with sufficient threads, it becomes difficult to obtain high throughput and good core utilization as job interaction increases.
2083As well, concurrency errors return, which threads pools are suppose to mitigate.
2084
2085
2086\section{\protect\CFA Runtime Structure}
2087
2088Figure~\ref{f:RunTimeStructure} illustrates the runtime structure of a \CFA program.
2089In addition to the new kinds of objects introduced by \CFA, there are two more runtime entities used to control parallel execution: cluster and (virtual) processor.
2090An executing thread is illustrated by its containment in a processor.
2091
2092\begin{figure}
2093\centering
2094\input{RunTimeStructure}
2095\caption{\CFA Runtime Structure}
2096\label{f:RunTimeStructure}
2097\end{figure}
2098
2099
2100\subsection{Cluster}
2101\label{s:RuntimeStructureCluster}
2102
2103A \newterm{cluster} is a collection of threads and virtual processors (abstract kernel-thread) that execute the threads (like a virtual machine).
2104The purpose of a cluster is to control the amount of parallelism that is possible among threads, plus scheduling and other execution defaults.
2105The default cluster-scheduler is single-queue multi-server, which provides automatic load-balancing of threads on processors.
2106However, the scheduler is pluggable, supporting alternative schedulers.
2107If several clusters exist, both threads and virtual processors, can be explicitly migrated from one cluster to another.
2108No automatic load balancing among clusters is performed by \CFA.
2109
2110When a \CFA program begins execution, it creates a user cluster with a single processor and a special processor to handle preemption that does not execute user threads.
2111The user cluster is created to contain the application user-threads.
2112Having all threads execute on the one cluster often maximizes utilization of processors, which minimizes runtime.
2113However, because of limitations of the underlying operating system, heterogeneous hardware, or scheduling requirements (real-time), multiple clusters are sometimes necessary.
2114
2115
2116\subsection{Virtual Processor}
2117\label{s:RuntimeStructureProcessor}
2118
2119A virtual processor is implemented by a kernel thread (\eg UNIX process), which is subsequently scheduled for execution on a hardware processor by the underlying operating system.
2120Programs may use more virtual processors than hardware processors.
2121On a multiprocessor, kernel threads are distributed across the hardware processors resulting in virtual processors executing in parallel.
2122(It is possible to use affinity to lock a virtual processor onto a particular hardware processor~\cite{affinityLinux, affinityWindows, affinityFreebsd, affinityNetbsd, affinityMacosx}, which is used when caching issues occur or for heterogeneous hardware processors.)
2123The \CFA runtime attempts to block unused processors and unblock processors as the system load increases;
2124balancing the workload with processors is difficult.
2125Preemption occurs on virtual processors rather than user threads, via operating-system interrupts.
2126Thus virtual processors execute user threads, where preemption frequency applies to a virtual processor, so preemption occurs randomly across the executed user threads.
2127Turning off preemption transforms user threads into fibers.
2128
2129
2130\subsection{Debug Kernel}
2131
2132There are two versions of the \CFA runtime kernel: debug and non-debug.
2133The debugging version has many runtime checks and internal assertions, \eg stack (non-writable) guard page, and checks for stack overflow whenever context switches occur among coroutines and threads, which catches most stack overflows.
2134After a program is debugged, the non-debugging version can be used to decrease space and increase performance.
2135
2136
2137\section{Implementation}
2138\label{s:Implementation}
2139
2140Currently, \CFA has fixed-sized stacks, where the stack size can be set at coroutine/thread creation but with no subsequent growth.
2141Schemes exist for dynamic stack-growth, such as stack copying and chained stacks.
2142However, stack copying requires pointer adjustment to items on the stack, which is impossible without some form of garbage collection.
2143As well, chained stacks require all modules be recompiled to use this feature, which breaks backward compatibility with existing C libraries.
2144In the long term, it is likely C libraries will migrate to stack chaining to support concurrency, at only a minimal cost to sequential programs.
2145Nevertheless, experience teaching \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue in most concurrent programs.
2146
2147A primary implementation challenge is avoiding contention from dynamically allocating memory because of bulk acquire, \eg the internal-scheduling design is (almost) free of allocations.
2148All blocking operations are made by parking threads onto queues, therefore all queues are designed with intrusive nodes, where each node has preallocated link fields for chaining.
2149Furthermore, several bulk-acquire operations need a variable amount of memory.
2150This storage is allocated at the base of a thread's stack before blocking, which means programmers must add a small amount of extra space for stacks.
2151
2152In \CFA, ordering of monitor acquisition relies on memory ordering to prevent deadlock~\cite{Havender68}, because all objects have distinct non-overlapping memory layouts, and mutual-exclusion for a monitor is only defined for its lifetime.
2153When a mutex call is made, pointers to the concerned monitors are aggregated into a variable-length array and sorted.
2154This array persists for the entire duration of the mutual exclusion and is used extensively for synchronization operations.
2155
2156To improve performance and simplicity, context switching occurs inside a routine call, so only callee-saved registers are copied onto the stack and then the stack register is switched;
2157the corresponding registers are then restored for the other context.
2158Note, the instruction pointer is untouched since the context switch is always inside the same routine.
2159Unlike coroutines, threads do not context switch among each other;
2160they context switch to the cluster scheduler.
2161This method is a 2-step context-switch and provides a clear distinction between user and kernel code, where scheduling and other system operations happen.
2162The alternative 1-step context-switch uses the \emph{from} thread's stack to schedule and then context-switches directly to the \emph{to} thread's stack.
2163Experimental results (not presented) show the performance of these two approaches is virtually equivalent, because both approaches are dominated by locking to prevent a race condition.
2164
2165All kernel threads (@pthreads@) created a stack.
2166Each \CFA virtual processor is implemented as a coroutine and these coroutines run directly on the kernel-thread stack, effectively stealing this stack.
2167The exception to this rule is the program main, \ie the initial kernel thread that is given to any program.
2168In order to respect C expectations, the stack of the initial kernel thread is used by program main rather than the main processor, allowing it to grow dynamically as in a normal C program.
2169
2170Finally, an important aspect for a complete threading system is preemption, which introduces extra non-determinism via transparent interleaving, rather than cooperation among threads for proper scheduling and processor fairness from long-running threads.
2171Because preemption frequency is usually long (1 millisecond) performance cost is negligible.
2172Preemption is normally handled by setting a count-down timer on each virtual processor.
2173When the timer expires, an interrupt is delivered, and the interrupt handler resets the count-down timer, and if the virtual processor is executing in user code, the signal handler performs a user-level context-switch, or if executing in the language runtime-kernel, the preemption is ignored or rolled forward to the point where the runtime kernel context switches back to user code.
2174Multiple signal handlers may be pending.
2175When control eventually switches back to the signal handler, it returns normally, and execution continues in the interrupted user thread, even though the return from the signal handler may be on a different kernel thread than the one where the signal is delivered.
2176The only issue with this approach is that signal masks from one kernel thread may be restored on another as part of returning from the signal handler;
2177therefore, the same signal mask is required for all virtual processors in a cluster.
2178
2179However, on current UNIX systems:
2180\begin{quote}
2181A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
2182If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
2183SIGNAL(7) - Linux Programmer's Manual
2184\end{quote}
2185Hence, the timer-expiry signal, which is generated \emph{externally} by the UNIX kernel to the UNIX process, is delivered to any of its UNIX subprocesses (kernel threads).
2186To ensure each virtual processor receives its own preemption signals, a discrete-event simulation is run on a special virtual processor, and only it sets and receives timer events.
2187Virtual processors register an expiration time with the discrete-event simulator, which is inserted in sorted order.
2188The simulation sets the count-down timer to the value at the head of the event list, and when the timer expires, all events less than or equal to the current time are processed.
2189Processing a preemption event sends an \emph{internal} @SIGUSR1@ signal to the registered virtual processor, which is always delivered to that processor.
2190
2191
2192\section{Performance}
2193\label{results}
2194
2195To verify the implementation of the \CFA runtime, a series of microbenchmarks are performed comparing \CFA with other widely used programming languages with concurrency.
2196Table~\ref{t:machine} shows the specifications of the computer used to run the benchmarks, and the versions of the software used in the comparison.
2197
2198\begin{table}
2199\centering
2200\caption{Experiment environment}
2201\label{t:machine}
2202
2203\begin{tabular}{|l|r||l|r|}
2204\hline
2205Architecture            & x86\_64                               & NUMA node(s)  & 8 \\
2206\hline
2207CPU op-mode(s)          & 32-bit, 64-bit                & Model name    & AMD Opteron\texttrademark\ Processor 6380 \\
2208\hline
2209Byte Order                      & Little Endian                 & CPU Freq              & 2.5 GHz \\
2210\hline
2211CPU(s)                          & 64                                    & L1d cache     & 16 KiB \\
2212\hline
2213Thread(s) per core      & 2                                     & L1i cache     & 64 KiB \\
2214\hline
2215Core(s) per socket      & 8                                     & L2 cache              & 2048 KiB \\
2216\hline
2217Socket(s)                       & 4                                     & L3 cache              & 6144 KiB \\
2218\hline
2219\hline
2220Operating system        & Ubuntu 16.04.3 LTS    & Kernel                & Linux 4.4-97-generic \\
2221\hline
2222gcc                                     & 6.3                                   & \CFA                  & 1.0.0 \\
2223\hline
2224Java                            & OpenJDK-9                     & Go                    & 1.9.2 \\
2225\hline
2226\end{tabular}
2227\end{table}
2228
2229All benchmarks are run using the following harness:
2230\begin{cfa}
2231unsigned int N = 10_000_000;
2232#define BENCH( run ) Time before = getTimeNsec(); run; Duration result = (getTimeNsec() - before) / N;
2233\end{cfa}
2234The method used to get time is @clock_gettime( CLOCK_REALTIME )@.
2235Each benchmark is performed @N@ times, where @N@ varies depending on the benchmark;
2236the total time is divided by @N@ to obtain the average time for a benchmark.
2237All omitted tests for other languages are functionally identical to the shown \CFA test.
2238
2239
2240\paragraph{Context-Switching}
2241
2242In procedural programming, the cost of a routine call is important as modularization (refactoring) increases.
2243(In many cases, a compiler inlines routine calls to eliminate this cost.)
2244Similarly, when modularization extends to coroutines/tasks, the time for a context switch becomes a relevant factor.
2245The coroutine context-switch is 2-step using resume/suspend, \ie from resumer to suspender and from suspender to resumer.
2246The thread context switch is 2-step using yield, \ie enter and return from the runtime kernel.
2247Figure~\ref{f:ctx-switch} shows the code for coroutines/threads with all results in Table~\ref{tab:ctx-switch}.
2248The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling.
2249
2250\begin{figure}
2251\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2252
2253\newbox\myboxA
2254\begin{lrbox}{\myboxA}
2255\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2256coroutine C {} c;
2257void main( C & ) { for ( ;; ) { @suspend();@ } }
2258int main() {
2259        BENCH(
2260                for ( size_t i = 0; i < N; i += 1 ) { @resume( c );@ } )
2261        sout | result`ns;
2262}
2263\end{cfa}
2264\end{lrbox}
2265
2266\newbox\myboxB
2267\begin{lrbox}{\myboxB}
2268\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2269
2270
2271int main() {
2272        BENCH(
2273                for ( size_t i = 0; i < N; i += 1 ) { @yield();@ } )
2274        sout | result`ns;
2275}
2276\end{cfa}
2277\end{lrbox}
2278
2279\subfloat[Coroutine]{\usebox\myboxA}
2280\quad
2281\subfloat[Thread]{\usebox\myboxB}
2282\captionof{figure}{\CFA context-switch benchmark}
2283\label{f:ctx-switch}
2284
2285\centering
2286
2287\captionof{table}{Context switch comparison (nanoseconds)}
2288\label{tab:ctx-switch}
2289\bigskip
2290\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
2291\cline{2-4}
2292\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2293\hline
2294Kernel Thread   & 333.5 & 332.96        & 4.1 \\
2295\CFA Coroutine  & 49            & 48.68 & 0.47    \\
2296\CFA Thread             & 105           & 105.57        & 1.37 \\
2297\uC Coroutine   & 44            & 44            & 0 \\
2298\uC Thread              & 100           & 99.29 & 0.96 \\
2299Goroutine               & 145           & 147.25        & 4.15 \\
2300Java Thread             & 373.5 & 375.14        & 8.72 \\
2301\hline
2302\end{tabular}
2303
2304\bigskip
2305\bigskip
2306
2307\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2308\begin{cfa}
2309monitor M { ... } m1/*, m2, m3, m4*/;
2310void __attribute__((noinline)) do_call( M & mutex m/*, m2, m3, m4*/ ) {}
2311int main() {
2312        BENCH( for( size_t i = 0; i < N; i += 1 ) { @do_call( m1/*, m2, m3, m4*/ );@ } )
2313        sout | result`ns;
2314}
2315\end{cfa}
2316\captionof{figure}{\CFA acquire/release mutex benchmark}
2317\label{f:mutex}
2318
2319\centering
2320
2321\captionof{table}{Mutex comparison (nanoseconds)}
2322\label{tab:mutex}
2323\bigskip
2324
2325\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
2326\cline{2-4}
2327\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2328\hline
2329C routine                                       & 2             & 2             & 0    \\
2330FetchAdd + FetchSub                     & 26            & 26            & 0    \\
2331Pthreads Mutex Lock                     & 31            & 31.71 & 0.97 \\
2332\uC @monitor@ member routine            & 31            & 31            & 0    \\
2333\CFA @mutex@ routine, 1 argument        & 46            & 46.68 & 0.93  \\
2334\CFA @mutex@ routine, 2 argument        & 84            & 85.36 & 1.99 \\
2335\CFA @mutex@ routine, 4 argument        & 158           & 161           & 4.22 \\
2336Java synchronized routine               & 27.5  & 29.79 & 2.93  \\
2337\hline
2338\end{tabular}
2339\end{figure}
2340
2341
2342\paragraph{Mutual-Exclusion}
2343
2344Mutual exclusion is measured by entering/leaving a critical section.
2345For monitors, entering and leaving a monitor routine is measured.
2346Figure~\ref{f:mutex} shows the code for \CFA with all results in Table~\ref{tab:mutex}.
2347To put the results in context, the cost of entering a non-inline routine and the cost of acquiring and releasing a @pthread_mutex@ lock is also measured.
2348Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2349
2350
2351\paragraph{Internal Scheduling}
2352
2353Internal scheduling is measured by waiting on and signalling a condition variable.
2354Figure~\ref{f:int-sched} shows the code for \CFA, with results in Table~\ref{tab:int-sched}.
2355Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2356Java scheduling is significantly greater because the benchmark explicitly creates multiple thread in order to prevent the JIT from making the program sequential, \ie removing all locking.
2357
2358\begin{figure}
2359\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2360\begin{cfa}
2361volatile int go = 0;
2362condition c;
2363monitor M { ... } m;
2364void __attribute__((noinline)) do_call( M & mutex a1 ) { signal( c ); }
2365thread T {};
2366void main( T & this ) {
2367        while ( go == 0 ) { yield(); }  // wait for other thread to start
2368        while ( go == 1 ) { @do_call( m );@ }
2369}
2370int  __attribute__((noinline)) do_wait( M & mutex m ) {
2371        go = 1; // continue other thread
2372        BENCH( for ( size_t i = 0; i < N; i += 1 ) { @wait( c );@ } );
2373        go = 0; // stop other thread
2374        sout | result`ns;
2375}
2376int main() {
2377        T t;
2378        do_wait( m );
2379}
2380\end{cfa}
2381\captionof{figure}{\CFA Internal-scheduling benchmark}
2382\label{f:int-sched}
2383
2384\centering
2385\captionof{table}{Internal-scheduling comparison (nanoseconds)}
2386\label{tab:int-sched}
2387\bigskip
2388
2389\begin{tabular}{|r|*{3}{D{.}{.}{5.2}|}}
2390\cline{2-4}
2391\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2392\hline
2393Pthreads Condition Variable             & 6005  & 5681.43       & 835.45 \\
2394\uC @signal@                                    & 324           & 325.54        & 3,02   \\
2395\CFA @signal@, 1 @monitor@              & 368.5         & 370.61        & 4.77   \\
2396\CFA @signal@, 2 @monitor@              & 467           & 470.5 & 6.79   \\
2397\CFA @signal@, 4 @monitor@              & 700.5         & 702.46        & 7.23  \\
2398Java @notify@                                   & 15471 & 172511        & 5689 \\
2399\hline
2400\end{tabular}
2401\end{figure}
2402
2403
2404\paragraph{External Scheduling}
2405
2406External scheduling is measured by accepting a call using the @waitfor@ statement (@_Accept@ in \uC).
2407Figure~\ref{f:ext-sched} shows the code for \CFA, with results in Table~\ref{tab:ext-sched}.
2408Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2409
2410\begin{figure}
2411\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2412\begin{cfa}
2413volatile int go = 0;
2414monitor M { ... } m;
2415thread T {};
2416void __attribute__((noinline)) do_call( M & mutex ) {}
2417void main( T & ) {
2418        while ( go == 0 ) { yield(); }  // wait for other thread to start
2419        while ( go == 1 ) { @do_call( m );@ }
2420}
2421int __attribute__((noinline)) do_wait( M & mutex m ) {
2422        go = 1; // continue other thread
2423        BENCH( for ( size_t i = 0; i < N; i += 1 ) { @waitfor( do_call, m );@ } )
2424        go = 0; // stop other thread
2425        sout | result`ns;
2426}
2427int main() {
2428        T t;
2429        do_wait( m );
2430}
2431\end{cfa}
2432\captionof{figure}{\CFA external-scheduling benchmark}
2433\label{f:ext-sched}
2434
2435\centering
2436
2437\captionof{table}{External-scheduling comparison (nanoseconds)}
2438\label{tab:ext-sched}
2439\bigskip
2440\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
2441\cline{2-4}
2442\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2443\hline
2444\uC @_Accept@                           & 358           & 359.11        & 2.53  \\
2445\CFA @waitfor@, 1 @monitor@     & 359           & 360.93        & 4.07  \\
2446\CFA @waitfor@, 2 @monitor@     & 450           & 449.39        & 6.62  \\
2447\CFA @waitfor@, 4 @monitor@     & 652           & 655.64        & 7.73 \\
2448\hline
2449\end{tabular}
2450
2451\bigskip
2452\medskip
2453
2454\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2455\begin{cfa}
2456thread MyThread {};
2457void main( MyThread & ) {}
2458int main() {
2459        BENCH( for ( size_t i = 0; i < N; i += 1 ) { @MyThread m;@ } )
2460        sout | result`ns;
2461}
2462\end{cfa}
2463\captionof{figure}{\CFA object-creation benchmark}
2464\label{f:creation}
2465
2466\centering
2467
2468\captionof{table}{Creation comparison (nanoseconds)}
2469\label{tab:creation}
2470\bigskip
2471
2472\begin{tabular}{|r|*{3}{D{.}{.}{5.2}|}}
2473\cline{2-4}
2474\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} & \multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2475\hline
2476Pthreads                                & 28091         & 28073.39      & 163.1  \\
2477\CFA Coroutine Lazy             & 6                     & 6.07          & 0.26   \\
2478\CFA Coroutine Eager    & 520           & 520.61        & 2.04   \\
2479\CFA Thread                             & 2032  & 2016.29       & 112.07  \\
2480\uC Coroutine                   & 106           & 107.36        & 1.47   \\
2481\uC Thread                              & 536.5 & 537.07        & 4.64   \\
2482Goroutine                               & 3103  & 3086.29       & 90.25  \\
2483Java Thread                             & 103416.5      & 103732.29     & 1137 \\
2484\hline
2485\end{tabular}
2486\end{figure}
2487
2488
2489\paragraph{Object Creation}
2490
2491Object creation is measured by creating/deleting the specific kind of concurrent object.
2492Figure~\ref{f:creation} shows the code for \CFA, with results in Table~\ref{tab:creation}.
2493The only note here is that the call stacks of \CFA coroutines are lazily created, therefore without priming the coroutine to force stack creation, the creation cost is artificially low.
2494
2495
2496\section{Conclusion}
2497
2498This paper demonstrates a concurrency API that is simple, efficient, and able to build higher-level concurrency features.
2499The approach provides concurrency based on a preemptive M:N user-level threading-system, executing in clusters, which encapsulate scheduling of work on multiple kernel threads providing parallelism.
2500The M:N model is judged to be efficient and provide greater flexibility than a 1:1 threading model.
2501High-level objects (monitor/task) are the core mechanism for mutual exclusion and synchronization.
2502A novel aspect is allowing multiple mutex-objects to be accessed simultaneously reducing the potential for deadlock for this complex scenario.
2503These concepts and the entire \CFA runtime-system are written in the \CFA language, demonstrating the expressiveness of the \CFA language.
2504Performance comparisons with other concurrent systems/languages show the \CFA approach is competitive across all low-level operations, which translates directly into good performance in well-written concurrent applications.
2505C programmers should feel comfortable using these mechanisms for developing concurrent applications, with the ability to obtain maximum available performance by mechanisms at the appropriate level.
2506
2507
2508\section{Future Work}
2509
2510While concurrency in \CFA has a strong start, development is still underway and there are missing features.
2511
2512\paragraph{Flexible Scheduling}
2513\label{futur:sched}
2514
2515An important part of concurrency is scheduling.
2516Different scheduling algorithms can affect performance (both in terms of average and variation).
2517However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
2518One solution is to offer various tweaking options, allowing the scheduler to be adjusted to the requirements of the workload.
2519However, to be truly flexible, a pluggable scheduler is necessary.
2520Currently, the \CFA pluggable scheduler is too simple to handle complex scheduling, \eg quality of service and real-time, where the scheduler must interact with mutex objects to deal with issues like priority inversion.
2521
2522\paragraph{Non-Blocking I/O}
2523\label{futur:nbio}
2524
2525Many modern workloads are not bound by computation but IO operations, a common case being web servers and XaaS~\cite{XaaS} (anything as a service).
2526These types of workloads require significant engineering to amortizing costs of blocking IO-operations.
2527At its core, non-blocking I/O is an operating-system level feature queuing IO operations, \eg network operations, and registering for notifications instead of waiting for requests to complete.
2528Current trends use asynchronous programming like callbacks, futures, and/or promises, \eg Node.js~\cite{NodeJs} for JavaScript, Spring MVC~\cite{SpringMVC} for Java, and Django~\cite{Django} for Python.
2529However, these solutions lead to code that is hard to create, read and maintain.
2530A better approach is to tie non-blocking I/O into the concurrency system to provide ease of use with low overhead, \eg thread-per-connection web-services.
2531A non-blocking I/O library is currently under development for \CFA.
2532
2533\paragraph{Other Concurrency Tools}
2534\label{futur:tools}
2535
2536While monitors offer flexible and powerful concurrency for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
2537Examples of such tools can include futures and promises~\cite{promises}, executors and actors.
2538These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
2539As well, new \CFA extensions should make it possible to create a uniform interface for virtually all mutual exclusion, including monitors and low-level locks.
2540
2541\paragraph{Implicit Threading}
2542\label{futur:implcit}
2543
2544Basic concurrent (embarrassingly parallel) applications can benefit greatly from implicit concurrency, where sequential programs are converted to concurrent, possibly with some help from pragmas to guide the conversion.
2545This type of concurrency can be achieved both at the language level and at the library level.
2546The canonical example of implicit concurrency is concurrent nested @for@ loops, which are amenable to divide and conquer algorithms~\cite{uC++book}.
2547The \CFA language features should make it possible to develop a reasonable number of implicit concurrency mechanism to solve basic HPC data-concurrency problems.
2548However, implicit concurrency is a restrictive solution with significant limitations, so it can never replace explicit concurrent programming.
2549
2550
2551\section{Acknowledgements}
2552
2553The authors would like to recognize the design assistance of Aaron Moss, Rob Schluntz and Andrew Beach on the features described in this paper.
2554Funding for this project has been provided by Huawei Ltd.\ (\url{http://www.huawei.com}), and Peter Buhr is partially funded by the Natural Sciences and Engineering Research Council of Canada.
2555
2556{%
2557\fontsize{9bp}{12bp}\selectfont%
2558\bibliography{pl,local}
2559}%
2560
2561\end{document}
2562
2563% Local Variables: %
2564% tab-width: 4 %
2565% fill-column: 120 %
2566% compile-command: "make" %
2567% End: %
Note: See TracBrowser for help on using the repository browser.