source: doc/papers/concurrency/Paper.tex @ 7bb6bd8

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 7bb6bd8 was 16948499, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

cleanup abstract and introduction

  • Property mode set to 100644
File size: 136.1 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{language=go,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
218{}
219\lstnewenvironment{python}[1][]
220{\lstset{language=python,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
221{}
222
223% inline code @...@
224\lstMakeShortInline@%
225
226\let\OLDthebibliography\thebibliography
227\renewcommand\thebibliography[1]{
228  \OLDthebibliography{#1}
229  \setlength{\parskip}{0pt}
230  \setlength{\itemsep}{4pt plus 0.3ex}
231}
232
233\title{\texorpdfstring{Advanced Control-flow and Concurrency in \protect\CFA}{Advanced Control-flow in Cforall}}
234
235\author[1]{Thierry Delisle}
236\author[1]{Peter A. Buhr*}
237\authormark{DELISLE \textsc{et al.}}
238
239\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}
240
241\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}}
242
243% \fundingInfo{Natural Sciences and Engineering Research Council of Canada}
244
245\abstract[Summary]{
246\CFA is a polymorphic, non-object-oriented, concurrent, backwards-compatible extension of the C programming language.
247This paper discusses the design philosophy and implementation of its advanced control-flow and concurrent/parallel features, along with the supporting runtime.
248These features are created from scratch as ISO C has only low-level and/or unimplemented concurrency, so C programmers continue to rely on library features like C pthreads.
249\CFA introduces modern language-level control-flow mechanisms, like coroutines, user-level threading, and monitors for mutual exclusion and synchronization.
250Library extension for executors, futures, and actors are built on these basic mechanisms.
251The runtime provides significant programmer simplification and safety by eliminating spurious wakeup and reducing monitor barging.
252The runtime also ensures multiple monitors can be safely acquired \emph{simultaneously} (deadlock free), and this feature is fully integrated with all monitor synchronization mechanisms.
253All language features integrate with the \CFA polymorphic type-system and exception handling, while respecting the expectations and style of C programmers.
254Experimental results show comparable performance of the new features with similar mechanisms in other concurrent programming-languages.
255}%
256
257\keywords{coroutines, concurrency, parallelism, threads, monitors, runtime, C, \CFA (Cforall)}
258
259
260\begin{document}
261\linenumbers                                            % comment out to turn off line numbering
262
263\maketitle
264
265
266\section{Introduction}
267
268This paper discusses the design philosophy and implementation of advanced language-level control-flow and concurrent/parallel features in \CFA~\cite{Moss18} and its runtime.
269\CFA is a modern, polymorphic, non-object-oriented\footnote{
270\CFA has features often associated with object-oriented programming languages, such as constructors, destructors, virtuals and simple inheritance.
271However, 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.},
272backwards-compatible extension of the C programming language.
273Within the \CFA framework, new control-flow features are created from scratch.
274ISO \Celeven defines only a subset of the \CFA extensions, where the overlapping features are concurrency~\cite[\S~7.26]{C11}.
275However, \Celeven concurrency is largely wrappers for a subset of the pthreads library~\cite{Butenhof97,Pthreads}.
276Furthermore, \Celeven and pthreads concurrency is simple, based on thread fork/join in a function and a few locks, which is low-level and error prone;
277no high-level language concurrency features are defined.
278Interestingly, 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.
279Finally, while the \Celeven standard does not state a threading model, the historical association with pthreads suggests implementations would adopt kernel-level threading (1:1)~\cite{ThreadModel}.
280
281In contrast, there has been a renewed interest during the past decade in user-level (M:N, green) threading in old and new programming languages.
282As multi-core hardware became available in the 1980/90s, both user and kernel threading were examined.
283Kernel 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}.
284Libraries like pthreads were developed for C, and the Solaris operating-system switched from user (JDK 1.1~\cite{JDK1.1}) to kernel threads.
285As a result, languages like Java, Scala~\cite{Scala}, Objective-C~\cite{obj-c-book}, \CCeleven~\cite{C11}, and C\#~\cite{Csharp} adopt the 1:1 kernel-threading model, with a variety of presentation mechanisms.
286From 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}.
287The 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}.
288As well, user-threading facilitates a simpler concurrency approach using thread objects that leverage sequential patterns versus events with call-backs~\cite{vonBehren03}.
289Finally, 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.
290
291A further effort over the past two decades is the development of language memory-models to deal with the conflict between language features and compiler/hardware optimizations, i.e., some language features are unsafe in the presence of aggressive sequential optimizations~\cite{Buhr95a,Boehm05}.
292The consequence is that a language must provide sufficient tools to program around safety issues, as inline and library code is all sequential to the compiler.
293One solution is low-level qualifiers and functions (e.g., @volatile@ and atomics) allowing \emph{programmers} to explicitly write safe (race-free~\cite{Boehm12}) programs.
294A safer solution is high-level language constructs so the \emph{compiler} knows the optimization boundaries, and hence, provides implicit safety.
295This problem is best know with respect to concurrency, but applies to other complex control-flow, like exceptions\footnote{
296\CFA exception handling will be presented in a separate paper.
297The 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++}
298} and coroutines.
299Finally, solutions in the language allows matching constructs with language paradigm, i.e., imperative and functional languages have different presentations of the same concept.
300
301Finally, it is important for a language to provide safety over performance \emph{as the default}, allowing careful reduction of safety for performance when necessary.
302Two concurrency violations of this philosophy are \emph{spurious wakeup} and \emph{barging}, i.e., random wakeup~\cite[\S~8]{Buhr05a} and signalling-as-hints~\cite[\S~8]{Buhr05a}, where one begats the other.
303If you believe spurious wakeup is a foundational concurrency property, than unblocking (signalling) a thread is always a hint.
304If you \emph{do not} believe spurious wakeup is foundational, than signalling-as-hints is a performance decision.
305Most importantly, removing spurious wakeup and signals-as-hints makes concurrent programming significantly safer because it removes local non-determinism.
306Clawing back performance where the local non-determinism is unimportant, should be an option not the default.
307
308\begin{comment}
309For 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++}.
310It 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.
311As well, user threading is often a complementary feature, allowing light-weight threading to match with low-cost objects, while hiding the application/kernel boundary.
312User 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{
313All implicit concurrency models have explicit threading in their implementation, and hence, can be build from explicit threading;
314however, 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.}
315Finally, 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.
316\CFA embraces language extensions and user-level threading to provide advanced control-flow (exception handling\footnote{
317\CFA exception handling will be presented in a separate paper.
318The 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++}
319} and coroutines) and concurrency.
320
321Most augmented traditional (Fortran 18~\cite{Fortran18}, Cobol 14~\cite{Cobol14}, Ada 12~\cite{Ada12}, Java 11~\cite{Java11}) and new languages (Go~\cite{Go}, Rust~\cite{Rust}, and D~\cite{D}), except \CC, diverge from C with different syntax and semantics, only interoperate indirectly with C, and are not systems languages, for those with managed memory.
322As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten.
323While \CC, like \CFA, takes an evolutionary approach to extend C, \CC's constantly growing complex and interdependent features-set (e.g., objects, inheritance, templates, etc.) mean idiomatic \CC code is difficult to use from C, and C programmers must expend significant effort learning \CC.
324Hence, rewriting and retraining costs for these languages, even \CC, are prohibitive for companies with a large C software-base.
325\CFA with its orthogonal feature-set, its high-performance runtime, and direct access to all existing C libraries circumvents these problems.
326\end{comment}
327
328\CFA embraces user-level threading, language extensions for advanced control-flow, and safety as the default.
329We present comparative examples so the reader can judge if the \CFA control-flow extensions are better and safer than those in or proposed for \Celeven, \CC and other concurrent, imperative programming languages, and perform experiments to show the \CFA runtime is competitive with other similar mechanisms.
330The main contributions of this work are:
331\begin{itemize}
332\item
333expressive language-level coroutines and user-level threading, which respect the expectations of C programmers.
334\item
335monitor synchronization without barging.
336\item
337safely acquiring multiple monitors \emph{simultaneously} (deadlock free), while seamlessly integrating this capability with all monitor synchronization mechanisms.
338\item
339providing statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features.
340\item
341library extensions for executors, futures, and actors built on the basic mechanisms.
342\item
343a runtime system with no spurious wakeup.
344\item
345experimental results showing comparable performance of the new features with similar mechanisms in other concurrent programming-languages.
346\end{itemize}
347
348\begin{comment}
349This paper provides a minimal concurrency \newterm{Application Program Interface} (API) that is simple, efficient and can be used to build other concurrency features.
350While the simplest concurrency system is a thread and a lock, this low-level approach is hard to master.
351An easier approach for programmers is to support higher-level constructs as the basis of concurrency.
352Indeed, for highly-productive concurrent-programming, high-level approaches are much more popular~\cite{Hochstein05}.
353Examples 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}.
354
355The following terminology is used.
356A \newterm{thread} is a fundamental unit of execution that runs a sequence of code and requires a stack to maintain state.
357Multiple simultaneous threads give rise to \newterm{concurrency}, which requires locking to ensure access to shared data and safe communication.
358\newterm{Locking}, and by extension \newterm{locks}, are defined as a mechanism to prevent progress of threads to provide safety.
359\newterm{Parallelism} is running multiple threads simultaneously.
360Parallelism implies \emph{actual} simultaneous execution, where concurrency only requires \emph{apparent} simultaneous execution.
361As such, parallelism only affects performance, which is observed through differences in space and/or time at runtime.
362Hence, there are two problems to be solved: concurrency and parallelism.
363While these two concepts are often combined, they are distinct, requiring different tools~\cite[\S~2]{Buhr05a}.
364Concurrency tools handle mutual exclusion and synchronization, while parallelism tools handle performance, cost, and resource utilization.
365
366The proposed concurrency API is implemented in a dialect of C, called \CFA (pronounced C-for-all).
367The 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.
368\end{comment}
369
370
371\begin{comment}
372\section{\CFA Overview}
373
374The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency.
375Extended versions and explanation of the following code examples are available at the \CFA website~\cite{Cforall} or in Moss~\etal~\cite{Moss18}.
376
377\CFA is a non-object-oriented extension of ISO-C, and hence, supports all C paradigms.
378Like C, the building blocks of \CFA are structures and routines.
379Virtually all of the code generated by the \CFA translator respects C memory layouts and calling conventions.
380While \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}.
381While some object-oriented features appear in \CFA, they are independent capabilities, allowing \CFA to adopt them while maintaining a procedural paradigm.
382
383
384\subsection{References}
385
386\CFA provides multi-level rebindable references, as an alternative to pointers, which significantly reduces syntactic noise.
387\begin{cfa}
388int x = 1, y = 2, z = 3;
389int * p1 = &x, ** p2 = &p1,  *** p3 = &p2,      $\C{// pointers to x}$
390    `&` r1 = x,   `&&` r2 = r1,   `&&&` r3 = r2;        $\C{// references to x}$
391int * p4 = &z, `&` r4 = z;
392
393*p1 = 3; **p2 = 3; ***p3 = 3;       // change x
394r1 =  3;     r2 = 3;      r3 = 3;        // change x: implicit dereferences *r1, **r2, ***r3
395**p3 = &y; *p3 = &p4;                // change p1, p2
396`&`r3 = &y; `&&`r3 = &`&`r4;             // change r1, r2: cancel implicit dereferences (&*)**r3, (&(&*)*)*r3, &(&*)r4
397\end{cfa}
398A reference is a handle to an object, like a pointer, but is automatically dereferenced the specified number of levels.
399Referencing (address-of @&@) a reference variable cancels one of the implicit dereferences, until there are no more implicit references, after which normal expression behaviour applies.
400
401
402\subsection{\texorpdfstring{\protect\lstinline{with} Statement}{with Statement}}
403\label{s:WithStatement}
404
405Heterogeneous data is aggregated into a structure/union.
406To 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.
407\begin{cquote}
408\vspace*{-\baselineskip}%???
409\lstDeleteShortInline@%
410\begin{cfa}
411struct S { char c; int i; double d; };
412struct T { double m, n; };
413// multiple aggregate parameters
414\end{cfa}
415\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
416\begin{cfa}
417void f( S & s, T & t ) {
418        `s.`c; `s.`i; `s.`d;
419        `t.`m; `t.`n;
420}
421\end{cfa}
422&
423\begin{cfa}
424void f( S & s, T & t ) `with ( s, t )` {
425        c; i; d;                // no qualification
426        m; n;
427}
428\end{cfa}
429\end{tabular}
430\lstMakeShortInline@%
431\end{cquote}
432Object-oriented programming languages only provide implicit qualification for the receiver.
433
434In detail, the @with@-statement syntax is:
435\begin{cfa}
436$\emph{with-statement}$:
437        'with' '(' $\emph{expression-list}$ ')' $\emph{compound-statement}$
438\end{cfa}
439and may appear as the body of a routine or nested within a routine body.
440Each expression in the expression-list provides a type and object.
441The type must be an aggregate type.
442(Enumerations are already opened.)
443The object is the implicit qualifier for the open structure-fields.
444All 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.
445
446
447\subsection{Overloading}
448
449\CFA maximizes the ability to reuse names via overloading to aggressively address the naming problem.
450Both variables and routines may be overloaded, where selection is based on number and types of returns and arguments (as in Ada~\cite{Ada}).
451\newpage
452\vspace*{-2\baselineskip}%???
453\begin{cquote}
454\begin{cfa}
455// selection based on type
456\end{cfa}
457\lstDeleteShortInline@%
458\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
459\begin{cfa}
460const short int `MIN` = -32768;
461const int `MIN` = -2147483648;
462const long int `MIN` = -9223372036854775808L;
463\end{cfa}
464&
465\begin{cfa}
466short int si = `MIN`;
467int i = `MIN`;
468long int li = `MIN`;
469\end{cfa}
470\end{tabular}
471\begin{cfa}
472// selection based on type and number of parameters
473\end{cfa}
474\begin{tabular}{@{}l@{\hspace{2.7\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
475\begin{cfa}
476void `f`( void );
477void `f`( char );
478void `f`( int, double );
479\end{cfa}
480&
481\begin{cfa}
482`f`();
483`f`( 'a' );
484`f`( 3, 5.2 );
485\end{cfa}
486\end{tabular}
487\begin{cfa}
488// selection based on type and number of returns
489\end{cfa}
490\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}|@{\hspace{2\parindentlnth}}l@{}}
491\begin{cfa}
492char `f`( int );
493double `f`( int );
494[char, double] `f`( int );
495\end{cfa}
496&
497\begin{cfa}
498char c = `f`( 3 );
499double d = `f`( 3 );
500[d, c] = `f`( 3 );
501\end{cfa}
502\end{tabular}
503\lstMakeShortInline@%
504\end{cquote}
505Overloading is important for \CFA concurrency since the runtime system relies on creating different types to represent concurrency objects.
506Therefore, overloading eliminates long prefixes and other naming conventions to prevent name clashes.
507As seen in Section~\ref{s:Concurrency}, routine @main@ is heavily overloaded.
508As another example, variable overloading is useful in the parallel semantics of the @with@ statement for fields with the same name:
509\begin{cfa}
510struct S { int `i`; int j; double m; } s;
511struct T { int `i`; int k; int m; } t;
512with ( s, t ) {
513        j + k;                                                                  $\C{// unambiguous, s.j + t.k}$
514        m = 5.0;                                                                $\C{// unambiguous, s.m = 5.0}$
515        m = 1;                                                                  $\C{// unambiguous, t.m = 1}$
516        int a = m;                                                              $\C{// unambiguous, a = t.m }$
517        double b = m;                                                   $\C{// unambiguous, b = s.m}$
518        int c = `s.i` + `t.i`;                                  $\C{// unambiguous, qualification}$
519        (double)m;                                                              $\C{// unambiguous, cast s.m}$
520}
521\end{cfa}
522For parallel semantics, both @s.i@ and @t.i@ are visible with the same type, so only @i@ is ambiguous without qualification.
523
524
525\subsection{Operators}
526
527Overloading also extends to operators.
528Operator-overloading syntax creates a routine name with an operator symbol and question marks for the operands:
529\begin{cquote}
530\lstDeleteShortInline@%
531\begin{tabular}{@{}ll@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
532\begin{cfa}
533int ++?(int op);
534int ?++(int op);
535int `?+?`(int op1, int op2);
536int ?<=?(int op1, int op2);
537int ?=? (int & op1, int op2);
538int ?+=?(int & op1, int op2);
539\end{cfa}
540&
541\begin{cfa}
542// unary prefix increment
543// unary postfix increment
544// binary plus
545// binary less than
546// binary assignment
547// binary plus-assignment
548\end{cfa}
549&
550\begin{cfa}
551struct S { int i, j; };
552S `?+?`( S op1, S op2) { // add two structures
553        return (S){op1.i + op2.i, op1.j + op2.j};
554}
555S s1 = {1, 2}, s2 = {2, 3}, s3;
556s3 = s1 `+` s2;         // compute sum: s3 == {2, 5}
557\end{cfa}
558\end{tabular}
559\lstMakeShortInline@%
560\end{cquote}
561
562
563\subsection{Constructors / Destructors}
564
565Object lifetime is a challenge in non-managed programming languages.
566\CFA responds with \CC-like constructors and destructors, using a different operator-overloading syntax.
567\begin{cfa}
568struct VLA { int len, * data; };                        $\C{// variable length array of integers}$
569void ?{}( VLA & vla ) with ( vla ) { len = 10;  data = alloc( len ); }  $\C{// default constructor}$
570void ?{}( VLA & vla, int size, char fill ) with ( vla ) { len = size;  data = alloc( len, fill ); } // initialization
571void ?{}( VLA & vla, VLA other ) { vla.len = other.len;  vla.data = other.data; } $\C{// copy, shallow}$
572void ^?{}( VLA & vla ) with ( vla ) { free( data ); } $\C{// destructor}$
573{
574        VLA  x,            y = { 20, 0x01 },     z = y; $\C{// z points to y}$
575        // $\LstCommentStyle{\color{red}\ \ \ x\{\};\ \ \ \ \ \ \ \ \ y\{ 20, 0x01 \};\ \ \ \ \ \ \ \ \ \ z\{ z, y \};\ \ \ \ \ \ \ implicit calls}$
576        ^x{};                                                                   $\C{// deallocate x}$
577        x{};                                                                    $\C{// reallocate x}$
578        z{ 5, 0xff };                                                   $\C{// reallocate z, not pointing to y}$
579        ^y{};                                                                   $\C{// deallocate y}$
580        y{ x };                                                                 $\C{// reallocate y, points to x}$
581        x{};                                                                    $\C{// reallocate x, not pointing to y}$
582}       //  $\LstCommentStyle{\color{red}\^{}z\{\};\ \ \^{}y\{\};\ \ \^{}x\{\};\ \ \ implicit calls}$
583\end{cfa}
584Like \CC, construction is implicit on allocation (stack/heap) and destruction is implicit on deallocation.
585The object and all their fields are constructed/destructed.
586\CFA also provides @new@ and @delete@ as library routines, which behave like @malloc@ and @free@, in addition to constructing and destructing objects:
587\begin{cfa}
588{
589        ... struct S s = {10}; ...                              $\C{// allocation, call constructor}$
590}                                                                                       $\C{// deallocation, call destructor}$
591struct S * s = new();                                           $\C{// allocation, call constructor}$
592...
593delete( s );                                                            $\C{// deallocation, call destructor}$
594\end{cfa}
595\CFA concurrency uses object lifetime as a means of mutual exclusion and/or synchronization.
596
597
598\subsection{Parametric Polymorphism}
599\label{s:ParametricPolymorphism}
600
601The 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.
602For example, the following sum routine works for any type that supports construction from 0 and addition:
603\begin{cfa}
604forall( otype T | { void `?{}`( T *, zero_t ); T `?+?`( T, T ); } ) // constraint type, 0 and +
605T sum( T a[$\,$], size_t size ) {
606        `T` total = { `0` };                                    $\C{// initialize by 0 constructor}$
607        for ( size_t i = 0; i < size; i += 1 )
608                total = total `+` a[i];                         $\C{// select appropriate +}$
609        return total;
610}
611S sa[5];
612int i = sum( sa, 5 );                                           $\C{// use S's 0 construction and +}$
613\end{cfa}
614Type variables can be @otype@ or @dtype@.
615@otype@ refers to a \emph{complete type}, \ie, a type with size, alignment, default constructor, copy constructor, destructor, and assignment operator.
616@dtype@ refers to an \emph{incomplete type}, \eg, void or a forward-declared type.
617The 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.
618
619\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:
620\begin{cfa}
621trait `sumable`( otype T ) {
622        void `?{}`( T &, zero_t );                              $\C{// 0 literal constructor}$
623        T `?+?`( T, T );                                                $\C{// assortment of additions}$
624        T ?+=?( T &, T );
625        T ++?( T & );
626        T ?++( T & );
627};
628forall( otype T `| sumable( T )` )                      $\C{// use trait}$
629T sum( T a[$\,$], size_t size );
630\end{cfa}
631
632Using the return type for overload discrimination, it is possible to write a type-safe @alloc@ based on the C @malloc@:
633\begin{cfa}
634forall( dtype T | sized(T) ) T * alloc( void ) { return (T *)malloc( sizeof(T) ); }
635int * ip = alloc();                                                     $\C{// select type and size from left-hand side}$
636double * dp = alloc();
637struct S {...} * sp = alloc();
638\end{cfa}
639where the return type supplies the type/size of the allocation, which is impossible in most type systems.
640\end{comment}
641
642
643\section{Coroutines: Stepping Stone}
644\label{coroutine}
645
646Coroutines are generalized routines allowing execution to be temporarily suspended and later resumed.
647Hence, 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.
648This capability is accomplished via the coroutine's stack, where suspend/resume context switch among stacks.
649Because 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.
650Therefore, the two fundamental features of the core \CFA coroutine-API are independent call-stacks and @suspend@/@resume@ operations.
651
652For example, a problem made easier with coroutines is unbounded generators, \eg generating an infinite sequence of Fibonacci numbers
653\begin{displaymath}
654\mathsf{fib}(n) = \left \{
655\begin{array}{ll}
6560                                       & n = 0         \\
6571                                       & n = 1         \\
658\mathsf{fib}(n-1) + \mathsf{fib}(n-2)   & n \ge 2       \\
659\end{array}
660\right.
661\end{displaymath}
662where Figure~\ref{f:C-fibonacci} shows conventional approaches for writing a Fibonacci generator in C.
663Figure~\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.
664Figure~\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)$.
665
666\begin{figure}
667\centering
668\newbox\myboxA
669% \begin{lrbox}{\myboxA}
670% \begin{cfa}[aboveskip=0pt,belowskip=0pt]
671% `int fn1, fn2, state = 1;`   // single global variables
672% int fib() {
673%       int fn;
674%       `switch ( state )` {  // explicit execution state
675%         case 1: fn = 0;  fn1 = fn;  state = 2;  break;
676%         case 2: fn = 1;  fn2 = fn1;  fn1 = fn;  state = 3;  break;
677%         case 3: fn = fn1 + fn2;  fn2 = fn1;  fn1 = fn;  break;
678%       }
679%       return fn;
680% }
681% int main() {
682%
683%       for ( int i = 0; i < 10; i += 1 ) {
684%               printf( "%d\n", fib() );
685%       }
686% }
687% \end{cfa}
688% \end{lrbox}
689\begin{lrbox}{\myboxA}
690\begin{cfa}[aboveskip=0pt,belowskip=0pt]
691#define FIB_INIT { 0, 1 }
692typedef struct { int fn1, fn; } Fib;
693int fib( Fib * f ) {
694
695        int ret = f->fn1;
696        f->fn1 = f->fn;
697        f->fn = ret + f->fn;
698        return ret;
699}
700
701
702
703int main() {
704        Fib f1 = FIB_INIT, f2 = FIB_INIT;
705        for ( int i = 0; i < 10; i += 1 ) {
706                printf( "%d %d\n",
707                                fib( &f1 ), fib( &f2 ) );
708        }
709}
710\end{cfa}
711\end{lrbox}
712
713\newbox\myboxB
714\begin{lrbox}{\myboxB}
715\begin{cfa}[aboveskip=0pt,belowskip=0pt]
716`coroutine` Fib { int fn1; };
717void main( Fib & fib ) with( fib ) {
718        int fn;
719        [fn1, fn] = [0, 1];
720        for () {
721                `suspend();`
722                [fn1, fn] = [fn, fn1 + fn];
723        }
724}
725int ?()( Fib & fib ) with( fib ) {
726        `resume( fib );`  return fn1;
727}
728int main() {
729        Fib f1, f2;
730        for ( 10 ) {
731                sout | f1() | f2();
732}
733
734
735\end{cfa}
736\end{lrbox}
737
738\newbox\myboxC
739\begin{lrbox}{\myboxC}
740\begin{python}[aboveskip=0pt,belowskip=0pt]
741
742def Fib():
743
744    fn1, fn = 0, 1
745    while True:
746        `yield fn1`
747        fn1, fn = fn, fn1 + fn
748
749
750// next prewritten
751
752
753f1 = Fib()
754f2 = Fib()
755for i in range( 10 ):
756        print( next( f1 ), next( f2 ) )
757
758
759
760\end{python}
761\end{lrbox}
762
763\subfloat[C]{\label{f:GlobalVariables}\usebox\myboxA}
764\hspace{3pt}
765\vrule
766\hspace{3pt}
767\subfloat[\CFA]{\label{f:ExternalState}\usebox\myboxB}
768\hspace{3pt}
769\vrule
770\hspace{3pt}
771\subfloat[Python]{\label{f:ExternalState}\usebox\myboxC}
772\caption{Fibonacci Generator}
773\label{f:C-fibonacci}
774
775% \bigskip
776%
777% \newbox\myboxA
778% \begin{lrbox}{\myboxA}
779% \begin{cfa}[aboveskip=0pt,belowskip=0pt]
780% `coroutine` Fib { int fn; };
781% void main( Fib & fib ) with( fib ) {
782%       fn = 0;  int fn1 = fn; `suspend()`;
783%       fn = 1;  int fn2 = fn1;  fn1 = fn; `suspend()`;
784%       for () {
785%               fn = fn1 + fn2; fn2 = fn1; fn1 = fn; `suspend()`; }
786% }
787% int next( Fib & fib ) with( fib ) { `resume( fib );` return fn; }
788% int main() {
789%       Fib f1, f2;
790%       for ( 10 )
791%               sout | next( f1 ) | next( f2 );
792% }
793% \end{cfa}
794% \end{lrbox}
795% \newbox\myboxB
796% \begin{lrbox}{\myboxB}
797% \begin{python}[aboveskip=0pt,belowskip=0pt]
798%
799% def Fibonacci():
800%       fn = 0; fn1 = fn; `yield fn`  # suspend
801%       fn = 1; fn2 = fn1; fn1 = fn; `yield fn`
802%       while True:
803%               fn = fn1 + fn2; fn2 = fn1; fn1 = fn; `yield fn`
804%
805%
806% f1 = Fibonacci()
807% f2 = Fibonacci()
808% for i in range( 10 ):
809%       print( `next( f1 )`, `next( f2 )` ) # resume
810%
811% \end{python}
812% \end{lrbox}
813% \subfloat[\CFA]{\label{f:Coroutine3States}\usebox\myboxA}
814% \qquad
815% \subfloat[Python]{\label{f:Coroutine1State}\usebox\myboxB}
816% \caption{Fibonacci input coroutine, 3 states, internal variables}
817% \label{f:cfa-fibonacci}
818\end{figure}
819
820Using a coroutine, it is possible to express the Fibonacci formula directly without any of the C problems.
821Figure~\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@.
822Like 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.
823The 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@.
824The interface routine @next@, takes a Fibonacci instance and context switches to it using @resume@;
825on restart, the Fibonacci field, @fn@, contains the next value in the sequence, which is returned.
826The first @resume@ is special because it allocates the coroutine stack and cocalls its coroutine main on that stack;
827when the coroutine main returns, its stack is deallocated.
828Hence, @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.
829Figure~\ref{f:Coroutine1State} shows the coroutine version of the C version in Figure~\ref{f:ExternalState}.
830Coroutine generators are called \newterm{output coroutines} because values are only returned.
831
832Figure~\ref{f:CFAFmt} shows an \newterm{input coroutine}, @Format@, for restructuring text into groups of characters of fixed-size blocks.
833For example, the input of the left is reformatted into the output on the right.
834\begin{quote}
835\tt
836\begin{tabular}{@{}l|l@{}}
837\multicolumn{1}{c|}{\textbf{\textrm{input}}} & \multicolumn{1}{c}{\textbf{\textrm{output}}} \\
838abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
839&
840\begin{tabular}[t]{@{}lllll@{}}
841abcd    & efgh  & ijkl  & mnop  & qrst  \\
842uvwx    & yzab  & cdef  & ghij  & klmn  \\
843opqr    & stuv  & wxyz  &               &
844\end{tabular}
845\end{tabular}
846\end{quote}
847The 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.
848The destructor provides a newline, if formatted text ends with a full line.
849Figure~\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.
850(Linearized code is the bane of device drivers.)
851
852\begin{figure}
853\centering
854\newbox\myboxA
855\begin{lrbox}{\myboxA}
856\begin{cfa}[aboveskip=0pt,belowskip=0pt]
857`coroutine` Fmt {
858        char ch;   // communication variables
859        int g, b;   // needed in destructor
860};
861void main( Fmt & fmt ) with( fmt ) {
862        for () {
863                for ( g = 0; g < 5; g += 1 ) { // groups
864                        for ( b = 0; b < 4; b += 1 ) { // blocks
865                                `suspend();`
866                                sout | ch; } // print character
867                        sout | "  "; } // block separator
868                sout | nl; }  // group separator
869}
870void ?{}( Fmt & fmt ) { `resume( fmt );` } // prime
871void ^?{}( Fmt & fmt ) with( fmt ) { // destructor
872        if ( g != 0 || b != 0 ) // special case
873                sout | nl; }
874void send( Fmt & fmt, char c ) { fmt.ch = c; `resume( fmt )`; }
875int main() {
876        Fmt fmt;
877        sout | nlOff;   // turn off auto newline
878        for ( 41 )
879                send( fmt, 'a' );
880}
881\end{cfa}
882\end{lrbox}
883
884\newbox\myboxB
885\begin{lrbox}{\myboxB}
886\begin{python}[aboveskip=0pt,belowskip=0pt]
887
888
889
890def Fmt():
891        try:
892                while True:
893                        for g in range( 5 ):
894                                for b in range( 4 ):
895
896                                        print( `(yield)`, end='' )
897                                print( '  ', end='' )
898                        print()
899
900
901        except GeneratorExit:
902                if g != 0 | b != 0:
903                        print()
904
905
906fmt = Fmt()
907`next( fmt )`                    # prime
908for i in range( 41 ):
909        `fmt.send( 'a' );`      # send to yield
910
911\end{python}
912\end{lrbox}
913\subfloat[\CFA]{\label{f:CFAFmt}\usebox\myboxA}
914\qquad
915\subfloat[Python]{\label{f:CFmt}\usebox\myboxB}
916\caption{Output formatting text}
917\label{f:fmt-line}
918\end{figure}
919
920The 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.
921However, @resume@ and @suspend@ context switch among existing stack-frames, rather than create new ones so there is no stack growth.
922\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.
923(The trivial cycle is a coroutine resuming itself.)
924This control flow is similar to recursion for normal routines, but again there is no stack growth from the context switch.
925
926\begin{figure}
927\centering
928\lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $
929\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
930\begin{cfa}
931`coroutine` Prod {
932        Cons & c;
933        int N, money, receipt;
934};
935void main( Prod & prod ) with( prod ) {
936        // 1st resume starts here
937        for ( i; N ) {
938                int p1 = random( 100 ), p2 = random( 100 );
939                sout | p1 | " " | p2;
940                int status = delivery( c, p1, p2 );
941                sout | " $" | money | nl | status;
942                receipt += 1;
943        }
944        stop( c );
945        sout | "prod stops";
946}
947int payment( Prod & prod, int money ) {
948        prod.money = money;
949        `resume( prod );`
950        return prod.receipt;
951}
952void start( Prod & prod, int N, Cons &c ) {
953        &prod.c = &c; // reassignable reference
954        prod.[N, receipt] = [N, 0];
955        `resume( prod );`
956}
957int main() {
958        Prod prod;
959        Cons cons = { prod };
960        start( prod, 5, cons );
961}
962\end{cfa}
963&
964\begin{cfa}
965`coroutine` Cons {
966        Prod & p;
967        int p1, p2, status;
968        bool done;
969};
970void ?{}( Cons & cons, Prod & p ) {
971        &cons.p = &p; // reassignable reference
972        cons.[status, done ] = [0, false];
973}
974void ^?{}( Cons & cons ) {}
975void main( Cons & cons ) with( cons ) {
976        // 1st resume starts here
977        int money = 1, receipt;
978        for ( ; ! done; ) {
979                sout | p1 | " " | p2 | nl | " $" | money;
980                status += 1;
981                receipt = payment( p, money );
982                sout | " #" | receipt;
983                money += 1;
984        }
985        sout | "cons stops";
986}
987int delivery( Cons & cons, int p1, int p2 ) {
988        cons.[p1, p2] = [p1, p2];
989        `resume( cons );`
990        return cons.status;
991}
992void stop( Cons & cons ) {
993        cons.done = true;
994        `resume( cons );`
995}
996\end{cfa}
997\end{tabular}
998\caption{Producer / consumer: resume-resume cycle, bi-directional communication}
999\label{f:ProdCons}
1000\end{figure}
1001
1002Figure~\ref{f:ProdCons} shows a producer/consumer symmetric-coroutine performing bi-directional communication.
1003Since 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@.
1004The @start@ routine communicates both the number of elements to be produced and the consumer into the producer's coroutine-structure.
1005Then the @resume@ to @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
1006@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.
1007
1008The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
1009For the first resume, @cons@'s stack is initialized, creating local variables retained between subsequent activations of the coroutine.
1010The 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).
1011The call from the consumer to @payment@ introduces the cycle between producer and consumer.
1012When @payment@ is called, the consumer copies values into the producer's communication variable and a resume is executed.
1013The context switch restarts the producer at the point where it last context switched, so it continues in @delivery@ after the resume.
1014
1015@delivery@ returns the status value in @prod@'s coroutine main, where the status is printed.
1016The loop then repeats calling @delivery@, where each call resumes the consumer coroutine.
1017The context switch to the consumer continues in @payment@.
1018The consumer increments and returns the receipt to the call in @cons@'s coroutine main.
1019The loop then repeats calling @payment@, where each call resumes the producer coroutine.
1020
1021After iterating $N$ times, the producer calls @stop@.
1022The @done@ flag is set to stop the consumer's execution and a resume is executed.
1023The context switch restarts @cons@ in @payment@ and it returns with the last receipt.
1024The 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@.
1025@stop@ returns and @prod@'s coroutine main terminates.
1026The program main restarts after the resume in @start@.
1027@start@ returns and the program main terminates.
1028
1029One \emph{killer} application for a coroutine is device drivers, which at one time caused 70\%-85\% of failures in Windows/Linux~\cite{Swift05}.
1030Many device drivers are a finite state-machine parsing a protocol, e.g.:
1031\begin{tabbing}
1032\ldots STX \= \ldots message \ldots \= ESC \= ETX \= \ldots message \ldots  \= ETX \= 2-byte crc \= \ldots      \kill
1033\ldots STX \> \ldots message \ldots \> ESC \> ETX \> \ldots message \ldots  \> ETX \> 2-byte crc \> \ldots
1034\end{tabbing}
1035where a network message begins with the control character STX and ends with an ETX, followed by a 2-byte cyclic-redundancy check.
1036Control characters may appear in a message if preceded by an ESC.
1037Because FSMs can be complex and occur frequently in important domains, direct support of the coroutine is crucial in a systems programminglanguage.
1038
1039\begin{figure}
1040\begin{cfa}
1041enum Status { CONT, MSG, ESTX, ELNTH, ECRC };
1042`coroutine` Driver {
1043        Status status;
1044        char * msg, byte;
1045};
1046void ?{}( Driver & d, char * m ) { d.msg = m; }         $\C[3.0in]{// constructor}$
1047Status next( Driver & d, char b ) with( d ) {           $\C{// 'with' opens scope}$
1048        byte = b; `resume( d );` return status;
1049}
1050void main( Driver & d ) with( d ) {
1051        enum { STX = '\002', ESC = '\033', ETX = '\003', MaxMsg = 64 };
1052        unsigned short int crc;                                                 $\C{// error checking}$
1053  msg: for () {                                                                         $\C{// parse message}$
1054                status = CONT;
1055                unsigned int lnth = 0, sum = 0;
1056                while ( byte != STX ) `suspend();`
1057          emsg: for () {
1058                        `suspend();`                                                    $\C{// process byte}$
1059                        choose ( byte ) {                                               $\C{// switch with default break}$
1060                          case STX:
1061                                status = ESTX; `suspend();` continue msg;
1062                          case ETX:
1063                                break emsg;
1064                          case ESC:
1065                                suspend();
1066                        } // choose
1067                        if ( lnth >= MaxMsg ) {                                 $\C{// buffer full ?}$
1068                                status = ELNTH; `suspend();` continue msg; }
1069                        msg[lnth++] = byte;
1070                        sum += byte;
1071                } // for
1072                msg[lnth] = '\0';                                                       $\C{// terminate string}\CRT$
1073                `suspend();`
1074                crc = (unsigned char)byte << 8; // prevent sign extension for signed char
1075                `suspend();`
1076                status = (crc | (unsigned char)byte) == sum ? MSG : ECRC;
1077                `suspend();`
1078        } // for
1079}
1080\end{cfa}
1081\caption{Device driver for simple communication protocol}
1082\end{figure}
1083
1084
1085\subsection{Coroutine Implementation}
1086
1087A 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.
1088There are several solutions to this problem and the chosen option forced the \CFA coroutine design.
1089
1090Object-oriented inheritance provides extra fields and code in a restricted context, but it requires programmers to explicitly perform the inheritance:
1091\begin{cfa}[morekeywords={class,inherits}]
1092class mycoroutine inherits baseCoroutine { ... }
1093\end{cfa}
1094and the programming language (and possibly its tool set, \eg debugger) may need to understand @baseCoroutine@ because of the stack.
1095Furthermore, the execution of constructors/destructors is in the wrong order for certain operations.
1096For 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.
1097
1098An alternative is composition:
1099\begin{cfa}
1100struct mycoroutine {
1101        ... // declarations
1102        baseCoroutine dummy; // composition, last declaration
1103}
1104\end{cfa}
1105which also requires an explicit declaration that must be the last one to ensure correct initialization order.
1106However, there is nothing preventing wrong placement or multiple declarations.
1107
1108For coroutines as for threads, many implementations are based on routine pointers or routine objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
1109For example, Boost implements coroutines in terms of four functor object-types:
1110\begin{cfa}
1111asymmetric_coroutine<>::pull_type
1112asymmetric_coroutine<>::push_type
1113symmetric_coroutine<>::call_type
1114symmetric_coroutine<>::yield_type
1115\end{cfa}
1116Similarly, the canonical threading paradigm is often based on routine pointers, \eg @pthreads@~\cite{Butenhof97}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}.
1117However, the generic thread-handle (identifier) is limited (few operations), unless it is wrapped in a custom type.
1118\begin{cfa}
1119void mycor( coroutine_t cid, void * arg ) {
1120        int * value = (int *)arg;                               $\C{// type unsafe, pointer-size only}$
1121        // Coroutine body
1122}
1123int main() {
1124        int input = 0, output;
1125        coroutine_t cid = coroutine_create( &mycor, (void *)&input ); $\C{// type unsafe, pointer-size only}$
1126        coroutine_resume( cid, (void *)input, (void **)&output ); $\C{// type unsafe, pointer-size only}$
1127}
1128\end{cfa}
1129Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda-based coroutines adds very little.
1130
1131Note, the type @coroutine_t@ must be an abstract handle to the coroutine, because the coroutine descriptor and its stack are non-copyable.
1132Copying the coroutine descriptor results in copies being out of date with the current state of the stack.
1133Correspondingly, 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.
1134(There is no mechanism in C to find all stack-specific pointers and update them as part of a copy.)
1135
1136The selected approach is to use language support by introducing a new kind of aggregate (structure):
1137\begin{cfa}
1138coroutine Fibonacci {
1139        int fn; // communication variables
1140};
1141\end{cfa}
1142The @coroutine@ keyword means the compiler (and tool set) can find and inject code where needed.
1143The downside of this approach is that it makes coroutine a special case in the language.
1144Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language.
1145Furthermore, implementing coroutines without language supports also displays the power of a programming language.
1146While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can still be constructed without language support.
1147The reserved keyword simply eases use for the common case.
1148
1149Part 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:
1150\begin{cfa}
1151trait is_coroutine( `dtype` T ) {
1152        void main( T & );
1153        coroutine_desc * get_coroutine( T & );
1154};
1155forall( `dtype` T | is_coroutine(T) ) void suspend( T & );
1156forall( `dtype` T | is_coroutine(T) ) void resume( T & );
1157\end{cfa}
1158The @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).
1159The 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.
1160The @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.
1161The 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@.
1162The \CFA keyword @coroutine@ implicitly implements the getter and forward declarations required for implementing the coroutine main:
1163\begin{cquote}
1164\begin{tabular}{@{}ccc@{}}
1165\begin{cfa}
1166coroutine MyCor {
1167        int value;
1168
1169};
1170\end{cfa}
1171&
1172{\Large $\Rightarrow$}
1173&
1174\begin{tabular}{@{}ccc@{}}
1175\begin{cfa}
1176struct MyCor {
1177        int value;
1178        coroutine_desc cor;
1179};
1180\end{cfa}
1181&
1182\begin{cfa}
1183static inline coroutine_desc *
1184get_coroutine( MyCor & this ) {
1185        return &this.cor;
1186}
1187\end{cfa}
1188&
1189\begin{cfa}
1190void main( MyCor * this );
1191
1192
1193
1194\end{cfa}
1195\end{tabular}
1196\end{tabular}
1197\end{cquote}
1198The 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.
1199
1200
1201\section{Concurrency}
1202\label{s:Concurrency}
1203
1204At its core, concurrency is based on multiple call-stacks and scheduling threads executing on these stacks.
1205Multiple 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}.
1206In 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.
1207A \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;
1208a \newterm{stackful} coroutine executes on its own stack, allowing full generality.
1209Only stackful coroutines are a stepping stone to concurrency.
1210
1211The 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}.
1212Therefore, a minimal concurrency system is possible using coroutines (see Section \ref{coroutine}) in conjunction with a scheduler to decide where to context switch next.
1213The resulting execution system now follows a cooperative threading-model, called \newterm{non-preemptive scheduling}.
1214
1215Because the scheduler is special, it can either be a stackless or stackful coroutine.
1216For 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.
1217For 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.
1218A stackful scheduler is often used for simplicity and security.
1219
1220Regardless of the approach used, a subset of concurrency related challenges start to appear.
1221For 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}.
1222While a scheduler introduces uncertainty in the order of execution, preemption introduces uncertainty about where context switches occur.
1223Interestingly, uncertainty is necessary for the runtime (operating) system to give the illusion of parallelism on a single processor and increase performance on multiple processors.
1224The reason is that only the runtime has complete knowledge about resources and how to best utilized them.
1225However, the introduction of unrestricted non-determinism results in the need for \newterm{mutual exclusion} and \newterm{synchronization} to restrict non-determinism for correctness;
1226otherwise, it is impossible to write meaningful programs.
1227Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows.
1228
1229An 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.
1230As such, library support for threading is far from widespread.
1231At the time of writing the paper, neither \protect\lstinline@gcc@ nor \protect\lstinline@clang@ support \protect\lstinline@threads.h@ in their standard libraries.}.
1232In 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.
1233As 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.
1234Furthermore, because C is a system-level language, programmers expect to choose precisely which features they need and which cost they are willing to pay.
1235Hence, concurrent programs should be written using high-level mechanisms, and only step down to lower-level mechanisms when performance bottlenecks are encountered.
1236
1237
1238\subsection{Thread Interface}
1239\label{threads}
1240
1241Both user and kernel threads are supported, where user threads provide concurrency and kernel threads provide parallelism.
1242Like 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:
1243\begin{cquote}
1244\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
1245\begin{cfa}
1246thread myThread {
1247        // communication variables
1248};
1249
1250
1251\end{cfa}
1252&
1253\begin{cfa}
1254trait is_thread( `dtype` T ) {
1255      void main( T & );
1256      thread_desc * get_thread( T & );
1257      void ^?{}( T & `mutex` );
1258};
1259\end{cfa}
1260\end{tabular}
1261\end{cquote}
1262(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitor}.)
1263Like a coroutine, the statically-typed @main@ routine is the starting point (first stack frame) of a user thread.
1264The difference is that a coroutine borrows a thread from its caller, so the first thread resuming a coroutine creates an instance of @main@;
1265whereas, 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{
1266The \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.}
1267No 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.
1268
1269\begin{comment} % put in appendix with coroutine version ???
1270As such the @main@ routine of a thread can be defined as
1271\begin{cfa}
1272thread foo {};
1273
1274void main(foo & this) {
1275        sout | "Hello World!";
1276}
1277\end{cfa}
1278
1279In 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.
1280With 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.
1281\begin{cfa}
1282typedef void (*voidRtn)(int);
1283
1284thread RtnRunner {
1285        voidRtn func;
1286        int arg;
1287};
1288
1289void ?{}(RtnRunner & this, voidRtn inRtn, int arg) {
1290        this.func = inRtn;
1291        this.arg  = arg;
1292}
1293
1294void main(RtnRunner & this) {
1295        // thread starts here and runs the routine
1296        this.func( this.arg );
1297}
1298
1299void hello(/*unused*/ int) {
1300        sout | "Hello World!";
1301}
1302
1303int main() {
1304        RtnRunner f = {hello, 42};
1305        return 0?
1306}
1307\end{cfa}
1308A 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}.
1309\end{comment}
1310
1311For user threads to be useful, it must be possible to start and stop the underlying thread, and wait for it to complete execution.
1312While using an API such as @fork@ and @join@ is relatively common, such an interface is awkward and unnecessary.
1313A simple approach is to use allocation/deallocation principles, and have threads implicitly @fork@ after construction and @join@ before destruction.
1314\begin{cfa}
1315thread World {};
1316void main( World & this ) {
1317        sout | "World!";
1318}
1319int main() {
1320        World w`[10]`;                                                  $\C{// implicit forks after creation}$
1321        sout | "Hello ";                                        $\C{// "Hello " and 10 "World!" printed concurrently}$
1322}                                                                                       $\C{// implicit joins before destruction}$
1323\end{cfa}
1324This semantics ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
1325This 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.
1326\begin{cfa}
1327int main() {
1328        MyThread * heapLive;
1329        {
1330                MyThread blockLive;                                     $\C{// fork block-based thread}$
1331                heapLive = `new`( MyThread );           $\C{// fork heap-based thread}$
1332                ...
1333        }                                                                               $\C{// join block-based thread}$
1334        ...
1335        `delete`( heapLive );                                   $\C{// join heap-based thread}$
1336}
1337\end{cfa}
1338The heap-based approach allows arbitrary thread-creation topologies, with respect to fork/join-style concurrency.
1339
1340Figure~\ref{s:ConcurrentMatrixSummation} shows concurrently adding the rows of a matrix and then totalling the subtotals sequentially, after all the row threads have terminated.
1341The program uses heap-based threads because each thread needs different constructor values.
1342(Python provides a simple iteration mechanism to initialize array elements to different values allowing stack allocation.)
1343The allocation/deallocation pattern appears unusual because allocated objects are immediately deallocated without any intervening code.
1344However, for threads, the deletion provides implicit synchronization, which is the intervening code.
1345While 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.
1346
1347\begin{figure}
1348\begin{cfa}
1349`thread` Adder { int * row, cols, & subtotal; } $\C{// communication variables}$
1350void ?{}( Adder & adder, int row[], int cols, int & subtotal ) {
1351    adder.[ row, cols, &subtotal ] = [ row, cols, &subtotal ];
1352}
1353void main( Adder & adder ) with( adder ) {
1354    subtotal = 0;
1355    for ( int c = 0; c < cols; c += 1 ) { subtotal += row[c]; }
1356}
1357int main() {
1358    const int rows = 10, cols = 1000;
1359    int matrix[rows][cols], subtotals[rows], total = 0;
1360    // read matrix
1361    Adder * adders[rows];
1362    for ( int r = 0; r < rows; r += 1 ) {       $\C{// start threads to sum rows}$
1363                adders[r] = `new( matrix[r], cols, &subtotals[r] );`
1364    }
1365    for ( int r = 0; r < rows; r += 1 ) {       $\C{// wait for threads to finish}$
1366                `delete( adders[r] );`                          $\C{// termination join}$
1367                total += subtotals[r];                          $\C{// total subtotal}$
1368    }
1369    sout | total;
1370}
1371\end{cfa}
1372\caption{Concurrent Matrix Summation}
1373\label{s:ConcurrentMatrixSummation}
1374\end{figure}
1375
1376
1377\section{Mutual Exclusion / Synchronization}
1378
1379Uncontrolled non-deterministic execution is meaningless.
1380To 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}.
1381Since 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).
1382In 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}.
1383However, 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.
1384Hence, a programmer must learn and manipulate two sets of design patterns.
1385While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
1386In contrast, approaches based on stateful models more closely resemble the standard call/return programming-model, resulting in a single programming paradigm.
1387
1388At 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}.
1389However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}.
1390A newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
1391While 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.
1392
1393One of the most natural, elegant, and efficient mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor}.
1394First 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}.
1395In 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.
1396For these reasons, \CFA selected monitors as the core high-level concurrency-construct, upon which higher-level approaches can be easily constructed.
1397
1398
1399\subsection{Mutual Exclusion}
1400
1401A group of instructions manipulating a specific instance of shared data that must be performed atomically is called an (individual) \newterm{critical-section}~\cite{Dijkstra65}.
1402The 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.
1403The 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.
1404\newterm{Mutual exclusion} enforces that the correct kind and number of threads are using a critical section.
1405
1406However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
1407Methods 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.
1408Ease 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.
1409For 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.
1410However, a significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock.
1411Easing composability is another feature higher-level mutual-exclusion mechanisms can offer.
1412
1413
1414\subsection{Synchronization}
1415
1416Synchronization enforces relative ordering of execution, and synchronization tools provide numerous mechanisms to establish these timing relationships.
1417Low-level synchronization primitives offer good performance and flexibility at the cost of ease of use;
1418higher-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.
1419Often 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.
1420If a writer thread is scheduled for next access, but another reader thread acquires the critical section first, that reader \newterm{barged}.
1421Barging 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).
1422Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
1423This challenge is often split into two different approaches: barging avoidance and barging prevention.
1424Algorithms that allow a barger, but divert it until later using current synchronization state (flags), are avoiding the barger;
1425algorithms that preclude a barger from entering during synchronization in the critical section prevent barging completely.
1426Techniques like baton-passing locks~\cite{Andrews89} between threads instead of unconditionally releasing locks is an example of barging prevention.
1427
1428
1429\section{Monitor}
1430\label{s:Monitor}
1431
1432A \textbf{monitor} is a set of routines that ensure mutual exclusion when accessing shared state.
1433More 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).
1434The strong association with the call/return paradigm eases programmability, readability and maintainability, at a slight cost in flexibility and efficiency.
1435
1436Note, 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.
1437Copying 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.
1438Copying 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.
1439As 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).
1440\begin{cfa}
1441trait is_monitor( `dtype` T ) {
1442        monitor_desc * get_monitor( T & );
1443        void ^?{}( T & mutex );
1444};
1445\end{cfa}
1446
1447
1448\subsection{Mutex Acquisition}
1449\label{s:MutexAcquisition}
1450
1451While correctness implies a monitor's mutual exclusion is acquired and released, there are implementation options about when and where the locking/unlocking occurs.
1452(Much of this discussion also applies to basic locks.)
1453For example, a monitor may need to be passed through multiple helper routines before it becomes necessary to acquire the monitor mutual-exclusion.
1454\begin{cfa}[morekeywords=nomutex]
1455monitor Aint { int cnt; };                                      $\C{// atomic integer counter}$
1456void ?{}( Aint & `nomutex` this ) with( this ) { cnt = 0; } $\C{// constructor}$
1457int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions}$
1458void ?{}( int & this, Aint & `mutex`$\(_{opt}\)$ v ) { this = v.cnt; }
1459int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; }
1460int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$
1461\end{cfa}
1462The @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.
1463(While a constructor may publish its address into a global variable, doing so generates a race-condition.)
1464The conversion operators for initializing and assigning with a normal integer only need @mutex@, if reading/writing the implementation type is not atomic.
1465Finally, 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.
1466
1467The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics, which is similar to the \CC template @std::atomic@.
1468\begin{cfa}
1469Aint x, y, z;
1470++x; ++y; ++z;                                                          $\C{// safe increment by multiple threads}$
1471x = 2; y = 2; z = 2;                                            $\C{// conversions}$
1472int i = x, j = y, k = z;
1473i = x; j = y; k = z;
1474\end{cfa}
1475
1476For maximum usability, monitors have \newterm{multi-acquire} semantics allowing a thread to acquire it multiple times without deadlock.
1477\begin{cfa}
1478monitor M { ... } m;
1479void foo( M & mutex m ) { ... }                         $\C{// acquire mutual exclusion}$
1480void bar( M & mutex m ) {                                       $\C{// acquire mutual exclusion}$
1481        ... `foo( m );` ...                                             $\C{// reacquire mutual exclusion}$
1482}
1483`bar( m );`                                                                     $\C{// nested monitor call}$
1484\end{cfa}
1485
1486The benefit of mandatory monitor qualifiers is self-documentation, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameters is redundant.
1487Instead, the semantics have one qualifier as the default, and the other required.
1488For example, make the safe @mutex@ qualifier the default because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
1489Alternatively, make the unsafe \lstinline[morekeywords=nomutex]@nomutex@ qualifier the default because it is the \emph{normal} parameter semantics while @mutex@ parameters are rare.
1490Providing a default qualifier implies knowing whether a parameter is a monitor.
1491Since \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.
1492For 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@.
1493
1494The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@.
1495Given:
1496\begin{cfa}
1497monitor M { ... }
1498int f1( M & mutex m );
1499int f2( M * mutex m );
1500int f3( M * mutex m[] );
1501int f4( stack( M * ) & mutex m );
1502\end{cfa}
1503the issue is that some of these parameter types are composed of multiple objects.
1504For @f1@, there is only a single parameter object.
1505Adding indirection in @f2@ still identifies a single object.
1506However, the matrix in @f3@ introduces multiple objects.
1507While shown shortly, multiple acquisition is possible;
1508however array lengths are often unknown in C.
1509This issue is exacerbated in @f4@, where the data structure must be safely traversed to acquire all of its elements.
1510
1511To make the issue tractable, \CFA only acquires one monitor per parameter with at most one level of indirection.
1512However, there is an ambiguity in the C type-system with respects to arrays.
1513Is the argument for @f2@ a single object or an array of objects?
1514If it is an array, only the first element of the array is acquired, which seems unsafe;
1515hence, @mutex@ is disallowed for array parameters.
1516\begin{cfa}
1517int f1( M & mutex m );                                          $\C{// allowed: recommended case}$
1518int f2( M * mutex m );                                          $\C{// disallowed: could be an array}$
1519int f3( M mutex m[$\,$] );                                      $\C{// disallowed: array length unknown}$
1520int f4( M ** mutex m );                                         $\C{// disallowed: could be an array}$
1521int f5( M * mutex m[$\,$] );                            $\C{// disallowed: array length unknown}$
1522\end{cfa}
1523% Note, not all array routines have distinct types: @f2@ and @f3@ have the same type, as do @f4@ and @f5@.
1524% However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
1525
1526For object-oriented monitors, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
1527\CFA has no receiver, and hence, must use an explicit mechanism to specify which object acquires mutual exclusion.
1528A positive consequence of this design decision is the ability to support multi-monitor routines.
1529\begin{cfa}
1530int f( M & mutex x, M & mutex y );              $\C{// multiple monitor parameter of any type}$
1531M m1, m2;
1532f( m1, m2 );
1533\end{cfa}
1534(While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.)
1535In practice, writing multi-locking routines that do not deadlock is tricky.
1536Having language support for such a feature is therefore a significant asset for \CFA.
1537
1538The capability to acquire multiple locks before entering a critical section is called \newterm{bulk acquire} (see Section~\ref{s:Implementation} for implementation details).
1539In the previous example, \CFA guarantees the order of acquisition is consistent across calls to different routines using the same monitors as arguments.
1540This consistent ordering means acquiring multiple monitors is safe from deadlock.
1541However, users can force the acquiring order.
1542For example, notice the use of @mutex@/\lstinline[morekeywords=nomutex]@nomutex@ and how this affects the acquiring order:
1543\begin{cfa}
1544void foo( M & mutex m1, M & mutex m2 );         $\C{// acquire m1 and m2}$
1545void bar( M & mutex m1, M & /* nomutex */ m2 ) { $\C{// acquire m1}$
1546        ... foo( m1, m2 ); ...                                  $\C{// acquire m2}$
1547}
1548void baz( M & /* nomutex */ m1, M & mutex m2 ) { $\C{// acquire m2}$
1549        ... foo( m1, m2 ); ...                                  $\C{// acquire m1}$
1550}
1551\end{cfa}
1552The multi-acquire semantics allows @bar@ or @baz@ to acquire a monitor lock and reacquire it in @foo@.
1553In the calls to @bar@ and @baz@, the monitors are acquired in opposite order.
1554
1555However, 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}.
1556In \CFA, a safety aid is provided by using bulk acquire of all monitors to shared objects, whereas other monitor systems provide no aid.
1557While \CFA provides only a partial solution, it handles many useful cases, \eg:
1558\begin{cfa}
1559monitor BankAccount { ... };
1560void deposit( BankAccount & `mutex` b, int deposit );
1561void transfer( BankAccount & `mutex` my, BankAccount & `mutex` your, int me2you ) {
1562        deposit( my, `-`me2you );                               $\C{// debit}$
1563        deposit( your, me2you );                                $\C{// credit}$
1564}
1565\end{cfa}
1566This example shows a trivial solution to the bank-account transfer problem.
1567Without multi- and bulk acquire, the solution to this problem requires careful engineering.
1568
1569
1570\subsection{\protect\lstinline@mutex@ statement}
1571\label{mutex-stmt}
1572
1573The monitor call-semantics associate all locking semantics to routines.
1574Like Java, \CFA offers an alternative @mutex@ statement to reduce refactoring and naming.
1575\begin{cquote}
1576\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
1577\begin{cfa}
1578monitor M { ... };
1579void foo( M & mutex m1, M & mutex m2 ) {
1580        // critical section
1581}
1582void bar( M & m1, M & m2 ) {
1583        foo( m1, m2 );
1584}
1585\end{cfa}
1586&
1587\begin{cfa}
1588
1589void bar( M & m1, M & m2 ) {
1590        mutex( m1, m2 ) {       // remove refactoring and naming
1591                // critical section
1592        }
1593}
1594
1595\end{cfa}
1596\\
1597\multicolumn{1}{c}{\textbf{routine call}} & \multicolumn{1}{c}{\lstinline@mutex@ \textbf{statement}}
1598\end{tabular}
1599\end{cquote}
1600
1601
1602\section{Scheduling}
1603\label{s:Scheduling}
1604
1605While monitor mutual-exclusion provides safe access to shared data, the monitor data may indicate that a thread accessing it cannot proceed.
1606For example, Figure~\ref{f:GenericBoundedBuffer} shows a bounded buffer that may be full/empty so produce/consumer threads must block.
1607Leaving the monitor and trying again (busy waiting) is impractical for high-level programming.
1608Monitors eliminate busy waiting by providing synchronization to schedule threads needing access to the shared data, where threads block versus spinning.
1609Synchronization 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.
1610\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.
1611
1612Figure~\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@.
1613The @wait@ routine atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the routine's parameter list.
1614The appropriate condition lock is signalled to unblock an opposite kind of thread after an element is inserted/removed from the buffer.
1615Signalling is unconditional, because signalling an empty condition lock does nothing.
1616
1617Signalling semantics cannot have the signaller and signalled thread in the monitor simultaneously, which means:
1618\begin{enumerate}
1619\item
1620The signalling thread returns immediately, and the signalled thread continues.
1621\item
1622The signalling thread continues and the signalled thread is marked for urgent unblocking at the next scheduling point (exit/wait).
1623\item
1624The signalling thread blocks but is marked for urgrent unblocking at the next scheduling point and the signalled thread continues.
1625\end{enumerate}
1626The first approach is too restrictive, as it precludes solving a reasonable class of problems, \eg dating service (see Figure~\ref{f:DatingService}).
1627\CFA supports the next two semantics as both are useful.
1628Finally, while it is common to store a @condition@ as a field of the monitor, in \CFA, a @condition@ variable can be created/stored independently.
1629Furthermore, 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.
1630
1631\begin{figure}
1632\centering
1633\newbox\myboxA
1634\begin{lrbox}{\myboxA}
1635\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1636forall( otype T ) { // distribute forall
1637        monitor Buffer {
1638                `condition` full, empty;
1639                int front, back, count;
1640                T elements[10];
1641        };
1642        void ?{}( Buffer(T) & buffer ) with(buffer) {
1643                [front, back, count] = 0;
1644        }
1645
1646        void insert( Buffer(T) & mutex buffer, T elem )
1647                                with(buffer) {
1648                if ( count == 10 ) `wait( empty )`;
1649                // insert elem into buffer
1650                `signal( full )`;
1651        }
1652        T remove( Buffer(T) & mutex buffer ) with(buffer) {
1653                if ( count == 0 ) `wait( full )`;
1654                // remove elem from buffer
1655                `signal( empty )`;
1656                return elem;
1657        }
1658}
1659\end{cfa}
1660\end{lrbox}
1661
1662\newbox\myboxB
1663\begin{lrbox}{\myboxB}
1664\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1665forall( otype T ) { // distribute forall
1666        monitor Buffer {
1667
1668                int front, back, count;
1669                T elements[10];
1670        };
1671        void ?{}( Buffer(T) & buffer ) with(buffer) {
1672                [front, back, count] = 0;
1673        }
1674        T remove( Buffer(T) & mutex buffer ); // forward
1675        void insert( Buffer(T) & mutex buffer, T elem )
1676                                with(buffer) {
1677                if ( count == 10 ) `waitfor( remove, buffer )`;
1678                // insert elem into buffer
1679
1680        }
1681        T remove( Buffer(T) & mutex buffer ) with(buffer) {
1682                if ( count == 0 ) `waitfor( insert, buffer )`;
1683                // remove elem from buffer
1684
1685                return elem;
1686        }
1687}
1688\end{cfa}
1689\end{lrbox}
1690
1691\subfloat[Internal Scheduling]{\label{f:BBInt}\usebox\myboxA}
1692%\qquad
1693\subfloat[External Scheduling]{\label{f:BBExt}\usebox\myboxB}
1694\caption{Generic Bounded-Buffer}
1695\label{f:GenericBoundedBuffer}
1696\end{figure}
1697
1698Figure~\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.
1699External 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.
1700If 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.
1701Threads 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.
1702External scheduling allows users to wait for events from other threads without concern of unrelated events occurring.
1703The mechnaism can be done in terms of control flow, \eg Ada @accept@ or \uC @_Accept@, or in terms of data, \eg Go channels.
1704While both mechanisms have strengths and weaknesses, this project uses a control-flow mechanism to stay consistent with other language semantics.
1705Two 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}).
1706
1707For internal scheduling, non-blocking signalling (as in the producer/consumer example) is used when the signaller is providing the cooperation for a waiting thread;
1708the 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.
1709The waiter unblocks next from the urgent queue, uses/takes the state, and exits the monitor.
1710Blocking signalling is the reverse, where the waiter is providing the cooperation for the signalling thread;
1711the 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.
1712The waiter changes state and exits the monitor, and the signaller unblocks next from the urgent queue to use/take the state.
1713
1714Figure~\ref{f:DatingService} shows a dating service demonstrating non-blocking and blocking signalling.
1715The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers.
1716A thread blocks until an appropriate partner arrives.
1717The complexity is exchanging phone numbers in the monitor because of the mutual-exclusion property.
1718For 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.
1719For 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.
1720
1721The 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;
1722as well, an arriving thread may not find a partner and must wait, which requires a condition variable, and condition variables imply internal scheduling.
1723
1724\begin{figure}
1725\centering
1726\newbox\myboxA
1727\begin{lrbox}{\myboxA}
1728\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1729enum { CCodes = 20 };
1730monitor DS {
1731        int GirlPhNo, BoyPhNo;
1732        condition Girls[CCodes], Boys[CCodes];
1733        condition exchange;
1734};
1735int girl( DS & mutex ds, int phNo, int ccode ) {
1736        if ( is_empty( Boys[ccode] ) ) {
1737                wait( Girls[ccode] );
1738                GirlPhNo = phNo;
1739                `signal( exchange );`
1740        } else {
1741                GirlPhNo = phNo;
1742                `signal( Boys[ccode] );`
1743                `wait( exchange );`
1744        } // if
1745        return BoyPhNo;
1746}
1747int boy( DS & mutex ds, int phNo, int ccode ) {
1748        // as above with boy/girl interchanged
1749}
1750\end{cfa}
1751\end{lrbox}
1752
1753\newbox\myboxB
1754\begin{lrbox}{\myboxB}
1755\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1756
1757monitor DS {
1758        int GirlPhNo, BoyPhNo;
1759        condition Girls[CCodes], Boys[CCodes];
1760
1761};
1762int girl( DS & mutex ds, int phNo, int ccode ) {
1763        if ( is_empty( Boys[ccode] ) ) { // no compatible
1764                wait( Girls[ccode] ); // wait for boy
1765                GirlPhNo = phNo; // make phone number available
1766
1767        } else {
1768                GirlPhNo = phNo; // make phone number available
1769                `signal_block( Boys[ccode] );` // restart boy
1770
1771        } // if
1772        return BoyPhNo;
1773}
1774int boy( DS & mutex ds, int phNo, int ccode ) {
1775        // as above with boy/girl interchanged
1776}
1777\end{cfa}
1778\end{lrbox}
1779
1780\subfloat[\lstinline@signal@]{\label{f:DatingSignal}\usebox\myboxA}
1781\qquad
1782\subfloat[\lstinline@signal_block@]{\label{f:DatingSignalBlock}\usebox\myboxB}
1783\caption{Dating service. }
1784\label{f:DatingService}
1785\end{figure}
1786
1787Both internal and external scheduling extend to multiple monitors in a natural way.
1788\begin{cquote}
1789\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
1790\begin{cfa}
1791monitor M { `condition e`; ... };
1792void foo( M & mutex m1, M & mutex m2 ) {
1793        ... wait( `e` ); ...   // wait( e, m1, m2 )
1794        ... wait( `e, m1` ); ...
1795        ... wait( `e, m2` ); ...
1796}
1797\end{cfa}
1798&
1799\begin{cfa}
1800void rtn$\(_1\)$( M & mutex m1, M & mutex m2 );
1801void rtn$\(_2\)$( M & mutex m1 );
1802void bar( M & mutex m1, M & mutex m2 ) {
1803        ... waitfor( `rtn` ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\), m1, m2 )}$
1804        ... waitfor( `rtn, m1` ); ... // $\LstCommentStyle{waitfor( rtn\(_2\), m1 )}$
1805}
1806\end{cfa}
1807\end{tabular}
1808\end{cquote}
1809For @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 )@.
1810To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
1811Wait statically verifies the released monitors are the acquired mutex-parameters so unconditional release is safe.
1812Finally, a signaller,
1813\begin{cfa}
1814void baz( M & mutex m1, M & mutex m2 ) {
1815        ... signal( e ); ...
1816}
1817\end{cfa}
1818must have acquired at least the same locks as the waiting thread signalled from the condition queue.
1819
1820Similarly, 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 )@.
1821To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn, m1 )@.
1822@waitfor@ statically verifies the released monitors are the same as the acquired mutex-parameters of the given routine or routine pointer.
1823To statically verify the released monitors match with the accepted routine's mutex parameters, the routine (pointer) prototype must be accessible.
1824% When an overloaded routine appears in an @waitfor@ statement, calls to any routine with that name are accepted.
1825% The rationale is that members with the same name should perform a similar function, and therefore, all should be eligible to accept a call.
1826Overloaded routines can be disambiguated using a cast:
1827\begin{cfa}
1828void rtn( M & mutex m );
1829`int` rtn( M & mutex m );
1830waitfor( (`int` (*)( M & mutex ))rtn, m );
1831\end{cfa}
1832
1833The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock.
1834\begin{cfa}
1835void foo( M & mutex m1, M & mutex m2 ) {
1836        ... wait( `e, m1` ); ...                                $\C{// release m1, keeping m2 acquired )}$
1837void bar( M & mutex m1, M & mutex m2 ) {        $\C{// must acquire m1 and m2 )}$
1838        ... signal( `e` ); ...
1839\end{cfa}
1840The @wait@ only releases @m1@ so the signalling thread cannot acquire both @m1@ and @m2@ to  enter @bar@ to get to the @signal@.
1841While deadlock issues can occur with multiple/nesting acquisition, this issue results from the fact that locks, and by extension monitors, are not perfectly composable.
1842
1843Finally, an important aspect of monitor implementation is barging, \ie can calling threads barge ahead of signalled threads?
1844If 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).
1845In fact, signals-as-hints is completely opposite from that proposed by Hoare in the seminal paper on monitors:
1846\begin{quote}
1847However, 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.
1848It 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}
1849\end{quote}
1850\CFA scheduling \emph{precludes} barging, which simplifies synchronization among threads in the monitor and increases correctness.
1851Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implict form of barging.
1852For example, there are no loops in either bounded buffer solution in Figure~\ref{f:GenericBoundedBuffer}.
1853Supporting 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.
1854
1855
1856\subsection{Barging Prevention}
1857
1858Figure~\ref{f:BargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signalling semantics.
1859The complexity begins at the end of the inner @mutex@ statement, where the semantics of internal scheduling need to be extended for multiple monitors.
1860The problem is that bulk acquire is used in the inner @mutex@ statement where one of the monitors is already acquired.
1861When 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.
1862However, both the signalling and waiting thread W1 still need monitor @m1@.
1863
1864\begin{figure}
1865\newbox\myboxA
1866\begin{lrbox}{\myboxA}
1867\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1868monitor M m1, m2;
1869condition c;
1870mutex( m1 ) { // $\LstCommentStyle{\color{red}outer}$
1871        ...
1872        mutex( m1, m2 ) { // $\LstCommentStyle{\color{red}inner}$
1873                ... `signal( c )`; ...
1874                // m1, m2 acquired
1875        } // $\LstCommentStyle{\color{red}release m2}$
1876        // m1 acquired
1877} // release m1
1878\end{cfa}
1879\end{lrbox}
1880
1881\newbox\myboxB
1882\begin{lrbox}{\myboxB}
1883\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1884
1885
1886mutex( m1 ) {
1887        ...
1888        mutex( m1, m2 ) {
1889                ... `wait( c )`; // block and release m1, m2
1890                // m1, m2 acquired
1891        } // $\LstCommentStyle{\color{red}release m2}$
1892        // m1 acquired
1893} // release m1
1894\end{cfa}
1895\end{lrbox}
1896
1897\newbox\myboxC
1898\begin{lrbox}{\myboxC}
1899\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1900
1901
1902mutex( m2 ) {
1903        ... `wait( c )`; ...
1904        // m2 acquired
1905} // $\LstCommentStyle{\color{red}release m2}$
1906
1907
1908
1909
1910\end{cfa}
1911\end{lrbox}
1912
1913\begin{cquote}
1914\subfloat[Signalling Thread]{\label{f:SignallingThread}\usebox\myboxA}
1915\hspace{2\parindentlnth}
1916\subfloat[Waiting Thread (W1)]{\label{f:WaitingThread}\usebox\myboxB}
1917\hspace{2\parindentlnth}
1918\subfloat[Waiting Thread (W2)]{\label{f:OtherWaitingThread}\usebox\myboxC}
1919\end{cquote}
1920\caption{Barging Prevention}
1921\label{f:BargingPrevention}
1922\end{figure}
1923
1924One 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.
1925However, Figure~\ref{f:OtherWaitingThread} shows this solution is complex depending on other waiters, resulting in options when the signaller finishes the inner mutex-statement.
1926The 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@.
1927In 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.
1928Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
1929
1930While a number of approaches were examined~\cite[\S~4.3]{Delisle18}, the solution chosen for \CFA is a novel techique called \newterm{partial signalling}.
1931Signalled threads are moved to the urgent queue and the waiter at the front defines the set of monitors necessary for it to unblock.
1932Partial signalling transfers ownership of monitors to the front waiter.
1933When the signaller thread exits or waits in the monitor, the front waiter is unblocked if all its monitors are released.
1934The 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.
1935
1936
1937\subsection{Loose Object Definitions}
1938\label{s:LooseObjectDefinitions}
1939
1940In an object-oriented programming-language, a class includes an exhaustive list of operations.
1941However, new members can be added via static inheritance or dynamic members, \eg JavaScript~\cite{JavaScript}.
1942Similarly, monitor routines can be added at any time in \CFA, making it less clear for programmers and more difficult to implement.
1943\begin{cfa}
1944monitor M { ... };
1945void `f`( M & mutex m );
1946void g( M & mutex m ) { waitfor( `f` ); }       $\C{// clear which f}$
1947void `f`( M & mutex m, int );                           $\C{// different f}$
1948void h( M & mutex m ) { waitfor( `f` ); }       $\C{// unclear which f}$
1949\end{cfa}
1950Hence, the cfa-code for entering a monitor looks like:
1951\begin{cfa}
1952if ( $\textrm{\textit{monitor is free}}$ ) $\LstCommentStyle{// \color{red}enter}$
1953else if ( $\textrm{\textit{already own monitor}}$ ) $\LstCommentStyle{// \color{red}continue}$
1954else if ( $\textrm{\textit{monitor accepts me}}$ ) $\LstCommentStyle{// \color{red}enter}$
1955else $\LstCommentStyle{// \color{red}block}$
1956\end{cfa}
1957For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions.
1958However, a fast check for \emph{monitor accepts me} is much harder to implement depending on the constraints put on the monitors.
1959Figure~\ref{fig:ClassicalMonitor} shows monitors are often expressed as an entry (calling) queue, some acceptor queues, and an urgent stack/queue.
1960
1961\begin{figure}
1962\centering
1963\subfloat[Classical monitor] {
1964\label{fig:ClassicalMonitor}
1965{\resizebox{0.45\textwidth}{!}{\input{monitor.pstex_t}}}
1966}% subfloat
1967\quad
1968\subfloat[Bulk acquire monitor] {
1969\label{fig:BulkMonitor}
1970{\resizebox{0.45\textwidth}{!}{\input{ext_monitor.pstex_t}}}
1971}% subfloat
1972\caption{Monitor Implementation}
1973\label{f:MonitorImplementation}
1974\end{figure}
1975
1976For 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.
1977This approach requires a unique dense ordering of routines with a small upper-bound and the ordering must be consistent across translation units.
1978For 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.
1979
1980Figure~\ref{fig:BulkMonitor} shows the \CFA monitor implementation.
1981The mutex routine called is associated with each thread on the entry queue, while a list of acceptable routines is kept separately.
1982The 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.
1983
1984
1985\subsection{Multi-Monitor Scheduling}
1986\label{s:Multi-MonitorScheduling}
1987
1988External scheduling, like internal scheduling, becomes significantly more complex for multi-monitor semantics.
1989Even in the simplest case, new semantics needs to be established.
1990\newpage
1991\begin{cfa}
1992monitor M { ... };
1993void f( M & mutex m1 );
1994void g( M & mutex m1, M & mutex m2 ) {
1995        waitfor( f );                                                   $\C{\color{red}// pass m1 or m2 to f?}$
1996}
1997\end{cfa}
1998The solution is for the programmer to disambiguate:
1999\begin{cfa}
2000        waitfor( f, m2 );                                               $\C{\color{red}// wait for call to f with argument m2}$
2001\end{cfa}
2002Both 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@.
2003This behaviour can be extended to the multi-monitor @waitfor@ statement.
2004\begin{cfa}
2005monitor M { ... };
2006void f( M & mutex m1, M & mutex m2 );
2007void g( M & mutex m1, M & mutex m2 ) {
2008        waitfor( f, m1, m2 );                                   $\C{\color{red}// wait for call to f with arguments m1 and m2}$
2009}
2010\end{cfa}
2011Again, the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired by the accepting routine.
2012Also, the order of the monitors in a @waitfor@ statement is unimportant.
2013
2014Figure~\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.
2015For both examples, the set of monitors is disjoint so unblocking is impossible.
2016
2017\begin{figure}
2018\lstDeleteShortInline@%
2019\begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
2020\begin{cfa}
2021monitor M1 {} m11, m12;
2022monitor M2 {} m2;
2023condition c;
2024void f( M1 & mutex m1, M2 & mutex m2 ) {
2025        signal( c );
2026}
2027void g( M1 & mutex m1, M2 & mutex m2 ) {
2028        wait( c );
2029}
2030g( `m11`, m2 ); // block on wait
2031f( `m12`, m2 ); // cannot fulfil
2032\end{cfa}
2033&
2034\begin{cfa}
2035monitor M1 {} m11, m12;
2036monitor M2 {} m2;
2037
2038void f( M1 & mutex m1, M2 & mutex m2 ) {
2039
2040}
2041void g( M1 & mutex m1, M2 & mutex m2 ) {
2042        waitfor( f, m1, m2 );
2043}
2044g( `m11`, m2 ); // block on accept
2045f( `m12`, m2 ); // cannot fulfil
2046\end{cfa}
2047\end{tabular}
2048\lstMakeShortInline@%
2049\caption{Unmatched \protect\lstinline@mutex@ sets}
2050\label{f:UnmatchedMutexSets}
2051\end{figure}
2052
2053
2054\subsection{Extended \protect\lstinline@waitfor@}
2055
2056Figure~\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.
2057For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding member(s) must exist.
2058The \emph{conditional-expression} of a @when@ may call a routine, but the routine must not block or context switch.
2059If 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@.
2060If 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.
2061If 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.
2062Hence, the terminating @else@ clause allows a conditional attempt to accept a call without blocking.
2063If there is a @timeout@ clause, it provides an upper bound on waiting.
2064If both a @timeout@ clause and an @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered.
2065In all cases, the statement following is executed \emph{after} a clause is executed to know which of the clauses executed.
2066
2067\begin{figure}
2068\begin{cfa}
2069`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
2070        waitfor( $\emph{mutex-member-name}$ )
2071                $\emph{statement}$                                      $\C{// action after call}$
2072`or` `when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
2073        waitfor( $\emph{mutex-member-name}$ )
2074                $\emph{statement}$                                      $\C{// action after call}$
2075`or`    ...                                                                     $\C{// list of waitfor clauses}$
2076`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
2077        `timeout`                                                               $\C{// optional terminating timeout clause}$
2078                $\emph{statement}$                                      $\C{// action after timeout}$
2079`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
2080        `else`                                                                  $\C{// optional terminating clause}$
2081                $\emph{statement}$                                      $\C{// action when no immediate calls}$
2082\end{cfa}
2083\caption{Extended \protect\lstinline@waitfor@}
2084\label{f:ExtendedWaitfor}
2085\end{figure}
2086
2087Note, a group of conditional @waitfor@ clauses is \emph{not} the same as a group of @if@ statements, e.g.:
2088\begin{cfa}
2089if ( C1 ) waitfor( mem1 );                       when ( C1 ) waitfor( mem1 );
2090else if ( C2 ) waitfor( mem2 );         or when ( C2 ) waitfor( mem2 );
2091\end{cfa}
2092The left example accepts only @mem1@ if @C1@ is true or only @mem2@ if @C2@ is true.
2093The right example accepts either @mem1@ or @mem2@ if @C1@ and @C2@ are true.
2094
2095An interesting use of @waitfor@ is accepting the @mutex@ destructor to know when an object is deallocated.
2096\begin{cfa}
2097void insert( Buffer(T) & mutex buffer, T elem ) with( buffer ) {
2098        if ( count == 10 )
2099                waitfor( remove, buffer ) {
2100                        // insert elem into buffer
2101                } or `waitfor( ^?{}, buffer )` throw insertFail;
2102}
2103\end{cfa}
2104When the buffer is deallocated, the current waiter is unblocked and informed, so it can perform an appropriate action.
2105However, the basic @waitfor@ semantics do not support this functionality, since using an object after its destructor is called is undefined.
2106Therefore, 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.
2107Accepting the destructor is an idiomatic way to terminate a thread in \CFA.
2108
2109
2110\subsection{\protect\lstinline@mutex@ Threads}
2111
2112Threads in \CFA are monitors to allow direct communication among threads, \ie threads can have mutex routines that are called by other threads.
2113Hence, all monitor features are available when using threads.
2114The following shows an example of two threads directly calling each other and accepting calls from each other in a cycle.
2115\begin{cfa}
2116thread Ping {} pi;
2117thread Pong {} po;
2118void ping( Ping & mutex ) {}
2119void pong( Pong & mutex ) {}
2120int main() {}
2121\end{cfa}
2122\vspace{-0.8\baselineskip}
2123\begin{cquote}
2124\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
2125\begin{cfa}
2126void main( Ping & pi ) {
2127        for ( int i = 0; i < 10; i += 1 ) {
2128                `waitfor( ping, pi );`
2129                `pong( po );`
2130        }
2131}
2132\end{cfa}
2133&
2134\begin{cfa}
2135void main( Pong & po ) {
2136        for ( int i = 0; i < 10; i += 1 ) {
2137                `ping( pi );`
2138                `waitfor( pong, po );`
2139        }
2140}
2141\end{cfa}
2142\end{tabular}
2143\end{cquote}
2144% \lstMakeShortInline@%
2145% \caption{Threads ping/pong using external scheduling}
2146% \label{f:pingpong}
2147% \end{figure}
2148Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start (and possibly complete) before the program main starts.
2149
2150
2151\subsection{Low-level Locks}
2152
2153For 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.
2154
2155
2156\section{Parallelism}
2157
2158Historically, computer performance was about processor speeds.
2159However, with heat dissipation being a direct consequence of speed increase, parallelism is the new source for increased performance~\cite{Sutter05, Sutter05b}.
2160Now, high-performance applications must care about parallelism, which requires concurrency.
2161The lowest-level approach of parallelism is to use \newterm{kernel threads} in combination with semantics like @fork@, @join@, \etc.
2162However, kernel threads are better as an implementation tool because of complexity and higher cost.
2163Therefore, different abstractions are often layered onto kernel threads to simplify them, \eg pthreads.
2164
2165
2166\subsection{User Threads with Preemption}
2167
2168A direct improvement on kernel threads is user threads, \eg Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
2169This 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.
2170In many cases, user threads can be used on a much larger scale (100,000 threads).
2171Like kernel threads, user threads support preemption, which maximizes nondeterminism, but introduces the same concurrency errors: race, livelock, starvation, and deadlock.
2172\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}.
2173
2174
2175\subsection{User Threads without Preemption (Fiber)}
2176\label{s:fibers}
2177
2178A variant of user thread is \newterm{fibers}, which removes preemption, \eg Go~\cite{Go} @goroutine@s.
2179Like functional programming, which removes mutation and its associated problems, removing preemption from concurrency reduces nondeterminism, making race and deadlock errors more difficult to generate.
2180However, preemption is necessary for concurrency that relies on spinning, so there are a class of problems that cannot be programmed without preemption.
2181
2182
2183\subsection{Thread Pools}
2184
2185In contrast to direct threading is indirect \newterm{thread pools}, where small jobs (work units) are inserted into a work pool for execution.
2186If the jobs are dependent, \ie interact, there is an implicit/explicit dependency graph that ties them together.
2187While removing direct concurrency, and hence the amount of context switching, thread pools significantly limit the interaction that can occur among jobs.
2188Indeed, jobs should not block because that also blocks the underlying thread, which effectively means the CPU utilization, and therefore throughput, suffers.
2189While 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.
2190As well, concurrency errors return, which threads pools are suppose to mitigate.
2191
2192
2193\section{\protect\CFA Runtime Structure}
2194
2195Figure~\ref{f:RunTimeStructure} illustrates the runtime structure of a \CFA program.
2196In 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.
2197An executing thread is illustrated by its containment in a processor.
2198
2199\begin{figure}
2200\centering
2201\input{RunTimeStructure}
2202\caption{\CFA Runtime Structure}
2203\label{f:RunTimeStructure}
2204\end{figure}
2205
2206
2207\subsection{Cluster}
2208\label{s:RuntimeStructureCluster}
2209
2210A \newterm{cluster} is a collection of threads and virtual processors (abstract kernel-thread) that execute the threads (like a virtual machine).
2211The purpose of a cluster is to control the amount of parallelism that is possible among threads, plus scheduling and other execution defaults.
2212The default cluster-scheduler is single-queue multi-server, which provides automatic load-balancing of threads on processors.
2213However, the scheduler is pluggable, supporting alternative schedulers.
2214If several clusters exist, both threads and virtual processors, can be explicitly migrated from one cluster to another.
2215No automatic load balancing among clusters is performed by \CFA.
2216
2217When 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.
2218The user cluster is created to contain the application user-threads.
2219Having all threads execute on the one cluster often maximizes utilization of processors, which minimizes runtime.
2220However, because of limitations of the underlying operating system, heterogeneous hardware, or scheduling requirements (real-time), multiple clusters are sometimes necessary.
2221
2222
2223\subsection{Virtual Processor}
2224\label{s:RuntimeStructureProcessor}
2225
2226A 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.
2227Programs may use more virtual processors than hardware processors.
2228On a multiprocessor, kernel threads are distributed across the hardware processors resulting in virtual processors executing in parallel.
2229(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.)
2230The \CFA runtime attempts to block unused processors and unblock processors as the system load increases;
2231balancing the workload with processors is difficult.
2232Preemption occurs on virtual processors rather than user threads, via operating-system interrupts.
2233Thus virtual processors execute user threads, where preemption frequency applies to a virtual processor, so preemption occurs randomly across the executed user threads.
2234Turning off preemption transforms user threads into fibers.
2235
2236
2237\subsection{Debug Kernel}
2238
2239There are two versions of the \CFA runtime kernel: debug and non-debug.
2240The 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.
2241After a program is debugged, the non-debugging version can be used to decrease space and increase performance.
2242
2243
2244\section{Implementation}
2245\label{s:Implementation}
2246
2247Currently, \CFA has fixed-sized stacks, where the stack size can be set at coroutine/thread creation but with no subsequent growth.
2248Schemes exist for dynamic stack-growth, such as stack copying and chained stacks.
2249However, stack copying requires pointer adjustment to items on the stack, which is impossible without some form of garbage collection.
2250As well, chained stacks require all modules be recompiled to use this feature, which breaks backward compatibility with existing C libraries.
2251In the long term, it is likely C libraries will migrate to stack chaining to support concurrency, at only a minimal cost to sequential programs.
2252Nevertheless, experience teaching \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue in most concurrent programs.
2253
2254A primary implementation challenge is avoiding contention from dynamically allocating memory because of bulk acquire, \eg the internal-scheduling design is (almost) free of allocations.
2255All 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.
2256Furthermore, several bulk-acquire operations need a variable amount of memory.
2257This 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.
2258
2259In \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.
2260When a mutex call is made, pointers to the concerned monitors are aggregated into a variable-length array and sorted.
2261This array persists for the entire duration of the mutual exclusion and is used extensively for synchronization operations.
2262
2263To 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;
2264the corresponding registers are then restored for the other context.
2265Note, the instruction pointer is untouched since the context switch is always inside the same routine.
2266Unlike coroutines, threads do not context switch among each other;
2267they context switch to the cluster scheduler.
2268This method is a 2-step context-switch and provides a clear distinction between user and kernel code, where scheduling and other system operations happen.
2269The 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.
2270Experimental 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.
2271
2272All kernel threads (@pthreads@) created a stack.
2273Each \CFA virtual processor is implemented as a coroutine and these coroutines run directly on the kernel-thread stack, effectively stealing this stack.
2274The exception to this rule is the program main, \ie the initial kernel thread that is given to any program.
2275In 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.
2276
2277Finally, 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.
2278Because preemption frequency is usually long (1 millisecond) performance cost is negligible.
2279Preemption is normally handled by setting a count-down timer on each virtual processor.
2280When 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.
2281Multiple signal handlers may be pending.
2282When 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.
2283The 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;
2284therefore, the same signal mask is required for all virtual processors in a cluster.
2285
2286However, on current UNIX systems:
2287\begin{quote}
2288A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
2289If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
2290SIGNAL(7) - Linux Programmer's Manual
2291\end{quote}
2292Hence, 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).
2293To 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.
2294Virtual processors register an expiration time with the discrete-event simulator, which is inserted in sorted order.
2295The 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.
2296Processing a preemption event sends an \emph{internal} @SIGUSR1@ signal to the registered virtual processor, which is always delivered to that processor.
2297
2298
2299\section{Performance}
2300\label{results}
2301
2302To verify the implementation of the \CFA runtime, a series of microbenchmarks are performed comparing \CFA with other widely used programming languages with concurrency.
2303Table~\ref{t:machine} shows the specifications of the computer used to run the benchmarks, and the versions of the software used in the comparison.
2304
2305\begin{table}
2306\centering
2307\caption{Experiment environment}
2308\label{t:machine}
2309
2310\begin{tabular}{|l|r||l|r|}
2311\hline
2312Architecture            & x86\_64                               & NUMA node(s)  & 8 \\
2313\hline
2314CPU op-mode(s)          & 32-bit, 64-bit                & Model name    & AMD Opteron\texttrademark\ Processor 6380 \\
2315\hline
2316Byte Order                      & Little Endian                 & CPU Freq              & 2.5 GHz \\
2317\hline
2318CPU(s)                          & 64                                    & L1d cache     & 16 KiB \\
2319\hline
2320Thread(s) per core      & 2                                     & L1i cache     & 64 KiB \\
2321\hline
2322Core(s) per socket      & 8                                     & L2 cache              & 2048 KiB \\
2323\hline
2324Socket(s)                       & 4                                     & L3 cache              & 6144 KiB \\
2325\hline
2326\hline
2327Operating system        & Ubuntu 16.04.3 LTS    & Kernel                & Linux 4.4-97-generic \\
2328\hline
2329gcc                                     & 6.3                                   & \CFA                  & 1.0.0 \\
2330\hline
2331Java                            & OpenJDK-9                     & Go                    & 1.9.2 \\
2332\hline
2333\end{tabular}
2334\end{table}
2335
2336All benchmarks are run using the following harness:
2337\begin{cfa}
2338unsigned int N = 10_000_000;
2339#define BENCH( run ) Time before = getTimeNsec(); run; Duration result = (getTimeNsec() - before) / N;
2340\end{cfa}
2341The method used to get time is @clock_gettime( CLOCK_REALTIME )@.
2342Each benchmark is performed @N@ times, where @N@ varies depending on the benchmark;
2343the total time is divided by @N@ to obtain the average time for a benchmark.
2344All omitted tests for other languages are functionally identical to the shown \CFA test.
2345
2346
2347\paragraph{Context-Switching}
2348
2349In procedural programming, the cost of a routine call is important as modularization (refactoring) increases.
2350(In many cases, a compiler inlines routine calls to eliminate this cost.)
2351Similarly, when modularization extends to coroutines/tasks, the time for a context switch becomes a relevant factor.
2352The coroutine context-switch is 2-step using resume/suspend, \ie from resumer to suspender and from suspender to resumer.
2353The thread context switch is 2-step using yield, \ie enter and return from the runtime kernel.
2354Figure~\ref{f:ctx-switch} shows the code for coroutines/threads with all results in Table~\ref{tab:ctx-switch}.
2355The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling.
2356
2357\begin{figure}
2358\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2359
2360\newbox\myboxA
2361\begin{lrbox}{\myboxA}
2362\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2363coroutine C {} c;
2364void main( C & ) { for ( ;; ) { @suspend();@ } }
2365int main() {
2366        BENCH(
2367                for ( size_t i = 0; i < N; i += 1 ) { @resume( c );@ } )
2368        sout | result`ns;
2369}
2370\end{cfa}
2371\end{lrbox}
2372
2373\newbox\myboxB
2374\begin{lrbox}{\myboxB}
2375\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2376
2377
2378int main() {
2379        BENCH(
2380                for ( size_t i = 0; i < N; i += 1 ) { @yield();@ } )
2381        sout | result`ns;
2382}
2383\end{cfa}
2384\end{lrbox}
2385
2386\subfloat[Coroutine]{\usebox\myboxA}
2387\quad
2388\subfloat[Thread]{\usebox\myboxB}
2389\captionof{figure}{\CFA context-switch benchmark}
2390\label{f:ctx-switch}
2391
2392\centering
2393
2394\captionof{table}{Context switch comparison (nanoseconds)}
2395\label{tab:ctx-switch}
2396\bigskip
2397\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
2398\cline{2-4}
2399\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2400\hline
2401Kernel Thread   & 333.5 & 332.96        & 4.1 \\
2402\CFA Coroutine  & 49            & 48.68 & 0.47    \\
2403\CFA Thread             & 105           & 105.57        & 1.37 \\
2404\uC Coroutine   & 44            & 44            & 0 \\
2405\uC Thread              & 100           & 99.29 & 0.96 \\
2406Goroutine               & 145           & 147.25        & 4.15 \\
2407Java Thread             & 373.5 & 375.14        & 8.72 \\
2408\hline
2409\end{tabular}
2410
2411\bigskip
2412\bigskip
2413
2414\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2415\begin{cfa}
2416monitor M { ... } m1/*, m2, m3, m4*/;
2417void __attribute__((noinline)) do_call( M & mutex m/*, m2, m3, m4*/ ) {}
2418int main() {
2419        BENCH( for( size_t i = 0; i < N; i += 1 ) { @do_call( m1/*, m2, m3, m4*/ );@ } )
2420        sout | result`ns;
2421}
2422\end{cfa}
2423\captionof{figure}{\CFA acquire/release mutex benchmark}
2424\label{f:mutex}
2425
2426\centering
2427
2428\captionof{table}{Mutex comparison (nanoseconds)}
2429\label{tab:mutex}
2430\bigskip
2431
2432\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
2433\cline{2-4}
2434\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2435\hline
2436C routine                                       & 2             & 2             & 0    \\
2437FetchAdd + FetchSub                     & 26            & 26            & 0    \\
2438Pthreads Mutex Lock                     & 31            & 31.71 & 0.97 \\
2439\uC @monitor@ member routine            & 31            & 31            & 0    \\
2440\CFA @mutex@ routine, 1 argument        & 46            & 46.68 & 0.93  \\
2441\CFA @mutex@ routine, 2 argument        & 84            & 85.36 & 1.99 \\
2442\CFA @mutex@ routine, 4 argument        & 158           & 161           & 4.22 \\
2443Java synchronized routine               & 27.5  & 29.79 & 2.93  \\
2444\hline
2445\end{tabular}
2446\end{figure}
2447
2448
2449\paragraph{Mutual-Exclusion}
2450
2451Mutual exclusion is measured by entering/leaving a critical section.
2452For monitors, entering and leaving a monitor routine is measured.
2453Figure~\ref{f:mutex} shows the code for \CFA with all results in Table~\ref{tab:mutex}.
2454To 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.
2455Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2456
2457
2458\paragraph{Internal Scheduling}
2459
2460Internal scheduling is measured by waiting on and signalling a condition variable.
2461Figure~\ref{f:int-sched} shows the code for \CFA, with results in Table~\ref{tab:int-sched}.
2462Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2463Java 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.
2464
2465\begin{figure}
2466\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2467\begin{cfa}
2468volatile int go = 0;
2469condition c;
2470monitor M { ... } m;
2471void __attribute__((noinline)) do_call( M & mutex a1 ) { signal( c ); }
2472thread T {};
2473void main( T & this ) {
2474        while ( go == 0 ) { yield(); }  // wait for other thread to start
2475        while ( go == 1 ) { @do_call( m );@ }
2476}
2477int  __attribute__((noinline)) do_wait( M & mutex m ) {
2478        go = 1; // continue other thread
2479        BENCH( for ( size_t i = 0; i < N; i += 1 ) { @wait( c );@ } );
2480        go = 0; // stop other thread
2481        sout | result`ns;
2482}
2483int main() {
2484        T t;
2485        do_wait( m );
2486}
2487\end{cfa}
2488\captionof{figure}{\CFA Internal-scheduling benchmark}
2489\label{f:int-sched}
2490
2491\centering
2492\captionof{table}{Internal-scheduling comparison (nanoseconds)}
2493\label{tab:int-sched}
2494\bigskip
2495
2496\begin{tabular}{|r|*{3}{D{.}{.}{5.2}|}}
2497\cline{2-4}
2498\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2499\hline
2500Pthreads Condition Variable             & 6005  & 5681.43       & 835.45 \\
2501\uC @signal@                                    & 324           & 325.54        & 3,02   \\
2502\CFA @signal@, 1 @monitor@              & 368.5         & 370.61        & 4.77   \\
2503\CFA @signal@, 2 @monitor@              & 467           & 470.5 & 6.79   \\
2504\CFA @signal@, 4 @monitor@              & 700.5         & 702.46        & 7.23  \\
2505Java @notify@                                   & 15471 & 172511        & 5689 \\
2506\hline
2507\end{tabular}
2508\end{figure}
2509
2510
2511\paragraph{External Scheduling}
2512
2513External scheduling is measured by accepting a call using the @waitfor@ statement (@_Accept@ in \uC).
2514Figure~\ref{f:ext-sched} shows the code for \CFA, with results in Table~\ref{tab:ext-sched}.
2515Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2516
2517\begin{figure}
2518\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2519\begin{cfa}
2520volatile int go = 0;
2521monitor M { ... } m;
2522thread T {};
2523void __attribute__((noinline)) do_call( M & mutex ) {}
2524void main( T & ) {
2525        while ( go == 0 ) { yield(); }  // wait for other thread to start
2526        while ( go == 1 ) { @do_call( m );@ }
2527}
2528int __attribute__((noinline)) do_wait( M & mutex m ) {
2529        go = 1; // continue other thread
2530        BENCH( for ( size_t i = 0; i < N; i += 1 ) { @waitfor( do_call, m );@ } )
2531        go = 0; // stop other thread
2532        sout | result`ns;
2533}
2534int main() {
2535        T t;
2536        do_wait( m );
2537}
2538\end{cfa}
2539\captionof{figure}{\CFA external-scheduling benchmark}
2540\label{f:ext-sched}
2541
2542\centering
2543
2544\captionof{table}{External-scheduling comparison (nanoseconds)}
2545\label{tab:ext-sched}
2546\bigskip
2547\begin{tabular}{|r|*{3}{D{.}{.}{3.2}|}}
2548\cline{2-4}
2549\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} &\multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2550\hline
2551\uC @_Accept@                           & 358           & 359.11        & 2.53  \\
2552\CFA @waitfor@, 1 @monitor@     & 359           & 360.93        & 4.07  \\
2553\CFA @waitfor@, 2 @monitor@     & 450           & 449.39        & 6.62  \\
2554\CFA @waitfor@, 4 @monitor@     & 652           & 655.64        & 7.73 \\
2555\hline
2556\end{tabular}
2557
2558\bigskip
2559\medskip
2560
2561\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2562\begin{cfa}
2563thread MyThread {};
2564void main( MyThread & ) {}
2565int main() {
2566        BENCH( for ( size_t i = 0; i < N; i += 1 ) { @MyThread m;@ } )
2567        sout | result`ns;
2568}
2569\end{cfa}
2570\captionof{figure}{\CFA object-creation benchmark}
2571\label{f:creation}
2572
2573\centering
2574
2575\captionof{table}{Creation comparison (nanoseconds)}
2576\label{tab:creation}
2577\bigskip
2578
2579\begin{tabular}{|r|*{3}{D{.}{.}{5.2}|}}
2580\cline{2-4}
2581\multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Median} & \multicolumn{1}{c|}{Average} & \multicolumn{1}{c|}{Std Dev} \\
2582\hline
2583Pthreads                                & 28091         & 28073.39      & 163.1  \\
2584\CFA Coroutine Lazy             & 6                     & 6.07          & 0.26   \\
2585\CFA Coroutine Eager    & 520           & 520.61        & 2.04   \\
2586\CFA Thread                             & 2032  & 2016.29       & 112.07  \\
2587\uC Coroutine                   & 106           & 107.36        & 1.47   \\
2588\uC Thread                              & 536.5 & 537.07        & 4.64   \\
2589Goroutine                               & 3103  & 3086.29       & 90.25  \\
2590Java Thread                             & 103416.5      & 103732.29     & 1137 \\
2591\hline
2592\end{tabular}
2593\end{figure}
2594
2595
2596\paragraph{Object Creation}
2597
2598Object creation is measured by creating/deleting the specific kind of concurrent object.
2599Figure~\ref{f:creation} shows the code for \CFA, with results in Table~\ref{tab:creation}.
2600The 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.
2601
2602
2603\section{Conclusion}
2604
2605This paper demonstrates a concurrency API that is simple, efficient, and able to build higher-level concurrency features.
2606The 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.
2607The M:N model is judged to be efficient and provide greater flexibility than a 1:1 threading model.
2608High-level objects (monitor/task) are the core mechanism for mutual exclusion and synchronization.
2609A novel aspect is allowing multiple mutex-objects to be accessed simultaneously reducing the potential for deadlock for this complex scenario.
2610These concepts and the entire \CFA runtime-system are written in the \CFA language, demonstrating the expressiveness of the \CFA language.
2611Performance 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.
2612C 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.
2613
2614
2615\section{Future Work}
2616
2617While concurrency in \CFA has a strong start, development is still underway and there are missing features.
2618
2619\paragraph{Flexible Scheduling}
2620\label{futur:sched}
2621
2622An important part of concurrency is scheduling.
2623Different scheduling algorithms can affect performance (both in terms of average and variation).
2624However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
2625One solution is to offer various tweaking options, allowing the scheduler to be adjusted to the requirements of the workload.
2626However, to be truly flexible, a pluggable scheduler is necessary.
2627Currently, 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.
2628
2629\paragraph{Non-Blocking I/O}
2630\label{futur:nbio}
2631
2632Many modern workloads are not bound by computation but IO operations, a common case being web servers and XaaS~\cite{XaaS} (anything as a service).
2633These types of workloads require significant engineering to amortizing costs of blocking IO-operations.
2634At 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.
2635Current 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.
2636However, these solutions lead to code that is hard to create, read and maintain.
2637A 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.
2638A non-blocking I/O library is currently under development for \CFA.
2639
2640\paragraph{Other Concurrency Tools}
2641\label{futur:tools}
2642
2643While monitors offer flexible and powerful concurrency for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
2644Examples of such tools can include futures and promises~\cite{promises}, executors and actors.
2645These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
2646As well, new \CFA extensions should make it possible to create a uniform interface for virtually all mutual exclusion, including monitors and low-level locks.
2647
2648\paragraph{Implicit Threading}
2649\label{futur:implcit}
2650
2651Basic 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.
2652This type of concurrency can be achieved both at the language level and at the library level.
2653The canonical example of implicit concurrency is concurrent nested @for@ loops, which are amenable to divide and conquer algorithms~\cite{uC++book}.
2654The \CFA language features should make it possible to develop a reasonable number of implicit concurrency mechanism to solve basic HPC data-concurrency problems.
2655However, implicit concurrency is a restrictive solution with significant limitations, so it can never replace explicit concurrent programming.
2656
2657
2658\section{Acknowledgements}
2659
2660The authors would like to recognize the design assistance of Aaron Moss, Rob Schluntz and Andrew Beach on the features described in this paper.
2661Funding 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.
2662
2663{%
2664\fontsize{9bp}{12bp}\selectfont%
2665\bibliography{pl,local}
2666}%
2667
2668\end{document}
2669
2670% Local Variables: %
2671% tab-width: 4 %
2672% fill-column: 120 %
2673% compile-command: "make" %
2674% End: %
Note: See TracBrowser for help on using the repository browser.