source: doc/papers/concurrency/Paper.tex @ 41efd33

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 41efd33 was b067d9b, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

  • Property mode set to 100644
File size: 158.1 KB
Line 
1\documentclass[AMA,STIX1COL]{WileyNJD-v2}
2
3\articletype{RESEARCH ARTICLE}%
4
5% Referees
6% Doug Lea, dl@cs.oswego.edu, SUNY Oswego
7% Herb Sutter, hsutter@microsoft.com, Microsoft Corp
8% Gor Nishanov, gorn@microsoft.com, Microsoft Corp
9% James Noble, kjx@ecs.vuw.ac.nz, Victoria University of Wellington, School of Engineering and Computer Science
10
11\received{XXXXX}
12\revised{XXXXX}
13\accepted{XXXXX}
14
15\raggedbottom
16
17%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
18
19% Latex packages used in the document.
20
21\usepackage{epic,eepic}
22\usepackage{xspace}
23\usepackage{enumitem}
24\usepackage{comment}
25\usepackage{upquote}                                            % switch curled `'" to straight
26\usepackage{listings}                                           % format program code
27\usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig}
28\renewcommand{\thesubfigure}{(\Alph{subfigure})}
29\captionsetup{justification=raggedright,singlelinecheck=false}
30\usepackage{dcolumn}                                            % align decimal points in tables
31\usepackage{capt-of}
32\setlength{\multicolsep}{6.0pt plus 2.0pt minus 1.5pt}
33
34\hypersetup{breaklinks=true}
35\definecolor{OliveGreen}{cmyk}{0.64 0 0.95 0.40}
36\definecolor{Mahogany}{cmyk}{0 0.85 0.87 0.35}
37\definecolor{Plum}{cmyk}{0.50 1 0 0}
38
39\usepackage[pagewise]{lineno}
40\renewcommand{\linenumberfont}{\scriptsize\sffamily}
41
42\renewcommand{\topfraction}{0.8}                        % float must be greater than X of the page before it is forced onto its own page
43\renewcommand{\bottomfraction}{0.8}                     % float must be greater than X of the page before it is forced onto its own page
44\renewcommand{\floatpagefraction}{0.8}          % float must be greater than X of the page before it is forced onto its own page
45\renewcommand{\textfraction}{0.0}                       % the entire page maybe devoted to floats with no text on the page at all
46
47\lefthyphenmin=3                                                        % hyphen only after 4 characters
48\righthyphenmin=3
49
50%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
51
52% Names used in the document.
53
54\newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
55\newcommand{\CFA}{\protect\CFAIcon}             % safe for section/caption
56\newcommand{\CFL}{\textrm{Cforall}\xspace}      % Cforall symbolic name
57\newcommand{\Celeven}{\textrm{C11}\xspace}      % C11 symbolic name
58\newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
59\newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
60\newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
61\newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
62\newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name
63\newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name
64
65%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
66
67\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
68\newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}}
69\newcommand{\uC}{$\mu$\CC}
70\newcommand{\TODO}[1]{{\Textbf{#1}}}
71
72%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
73
74% Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
75% removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
76% AFTER HYPERREF.
77%\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}
78\renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}
79
80\renewcommand*{\thefootnote}{\Alph{footnote}} % hack because fnsymbol does not work
81%\renewcommand*{\thefootnote}{\fnsymbol{footnote}}
82
83\makeatletter
84% parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
85% use rather than use \parident directly.
86\newlength{\parindentlnth}
87\setlength{\parindentlnth}{\parindent}
88
89\newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{\lst@basicstyle{#1}}}}
90\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
91\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
92
93\newlength{\gcolumnposn}                                        % temporary hack because lstlisting does not handle tabs correctly
94\newlength{\columnposn}
95\setlength{\gcolumnposn}{3.5in}
96\setlength{\columnposn}{\gcolumnposn}
97
98\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}}}}
99\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
100
101% Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
102% The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
103% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
104\newcommand{\newtermFontInline}{\emph}
105\newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
106\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
107\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
108
109% Latin abbreviation
110\newcommand{\abbrevFont}{\textit}                       % set empty for no italics
111\@ifundefined{eg}{
112\newcommand{\EG}{\abbrevFont{e}\abbrevFont{g}}
113\newcommand*{\eg}{%
114        \@ifnextchar{,}{\EG}%
115                {\@ifnextchar{:}{\EG}%
116                        {\EG,\xspace}}%
117}}{}%
118\@ifundefined{ie}{
119\newcommand{\IE}{\abbrevFont{i}\abbrevFont{e}}
120\newcommand*{\ie}{%
121        \@ifnextchar{,}{\IE}%
122                {\@ifnextchar{:}{\IE}%
123                        {\IE,\xspace}}%
124}}{}%
125\@ifundefined{etc}{
126\newcommand{\ETC}{\abbrevFont{etc}}
127\newcommand*{\etc}{%
128        \@ifnextchar{.}{\ETC}%
129        {\ETC.\xspace}%
130}}{}%
131\@ifundefined{etal}{
132\newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}}
133\newcommand*{\etal}{%
134        \@ifnextchar{.}{\protect\ETAL}%
135                {\protect\ETAL.\xspace}%
136}}{}%
137\@ifundefined{viz}{
138\newcommand{\VIZ}{\abbrevFont{viz}}
139\newcommand*{\viz}{%
140        \@ifnextchar{.}{\VIZ}%
141                {\VIZ.\xspace}%
142}}{}%
143\makeatother
144
145\newenvironment{cquote}
146               {\list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
147                \item\relax}
148               {\endlist}
149
150%\newenvironment{cquote}{%
151%\list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
152%\item\relax%
153%}{%
154%\endlist%
155%}% cquote
156
157% CFA programming language, based on ANSI C (with some gcc additions)
158\lstdefinelanguage{CFA}[ANSI]{C}{
159        morekeywords={
160                _Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, __attribute, __attribute__,
161                auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__, __const, __const__,
162                coroutine, disable, dtype, enable, exception, __extension__, fallthrough, fallthru, finally,
163                __float80, float80, __float128, float128, forall, ftype, generator, _Generic, _Imaginary, __imag, __imag__,
164                inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
165                otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread,
166                _Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
167                virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
168        moredirectives={defined,include_next},
169        % replace/adjust listing characters that look bad in sanserif
170        literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
171                {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
172                {<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
173                {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex{\textrm{\textgreater}}}2,
174}
175
176\lstset{
177language=CFA,
178columns=fullflexible,
179basicstyle=\linespread{0.9}\sf,                                                 % reduce line spacing and use sanserif font
180stringstyle=\tt,                                                                                % use typewriter font
181tabsize=5,                                                                                              % N space tabbing
182xleftmargin=\parindentlnth,                                                             % indent code to paragraph indentation
183%mathescape=true,                                                                               % LaTeX math escape in CFA code $...$
184escapechar=\$,                                                                                  % LaTeX escape in CFA code
185keepspaces=true,                                                                                %
186showstringspaces=false,                                                                 % do not show spaces with cup
187showlines=true,                                                                                 % show blank lines at end of code
188aboveskip=4pt,                                                                                  % spacing above/below code block
189belowskip=3pt,
190moredelim=**[is][\color{red}]{`}{`},
191}% lstset
192
193% uC++ programming language, based on ANSI C++
194\lstdefinelanguage{uC++}[ANSI]{C++}{
195        morekeywords={
196                _Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _CatchResume, _Cormonitor, _Coroutine, _Disable,
197                _Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
198                _Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
199}
200\lstdefinelanguage{Golang}{
201        morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
202        morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
203                bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
204        morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
205        morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
206        morekeywords=[5]{Println,Printf,Error,},
207        sensitive=true,
208        morecomment=[l]{//},
209        morecomment=[s]{/*}{*/},
210        morestring=[b]',
211        morestring=[b]",
212        morestring=[s]{`}{`},
213}
214
215% Go programming language: https://github.com/julienc91/listings-golang/blob/master/listings-golang.sty
216\lstdefinelanguage{Golang}{
217        morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
218        morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
219                bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
220        morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
221        morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
222        morekeywords=[5]{Println,Printf,Error,},
223        sensitive=true,
224        morecomment=[l]{//},
225        morecomment=[s]{/*}{*/},
226        morestring=[b]',
227        morestring=[b]",
228        morestring=[s]{`}{`},
229        % replace/adjust listing characters that look bad in sanserif
230        literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
231                {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
232                {<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
233                {<-}{\makebox[2ex][c]{\textrm{\textless}\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}}2,
234}
235
236\lstnewenvironment{cfa}[1][]
237{\lstset{#1}}
238{}
239\lstnewenvironment{C++}[1][]                            % use C++ style
240{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
241{}
242\lstnewenvironment{uC++}[1][]
243{\lstset{#1}}
244{}
245\lstnewenvironment{Go}[1][]
246{\lstset{language=Golang,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
247{}
248\lstnewenvironment{python}[1][]
249{\lstset{language=python,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
250{}
251
252% inline code @...@
253\lstMakeShortInline@%
254
255\newcommand{\commenttd}[1]{{\color{red}{Thierry : #1}}}
256
257\let\OLDthebibliography\thebibliography
258\renewcommand\thebibliography[1]{
259  \OLDthebibliography{#1}
260  \setlength{\parskip}{0pt}
261  \setlength{\itemsep}{4pt plus 0.3ex}
262}
263
264\newbox\myboxA
265\newbox\myboxB
266\newbox\myboxC
267\newbox\myboxD
268
269\title{\texorpdfstring{Advanced Control-flow and Concurrency in \protect\CFA}{Advanced Control-flow in Cforall}}
270
271\author[1]{Thierry Delisle}
272\author[1]{Peter A. Buhr*}
273\authormark{DELISLE \textsc{et al.}}
274
275\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}
276
277\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}}
278
279% \fundingInfo{Natural Sciences and Engineering Research Council of Canada}
280
281\abstract[Summary]{
282\CFA is a polymorphic, non-object-oriented, concurrent, backwards-compatible extension of the C programming language.
283This paper discusses the design philosophy and implementation of its advanced control-flow and concurrent/parallel features, along with the supporting runtime written in \CFA.
284These 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 pthreads.
285\CFA introduces modern language-level control-flow mechanisms, like generators, coroutines, user-level threading, and monitors for mutual exclusion and synchronization.
286% Library extension for executors, futures, and actors are built on these basic mechanisms.
287The runtime provides significant programmer simplification and safety by eliminating spurious wakeup and monitor barging.
288The runtime also ensures multiple monitors can be safely acquired \emph{simultaneously} (deadlock free), and this feature is fully integrated with all monitor synchronization mechanisms.
289All control-flow features integrate with the \CFA polymorphic type-system and exception handling, while respecting the expectations and style of C programmers.
290Experimental results show comparable performance of the new features with similar mechanisms in other concurrent programming languages.
291}%
292
293\keywords{generator, coroutine, concurrency, parallelism, thread, monitor, runtime, C, \CFA (Cforall)}
294
295
296\begin{document}
297\linenumbers                                            % comment out to turn off line numbering
298
299\maketitle
300
301
302\section{Introduction}
303
304This paper discusses the design philosophy and implementation of advanced language-level control-flow and concurrent/parallel features in \CFA~\cite{Moss18,Cforall} and its runtime, which is written entirely in \CFA.
305\CFA is a modern, polymorphic, non-object-oriented\footnote{
306\CFA has features often associated with object-oriented programming languages, such as constructors, destructors, virtuals and simple inheritance.
307However, 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.},
308backwards-compatible extension of the C programming language.
309In many ways, \CFA is to C as Scala~\cite{Scala} is to Java, providing a \emph{research vehicle} for new typing and control-flow capabilities on top of a highly popular programming language allowing immediate dissemination.
310Within the \CFA framework, new control-flow features are created from scratch because ISO \Celeven defines only a subset of the \CFA extensions, where the overlapping features are concurrency~\cite[\S~7.26]{C11}.
311However, \Celeven concurrency is largely wrappers for a subset of the pthreads library~\cite{Butenhof97,Pthreads}, and \Celeven and pthreads concurrency is simple, based on thread fork/join in a function and mutex/condition locks, which is low-level and error-prone;
312no high-level language concurrency features are defined.
313Interestingly, almost a decade after publication of the \Celeven standard, neither gcc-8, clang-9 nor msvc-19 (most recent versions) support the \Celeven include @threads.h@, indicating little interest in the C11 concurrency approach (possibly because the effort to add concurrency to \CC).
314Finally, 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}.
315
316In contrast, there has been a renewed interest during the past decade in user-level (M:N, green) threading in old and new programming languages.
317As multi-core hardware became available in the 1980/90s, both user and kernel threading were examined.
318Kernel 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}.
319Libraries like pthreads were developed for C, and the Solaris operating-system switched from user (JDK 1.1~\cite{JDK1.1}) to kernel threads.
320As a result, languages like Java, 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.
321From 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,Marcel}, including putting green threads back into Java~\cite{Quasar}.
322The main argument for user-level threading is that it is lighter weight than kernel threading (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 medium work units to facilitate load balancing by the runtime~\cite{Verch12}.
323As well, user-threading facilitates a simpler concurrency approach using thread objects that leverage sequential patterns versus events with call-backs~\cite{Adya02,vonBehren03}.
324Finally, performant user-threading implementations (both time and space) meet or exceed direct kernel-threading implementations, while achieving the programming advantages of high concurrency levels and safety.
325
326A 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, \ie some language features are unsafe in the presence of aggressive sequential optimizations~\cite{Buhr95a,Boehm05}.
327The 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.
328One solution is low-level qualifiers and functions (\eg @volatile@ and atomics) allowing \emph{programmers} to explicitly write safe (race-free~\cite{Boehm12}) programs.
329A safer solution is high-level language constructs so the \emph{compiler} knows the optimization boundaries, and hence, provides implicit safety.
330This problem is best known with respect to concurrency, but applies to other complex control-flow, like exceptions\footnote{
331\CFA exception handling will be presented in a separate paper.
332The key feature that dovetails with this paper is nonlocal 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++}
333} and coroutines.
334Finally, language solutions allow matching constructs with language paradigm, \ie imperative and functional languages often have different presentations of the same concept to fit their programming model.
335
336Finally, it is important for a language to provide safety over performance \emph{as the default}, allowing careful reduction of safety for performance when necessary.
337Two concurrency violations of this philosophy are \emph{spurious wakeup} (random wakeup~\cite[\S~8]{Buhr05a}) and \emph{barging}\footnote{
338The notion of competitive succession instead of direct handoff, \ie a lock owner releases the lock and an arriving thread acquires it ahead of preexisting waiter threads.
339} (signals-as-hints~\cite[\S~8]{Buhr05a}), where one is a consequence of the other, \ie once there is spurious wakeup, signals-as-hints follow.
340However, spurious wakeup is \emph{not} a foundational concurrency property~\cite[\S~8]{Buhr05a}, it is a performance design choice.
341Similarly, signals-as-hints are often a performance decision.
342We argue removing spurious wakeup and signals-as-hints make concurrent programming significantly safer because it removes local non-determinism and matches with programmer expectation.
343(Author experience teaching concurrency is that students are highly confused by these semantics.)
344Clawing back performance, when local non-determinism is unimportant, should be an option not the default.
345
346\begin{comment}
347Most 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.
348As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten.
349While \CC, like \CFA, takes an evolutionary approach to extend C, \CC's constantly growing complex and interdependent features-set (\eg objects, inheritance, templates, etc.) mean idiomatic \CC code is difficult to use from C, and C programmers must expend significant effort learning \CC.
350Hence, rewriting and retraining costs for these languages, even \CC, are prohibitive for companies with a large C software-base.
351\CFA with its orthogonal feature-set, its high-performance runtime, and direct access to all existing C libraries circumvents these problems.
352\end{comment}
353
354\CFA embraces user-level threading, language extensions for advanced control-flow, and safety as the default.
355We present comparative examples so the reader can judge if the \CFA control-flow extensions are better and safer than those in other concurrent, imperative programming languages, and perform experiments to show the \CFA runtime is competitive with other similar mechanisms.
356The main contributions of this work are:
357\begin{itemize}[topsep=3pt,itemsep=1pt]
358\item
359language-level generators, coroutines and user-level threading, which respect the expectations of C programmers.
360\item
361monitor synchronization without barging, and the ability to safely acquiring multiple monitors \emph{simultaneously} (deadlock free), while seamlessly integrating these capabilities with all monitor synchronization mechanisms.
362\item
363providing statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features.
364% \item
365% library extensions for executors, futures, and actors built on the basic mechanisms.
366\item
367a runtime system with no spurious wakeup.
368\item
369a dynamic partitioning mechanism to segregate the execution environment for specialized requirements.
370% \item
371% a non-blocking I/O library
372\item
373experimental results showing comparable performance of the new features with similar mechanisms in other programming languages.
374\end{itemize}
375
376Section~\ref{s:StatefulFunction} begins advanced control by introducing sequential functions that retain data and execution state between calls, which produces constructs @generator@ and @coroutine@.
377Section~\ref{s:Concurrency} begins concurrency, or how to create (fork) and destroy (join) a thread, which produces the @thread@ construct.
378Section~\ref{s:MutualExclusionSynchronization} discusses the two mechanisms to restricted nondeterminism when controlling shared access to resources (mutual exclusion) and timing relationships among threads (synchronization).
379Section~\ref{s:Monitor} shows how both mutual exclusion and synchronization are safely embedded in the @monitor@ and @thread@ constructs.
380Section~\ref{s:CFARuntimeStructure} describes the large-scale mechanism to structure (cluster) threads and virtual processors (kernel threads).
381Section~\ref{s:Performance} uses a series of microbenchmarks to compare \CFA threading with pthreads, Java OpenJDK-9, Go 1.12.6 and \uC 7.0.0.
382
383
384\section{Stateful Function}
385\label{s:StatefulFunction}
386
387The stateful function is an old idea~\cite{Conway63,Marlin80} that is new again~\cite{C++20Coroutine19}, where execution is temporarily suspended and later resumed, \eg plugin, device driver, finite-state machine.
388Hence, a stateful function may not end when it returns to its caller, allowing it to be restarted with the data and execution location present at the point of suspension.
389This capability is accomplished by retaining a data/execution \emph{closure} between invocations.
390If the closure is fixed size, we call it a \emph{generator} (or \emph{stackless}), and its control flow is restricted, \eg suspending outside the generator is prohibited.
391If the closure is variable size, we call it a \emph{coroutine} (or \emph{stackful}), and as the names implies, often implemented with a separate stack with no programming restrictions.
392Hence, refactoring a stackless coroutine may require changing it to stackful.
393A foundational property of all \emph{stateful functions} is that resume/suspend \emph{do not} cause incremental stack growth, \ie resume/suspend operations are remembered through the closure not the stack.
394As well, activating a stateful function is \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles).
395A fixed closure activated by modified call/return is faster than a variable closure activated by context switching.
396Additionally, any storage management for the closure (especially in unmanaged languages, \ie no garbage collection) must also be factored into design and performance.
397Therefore, selecting between stackless and stackful semantics is a tradeoff between programming requirements and performance, where stackless is faster and stackful is more general.
398Note, creation cost is amortized across usage, so activation cost is usually the dominant factor.
399
400\begin{figure}
401\centering
402\begin{lrbox}{\myboxA}
403\begin{cfa}[aboveskip=0pt,belowskip=0pt]
404typedef struct {
405        int fn1, fn;
406} Fib;
407#define FibCtor { 1, 0 }
408int fib( Fib * f ) {
409
410
411
412        int fn = f->fn; f->fn = f->fn1;
413                f->fn1 = f->fn + fn;
414        return fn;
415
416}
417int main() {
418        Fib f1 = FibCtor, f2 = FibCtor;
419        for ( int i = 0; i < 10; i += 1 )
420                printf( "%d %d\n",
421                           fib( &f1 ), fib( &f2 ) );
422}
423\end{cfa}
424\end{lrbox}
425
426\begin{lrbox}{\myboxB}
427\begin{cfa}[aboveskip=0pt,belowskip=0pt]
428`generator` Fib {
429        int fn1, fn;
430};
431
432void `main(Fib & fib)` with(fib) {
433
434        [fn1, fn] = [1, 0];
435        for () {
436                `suspend;`
437                [fn1, fn] = [fn, fn + fn1];
438
439        }
440}
441int main() {
442        Fib f1, f2;
443        for ( 10 )
444                sout | `resume( f1 )`.fn
445                         | `resume( f2 )`.fn;
446}
447\end{cfa}
448\end{lrbox}
449
450\begin{lrbox}{\myboxC}
451\begin{cfa}[aboveskip=0pt,belowskip=0pt]
452typedef struct {
453        int fn1, fn;  void * `next`;
454} Fib;
455#define FibCtor { 1, 0, NULL }
456Fib * comain( Fib * f ) {
457        if ( f->next ) goto *f->next;
458        f->next = &&s1;
459        for ( ;; ) {
460                return f;
461          s1:; int fn = f->fn + f->fn1;
462                        f->fn1 = f->fn; f->fn = fn;
463        }
464}
465int main() {
466        Fib f1 = FibCtor, f2 = FibCtor;
467        for ( int i = 0; i < 10; i += 1 )
468                printf("%d %d\n",comain(&f1)->fn,
469                                 comain(&f2)->fn);
470}
471\end{cfa}
472\end{lrbox}
473
474\subfloat[C asymmetric generator]{\label{f:CFibonacci}\usebox\myboxA}
475\hspace{3pt}
476\vrule
477\hspace{3pt}
478\subfloat[\CFA asymmetric generator]{\label{f:CFAFibonacciGen}\usebox\myboxB}
479\hspace{3pt}
480\vrule
481\hspace{3pt}
482\subfloat[C generator implementation]{\label{f:CFibonacciSim}\usebox\myboxC}
483\caption{Fibonacci (output) asymmetric generator}
484\label{f:FibonacciAsymmetricGenerator}
485
486\bigskip
487
488\begin{lrbox}{\myboxA}
489\begin{cfa}[aboveskip=0pt,belowskip=0pt]
490`generator Fmt` {
491        char ch;
492        int g, b;
493};
494void ?{}( Fmt & fmt ) { `resume(fmt);` } // constructor
495void ^?{}( Fmt & f ) with(f) { $\C[1.75in]{// destructor}$
496        if ( g != 0 || b != 0 ) sout | nl; }
497void `main( Fmt & f )` with(f) {
498        for () { $\C{// until destructor call}$
499                for ( ; g < 5; g += 1 ) { $\C{// groups}$
500                        for ( ; b < 4; b += 1 ) { $\C{// blocks}$
501                                `suspend;` $\C{// wait for character}$
502                                while ( ch == '\n' ) `suspend;` // ignore
503                                sout | ch;                                              // newline
504                        } sout | " ";  // block spacer
505                } sout | nl; // group newline
506        }
507}
508int main() {
509        Fmt fmt; $\C{// fmt constructor called}$
510        for () {
511                sin | fmt.ch; $\C{// read into generator}$
512          if ( eof( sin ) ) break;
513                `resume( fmt );`
514        }
515
516} $\C{// fmt destructor called}\CRT$
517\end{cfa}
518\end{lrbox}
519
520\begin{lrbox}{\myboxB}
521\begin{cfa}[aboveskip=0pt,belowskip=0pt]
522typedef struct {
523        void * next;
524        char ch;
525        int g, b;
526} Fmt;
527void comain( Fmt * f ) {
528        if ( f->next ) goto *f->next;
529        f->next = &&s1;
530        for ( ;; ) {
531                for ( f->g = 0; f->g < 5; f->g += 1 ) {
532                        for ( f->b = 0; f->b < 4; f->b += 1 ) {
533                                return;
534                          s1:;  while ( f->ch == '\n' ) return;
535                                printf( "%c", f->ch );
536                        } printf( " " );
537                } printf( "\n" );
538        }
539}
540int main() {
541        Fmt fmt = { NULL };  comain( &fmt ); // prime
542        for ( ;; ) {
543                scanf( "%c", &fmt.ch );
544          if ( feof( stdin ) ) break;
545                comain( &fmt );
546        }
547        if ( fmt.g != 0 || fmt.b != 0 ) printf( "\n" );
548}
549\end{cfa}
550\end{lrbox}
551
552\subfloat[\CFA asymmetric generator]{\label{f:CFAFormatGen}\usebox\myboxA}
553\hspace{3pt}
554\vrule
555\hspace{3pt}
556\subfloat[C generator simulation]{\label{f:CFormatSim}\usebox\myboxB}
557\hspace{3pt}
558\caption{Formatter (input) asymmetric generator}
559\label{f:FormatterAsymmetricGenerator}
560\end{figure}
561
562Stateful functions appear as generators, coroutines, and threads, where presentations are based on function objects or pointers~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
563For example, Python presents generators as a function object:
564\begin{python}
565def Gen():
566        ... `yield val` ...
567gen = Gen()
568for i in range( 10 ):
569        print( next( gen ) )
570\end{python}
571Boost presents coroutines in terms of four functor object-types:
572\begin{cfa}
573asymmetric_coroutine<>::pull_type
574asymmetric_coroutine<>::push_type
575symmetric_coroutine<>::call_type
576symmetric_coroutine<>::yield_type
577\end{cfa}
578and many languages present threading using function pointers, @pthreads@~\cite{Butenhof97}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}, \eg pthreads:
579\begin{cfa}
580void * rtn( void * arg ) { ... }
581int i = 3, rc;
582pthread_t t; $\C{// thread id}$
583`rc = pthread_create( &t, rtn, (void *)i );` $\C{// create and initialized task, type-unsafe input parameter}$
584\end{cfa}
585% void mycor( pthread_t cid, void * arg ) {
586%       int * value = (int *)arg;                               $\C{// type unsafe, pointer-size only}$
587%       // thread body
588% }
589% int main() {
590%       int input = 0, output;
591%       coroutine_t cid = coroutine_create( &mycor, (void *)&input ); $\C{// type unsafe, pointer-size only}$
592%       coroutine_resume( cid, (void *)input, (void **)&output ); $\C{// type unsafe, pointer-size only}$
593% }
594\CFA's preferred presentation model for generators/coroutines/threads is a hybrid of objects and functions, with an object-oriented flavour.
595Essentially, the generator/coroutine/thread function is semantically coupled with a generator/coroutine/thread custom type.
596The custom type solves several issues, while accessing the underlying mechanisms used by the custom types is still allowed.
597
598
599\subsection{Generator}
600
601Stackless generators have the potential to be very small and fast, \ie as small and fast as function call/return for both creation and execution.
602The \CFA goal is to achieve this performance target, possibly at the cost of some semantic complexity.
603A series of different kinds of generators and their implementation demonstrate how this goal is accomplished.
604
605Figure~\ref{f:FibonacciAsymmetricGenerator} shows an unbounded asymmetric generator for an infinite sequence of Fibonacci numbers written in C and \CFA, with a simple C implementation for the \CFA version.
606This generator is an \emph{output generator}, producing a new result on each resumption.
607To compute Fibonacci, the previous two values in the sequence are retained to generate the next value, \ie @fn1@ and @fn@, plus the execution location where control restarts when the generator is resumed, \ie top or middle.
608An additional requirement is the ability to create an arbitrary number of generators (of any kind), \ie retaining one state in global variables is insufficient;
609hence, state is retained in a closure between calls.
610Figure~\ref{f:CFibonacci} shows the C approach of manually creating the closure in structure @Fib@, and multiple instances of this closure provide multiple Fibonacci generators.
611The C version only has the middle execution state because the top execution state is declaration initialization.
612Figure~\ref{f:CFAFibonacciGen} shows the \CFA approach, which also has a manual closure, but replaces the structure with a custom \CFA @generator@ type.
613This generator type is then connected to a function that \emph{must be named \lstinline|main|},\footnote{
614The name \lstinline|main| has special meaning in C, specifically the function where a program starts execution.
615Hence, overloading this name for other starting points (generator/coroutine/thread) is a logical extension.}
616called a \emph{generator main},which takes as its only parameter a reference to the generator type.
617The generator main contains @suspend@ statements that suspend execution without ending the generator versus @return@.
618For the Fibonacci generator-main,\footnote{
619The \CFA \lstinline|with| opens an aggregate scope making its fields directly accessible, like Pascal \lstinline|with|, but using parallel semantics.
620Multiple aggregates may be opened.}
621the top initialization state appears at the start and the middle execution state is denoted by statement @suspend@.
622Any local variables in @main@ \emph{are not retained} between calls;
623hence local variables are only for temporary computations \emph{between} suspends.
624All retained state \emph{must} appear in the generator's type.
625As well, generator code containing a @suspend@ cannot be refactored into a helper function called by the generator, because @suspend@ is implemented via @return@, so a return from the helper function goes back to the current generator not the resumer.
626The generator is started by calling function @resume@ with a generator instance, which begins execution at the top of the generator main, and subsequent @resume@ calls restart the generator at its point of last suspension.
627Resuming an ended (returned) generator is undefined.
628Function @resume@ returns its argument generator so it can be cascaded in an expression, in this case to print the next Fibonacci value @fn@ computed in the generator instance.
629Figure~\ref{f:CFibonacciSim} shows the C implementation of the \CFA generator only needs one additional field, @next@, to handle retention of execution state.
630The computed @goto@ at the start of the generator main, which branches after the previous suspend, adds very little cost to the resume call.
631Finally, an explicit generator type provides both design and performance benefits, such as multiple type-safe interface functions taking and returning arbitrary types.\footnote{
632The \CFA operator syntax uses \lstinline|?| to denote operands, which allows precise definitions for pre, post, and infix operators, \eg \lstinline|++?|, \lstinline|?++|, and \lstinline|?+?|, in addition \lstinline|?\{\}| denotes a constructor, as in \lstinline|foo `f` = `\{`...`\}`|, \lstinline|^?\{\}| denotes a destructor, and \lstinline|?()| is \CC function call \lstinline|operator()|.
633}%
634\begin{cfa}
635int ?()( Fib & fib ) { return `resume( fib )`.fn; } $\C[3.9in]{// function-call interface}$
636int ?()( Fib & fib, int N ) { for ( N - 1 ) `fib()`; return `fib()`; } $\C{// use function-call interface to skip N values}$
637double ?()( Fib & fib ) { return (int)`fib()` / 3.14159; } $\C{// different return type, cast prevents recursive call}\CRT$
638sout | (int)f1() | (double)f1() | f2( 2 ); // alternative interface, cast selects call based on return type, step 2 values
639\end{cfa}
640Now, the generator can be a separately compiled opaque-type only accessed through its interface functions.
641For contrast, Figure~\ref{f:PythonFibonacci} shows the equivalent Python Fibonacci generator, which does not use a generator type, and hence only has a single interface, but an implicit closure.
642
643Having to manually create the generator closure by moving local-state variables into the generator type is an additional programmer burden.
644(This restriction is removed by the coroutine in Section~\ref{s:Coroutine}.)
645This requirement follows from the generality of variable-size local-state, \eg local state with a variable-length array requires dynamic allocation because the array size is unknown at compile time.
646However, dynamic allocation significantly increases the cost of generator creation/destruction and is a showstopper for embedded real-time programming.
647But more importantly, the size of the generator type is tied to the local state in the generator main, which precludes separate compilation of the generator main, \ie a generator must be inlined or local state must be dynamically allocated.
648With respect to safety, we believe static analysis can discriminate local state from temporary variables in a generator, \ie variable usage spanning @suspend@, and generate a compile-time error.
649Finally, our current experience is that most generator problems have simple data state, including local state, but complex execution state, so the burden of creating the generator type is small.
650As well, C programmers are not afraid of this kind of semantic programming requirement, if it results in very small, fast generators.
651
652Figure~\ref{f:CFAFormatGen} shows an asymmetric \newterm{input generator}, @Fmt@, for restructuring text into groups of characters of fixed-size blocks, \ie the input on the left is reformatted into the output on the right, where newlines are ignored.
653\begin{center}
654\tt
655\begin{tabular}{@{}l|l@{}}
656\multicolumn{1}{c|}{\textbf{\textrm{input}}} & \multicolumn{1}{c}{\textbf{\textrm{output}}} \\
657\begin{tabular}[t]{@{}ll@{}}
658abcdefghijklmnopqrstuvwxyz \\
659abcdefghijklmnopqrstuvwxyz
660\end{tabular}
661&
662\begin{tabular}[t]{@{}lllll@{}}
663abcd    & efgh  & ijkl  & mnop  & qrst  \\
664uvwx    & yzab  & cdef  & ghij  & klmn  \\
665opqr    & stuv  & wxyz  &               &
666\end{tabular}
667\end{tabular}
668\end{center}
669The example takes advantage of resuming a generator in the constructor to prime the loops so the first character sent for formatting appears inside the nested loops.
670The destructor provides a newline, if formatted text ends with a full line.
671Figure~\ref{f:CFormatSim} shows the C implementation of the \CFA input generator with one additional field and the computed @goto@.
672For contrast, Figure~\ref{f:PythonFormatter} shows the equivalent Python format generator with the same properties as the Fibonacci generator.
673
674Figure~\ref{f:DeviceDriverGen} shows a \emph{killer} asymmetric generator, a device-driver, because device drivers caused 70\%-85\% of failures in Windows/Linux~\cite{Swift05}.
675Device drives follow the pattern of simple data state but complex execution state, \ie finite state-machine (FSM) parsing a protocol.
676For example, the following protocol:
677\begin{center}
678\ldots\, STX \ldots\, message \ldots\, ESC ETX \ldots\, message \ldots\, ETX 2-byte crc \ldots
679\end{center}
680is a network message beginning with the control character STX, ending with an ETX, and followed by a 2-byte cyclic-redundancy check.
681Control characters may appear in a message if preceded by an ESC.
682When a message byte arrives, it triggers an interrupt, and the operating system services the interrupt by calling the device driver with the byte read from a hardware register.
683The device driver returns a status code of its current state, and when a complete message is obtained, the operating system knows the message is in the message buffer.
684Hence, the device driver is an input/output generator.
685
686Note, the cost of creating and resuming the device-driver generator, @Driver@, is virtually identical to call/return, so performance in an operating-system kernel is excellent.
687As well, the data state is small, where variables @byte@ and @msg@ are communication variables for passing in message bytes and returning the message, and variables @lnth@, @crc@, and @sum@ are local variable that must be retained between calls and are manually hoisted into the generator type.
688% Manually, detecting and hoisting local-state variables is easy when the number is small.
689In contrast, the execution state is large, with one @resume@ and seven @suspend@s.
690Hence, the key benefits of the generator are correctness, safety, and maintenance because the execution states are transcribed directly into the programming language rather than using a table-driven approach.
691Because FSMs can be complex and frequently occur in important domains, direct generator support is important in a system programming language.
692
693\begin{figure}
694\centering
695\newbox\myboxA
696\begin{lrbox}{\myboxA}
697\begin{python}[aboveskip=0pt,belowskip=0pt]
698def Fib():
699        fn1, fn = 0, 1
700        while True:
701                `yield fn1`
702                fn1, fn = fn, fn1 + fn
703f1 = Fib()
704f2 = Fib()
705for i in range( 10 ):
706        print( next( f1 ), next( f2 ) )
707
708
709
710
711
712
713\end{python}
714\end{lrbox}
715
716\newbox\myboxB
717\begin{lrbox}{\myboxB}
718\begin{python}[aboveskip=0pt,belowskip=0pt]
719def Fmt():
720        try:
721                while True:
722                        for g in range( 5 ):
723                                for b in range( 4 ):
724                                        print( `(yield)`, end='' )
725                                print( '  ', end='' )
726                        print()
727        except GeneratorExit:
728                if g != 0 | b != 0:
729                        print()
730fmt = Fmt()
731`next( fmt )`                    # prime, next prewritten
732for i in range( 41 ):
733        `fmt.send( 'a' );`      # send to yield
734\end{python}
735\end{lrbox}
736\subfloat[Fibonacci]{\label{f:PythonFibonacci}\usebox\myboxA}
737\hspace{3pt}
738\vrule
739\hspace{3pt}
740\subfloat[Formatter]{\label{f:PythonFormatter}\usebox\myboxB}
741\caption{Python generator}
742\label{f:PythonGenerator}
743
744\bigskip
745
746\begin{tabular}{@{}l|l@{}}
747\begin{cfa}[aboveskip=0pt,belowskip=0pt]
748enum Status { CONT, MSG, ESTX,
749                                ELNTH, ECRC };
750`generator` Driver {
751        Status status;
752        unsigned char byte, * msg; // communication
753        unsigned int lnth, sum;      // local state
754        unsigned short int crc;
755};
756void ?{}( Driver & d, char * m ) { d.msg = m; }
757Status next( Driver & d, char b ) with( d ) {
758        byte = b; `resume( d );` return status;
759}
760void main( Driver & d ) with( d ) {
761        enum { STX = '\002', ESC = '\033',
762                        ETX = '\003', MaxMsg = 64 };
763  msg: for () { // parse message
764                status = CONT;
765                lnth = 0; sum = 0;
766                while ( byte != STX ) `suspend;`
767          emsg: for () {
768                        `suspend;` // process byte
769\end{cfa}
770&
771\begin{cfa}[aboveskip=0pt,belowskip=0pt]
772                        choose ( byte ) { // switch with implicit break
773                          case STX:
774                                status = ESTX; `suspend;` continue msg;
775                          case ETX:
776                                break emsg;
777                          case ESC:
778                                `suspend;`
779                        }
780                        if ( lnth >= MaxMsg ) { // buffer full ?
781                                status = ELNTH; `suspend;` continue msg; }
782                        msg[lnth++] = byte;
783                        sum += byte;
784                }
785                msg[lnth] = '\0'; // terminate string
786                `suspend;`
787                crc = byte << 8;
788                `suspend;`
789                status = (crc | byte) == sum ? MSG : ECRC;
790                `suspend;`
791        }
792}
793\end{cfa}
794\end{tabular}
795\caption{Device-driver generator for communication protocol}
796\label{f:DeviceDriverGen}
797\end{figure}
798
799Figure~\ref{f:CFAPingPongGen} shows a symmetric generator, where the generator resumes another generator, forming a resume/resume cycle.
800(The trivial cycle is a generator resuming itself.)
801This control flow is similar to recursion for functions but without stack growth.
802The steps for symmetric control-flow are creating, executing, and terminating the cycle.
803Constructing the cycle must deal with definition-before-use to close the cycle, \ie, the first generator must know about the last generator, which is not within scope.
804(This issue occurs for any cyclic data structure.)
805% The example creates all the generators and then assigns the partners that form the cycle.
806% Alternatively, the constructor can assign the partners as they are declared, except the first, and the first-generator partner is set after the last generator declaration to close the cycle.
807Once the cycle is formed, the program main resumes one of the generators, and the generators can then traverse an arbitrary cycle using @resume@ to activate partner generator(s).
808Terminating the cycle is accomplished by @suspend@ or @return@, both of which go back to the stack frame that started the cycle (program main in the example).
809The starting stack-frame is below the last active generator because the resume/resume cycle does not grow the stack.
810Also, since local variables are not retained in the generator function, it does not contain any objects with destructors that must be called, so the  cost is the same as a function return.
811Destructor cost occurs when the generator instance is deallocated, which is easily controlled by the programmer.
812
813Figure~\ref{f:CPingPongSim} shows the implementation of the symmetric generator, where the complexity is the @resume@, which needs an extension to the calling convention to perform a forward rather than backward jump.
814This jump-starts at the top of the next generator main to re-execute the normal calling convention to make space on the stack for its local variables.
815However, before the jump, the caller must reset its stack (and any registers) equivalent to a @return@, but subsequently jump forward.
816This semantics is basically a tail-call optimization, which compilers already perform.
817The example shows the assembly code to undo the generator's entry code before the direct jump.
818This assembly code depends on what entry code is generated, specifically if there are local variables and the level of optimization.
819To provide this new calling convention requires a mechanism built into the compiler, which is beyond the scope of \CFA at this time.
820Nevertheless, it is possible to hand generate any symmetric generators for proof of concept and performance testing.
821A compiler could also eliminate other artifacts in the generator simulation to further increase performance, \eg LLVM has various coroutine support~\cite{CoroutineTS}, and \CFA can leverage this support should it fork @clang@.
822
823\begin{figure}
824\centering
825\begin{lrbox}{\myboxA}
826\begin{cfa}[aboveskip=0pt,belowskip=0pt]
827`generator PingPong` {
828        const char * name;
829        int N;
830        int i;                          // local state
831        PingPong & partner; // rebindable reference
832};
833
834void `main( PingPong & pp )` with(pp) {
835        for ( ; i < N; i += 1 ) {
836                sout | name | i;
837                `resume( partner );`
838        }
839}
840int main() {
841        enum { N = 5 };
842        PingPong ping = {"ping",N,0}, pong = {"pong",N,0};
843        &ping.partner = &pong;  &pong.partner = &ping;
844        `resume( ping );`
845}
846\end{cfa}
847\end{lrbox}
848
849\begin{lrbox}{\myboxB}
850\begin{cfa}[escapechar={},aboveskip=0pt,belowskip=0pt]
851typedef struct PingPong {
852        const char * name;
853        int N, i;
854        struct PingPong * partner;
855        void * next;
856} PingPong;
857#define PPCtor(name, N) {name,N,0,NULL,NULL}
858void comain( PingPong * pp ) {
859        if ( pp->next ) goto *pp->next;
860        pp->next = &&cycle;
861        for ( ; pp->i < pp->N; pp->i += 1 ) {
862                printf( "%s %d\n", pp->name, pp->i );
863                asm( "mov  %0,%%rdi" : "=m" (pp->partner) );
864                asm( "mov  %rdi,%rax" );
865                asm( "popq %rbx" );
866                asm( "jmp  comain" );
867          cycle: ;
868        }
869}
870\end{cfa}
871\end{lrbox}
872
873\subfloat[\CFA symmetric generator]{\label{f:CFAPingPongGen}\usebox\myboxA}
874\hspace{3pt}
875\vrule
876\hspace{3pt}
877\subfloat[C generator simulation]{\label{f:CPingPongSim}\usebox\myboxB}
878\hspace{3pt}
879\caption{Ping-Pong symmetric generator}
880\label{f:PingPongSymmetricGenerator}
881\end{figure}
882
883Finally, part of this generator work was inspired by the recent \CCtwenty generator proposal~\cite{C++20Coroutine19} (which they call coroutines).
884Our work provides the same high-performance asymmetric generators as \CCtwenty, and extends their work with symmetric generators.
885An additional \CCtwenty generator feature allows @suspend@ and @resume@ to be followed by a restricted compound statement that is executed after the current generator has reset its stack but before calling the next generator, specified with \CFA syntax:
886\begin{cfa}
887... suspend`{ ... }`;
888... resume( C )`{ ... }` ...
889\end{cfa}
890Since the current generator's stack is released before calling the compound statement, the compound statement can only reference variables in the generator's type.
891This feature is useful when a generator is used in a concurrent context to ensure it is stopped before releasing a lock in the compound statement, which might immediately allow another thread to resume the generator.
892Hence, this mechanism provides a general and safe handoff of the generator among competing threads.
893
894
895\subsection{Coroutine}
896\label{s:Coroutine}
897
898Stackful coroutines extend generator semantics, \ie there is an implicit closure and @suspend@ may appear in a helper function called from the coroutine main.
899A coroutine is specified by replacing @generator@ with @coroutine@ for the type.
900Coroutine generality results in higher cost for creation, due to dynamic stack allocation, execution, due to context switching among stacks, and terminating, due to possible stack unwinding and dynamic stack deallocation.
901A series of different kinds of coroutines and their implementations demonstrate how coroutines extend generators.
902
903First, the previous generator examples are converted to their coroutine counterparts, allowing local-state variables to be moved from the generator type into the coroutine main.
904\begin{description}
905\item[Fibonacci]
906Move the declaration of @fn1@ to the start of coroutine main.
907\begin{cfa}[xleftmargin=0pt]
908void main( Fib & fib ) with(fib) {
909        `int fn1;`
910\end{cfa}
911\item[Formatter]
912Move the declaration of @g@ and @b@ to the for loops in the coroutine main.
913\begin{cfa}[xleftmargin=0pt]
914for ( `g`; 5 ) {
915        for ( `b`; 4 ) {
916\end{cfa}
917\item[Device Driver]
918Move the declaration of @lnth@ and @sum@ to their points of initialization.
919\begin{cfa}[xleftmargin=0pt]
920        status = CONT;
921        `unsigned int lnth = 0, sum = 0;`
922        ...
923        `unsigned short int crc = byte << 8;`
924\end{cfa}
925\item[PingPong]
926Move the declaration of @i@ to the for loop in the coroutine main.
927\begin{cfa}[xleftmargin=0pt]
928void main( PingPong & pp ) with(pp) {
929        for ( `i`; N ) {
930\end{cfa}
931\end{description}
932It is also possible to refactor code containing local-state and @suspend@ statements into a helper function, like the computation of the CRC for the device driver.
933\begin{cfa}
934unsigned int Crc() {
935        `suspend;`
936        unsigned short int crc = byte << 8;
937        `suspend;`
938        status = (crc | byte) == sum ? MSG : ECRC;
939        return crc;
940}
941\end{cfa}
942A call to this function is placed at the end of the driver's coroutine-main.
943For complex finite-state machines, refactoring is part of normal program abstraction, especially when code is used in multiple places.
944Again, this complexity is usually associated with execution state rather than data state.
945
946\begin{comment}
947Figure~\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 functions, \eg @next@.
948Like 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.
949The 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@.
950The interface function @next@, takes a Fibonacci instance and context switches to it using @resume@;
951on restart, the Fibonacci field, @fn@, contains the next value in the sequence, which is returned.
952The first @resume@ is special because it allocates the coroutine stack and cocalls its coroutine main on that stack;
953when the coroutine main returns, its stack is deallocated.
954Hence, @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.
955Figure~\ref{f:Coroutine1State} shows the coroutine version of the C version in Figure~\ref{f:ExternalState}.
956Coroutine generators are called \newterm{output coroutines} because values are only returned.
957
958\begin{figure}
959\centering
960\newbox\myboxA
961% \begin{lrbox}{\myboxA}
962% \begin{cfa}[aboveskip=0pt,belowskip=0pt]
963% `int fn1, fn2, state = 1;`   // single global variables
964% int fib() {
965%       int fn;
966%       `switch ( state )` {  // explicit execution state
967%         case 1: fn = 0;  fn1 = fn;  state = 2;  break;
968%         case 2: fn = 1;  fn2 = fn1;  fn1 = fn;  state = 3;  break;
969%         case 3: fn = fn1 + fn2;  fn2 = fn1;  fn1 = fn;  break;
970%       }
971%       return fn;
972% }
973% int main() {
974%
975%       for ( int i = 0; i < 10; i += 1 ) {
976%               printf( "%d\n", fib() );
977%       }
978% }
979% \end{cfa}
980% \end{lrbox}
981\begin{lrbox}{\myboxA}
982\begin{cfa}[aboveskip=0pt,belowskip=0pt]
983#define FibCtor { 0, 1 }
984typedef struct { int fn1, fn; } Fib;
985int fib( Fib * f ) {
986
987        int ret = f->fn1;
988        f->fn1 = f->fn;
989        f->fn = ret + f->fn;
990        return ret;
991}
992
993
994
995int main() {
996        Fib f1 = FibCtor, f2 = FibCtor;
997        for ( int i = 0; i < 10; i += 1 ) {
998                printf( "%d %d\n",
999                                fib( &f1 ), fib( &f2 ) );
1000        }
1001}
1002\end{cfa}
1003\end{lrbox}
1004
1005\newbox\myboxB
1006\begin{lrbox}{\myboxB}
1007\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1008`coroutine` Fib { int fn1; };
1009void main( Fib & fib ) with( fib ) {
1010        int fn;
1011        [fn1, fn] = [0, 1];
1012        for () {
1013                `suspend;`
1014                [fn1, fn] = [fn, fn1 + fn];
1015        }
1016}
1017int ?()( Fib & fib ) with( fib ) {
1018        return `resume( fib )`.fn1;
1019}
1020int main() {
1021        Fib f1, f2;
1022        for ( 10 ) {
1023                sout | f1() | f2();
1024}
1025
1026
1027\end{cfa}
1028\end{lrbox}
1029
1030\newbox\myboxC
1031\begin{lrbox}{\myboxC}
1032\begin{python}[aboveskip=0pt,belowskip=0pt]
1033
1034def Fib():
1035
1036        fn1, fn = 0, 1
1037        while True:
1038                `yield fn1`
1039                fn1, fn = fn, fn1 + fn
1040
1041
1042// next prewritten
1043
1044
1045f1 = Fib()
1046f2 = Fib()
1047for i in range( 10 ):
1048        print( next( f1 ), next( f2 ) )
1049
1050
1051
1052\end{python}
1053\end{lrbox}
1054
1055\subfloat[C]{\label{f:GlobalVariables}\usebox\myboxA}
1056\hspace{3pt}
1057\vrule
1058\hspace{3pt}
1059\subfloat[\CFA]{\label{f:ExternalState}\usebox\myboxB}
1060\hspace{3pt}
1061\vrule
1062\hspace{3pt}
1063\subfloat[Python]{\label{f:ExternalState}\usebox\myboxC}
1064\caption{Fibonacci generator}
1065\label{f:C-fibonacci}
1066\end{figure}
1067
1068\bigskip
1069
1070\newbox\myboxA
1071\begin{lrbox}{\myboxA}
1072\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1073`coroutine` Fib { int fn; };
1074void main( Fib & fib ) with( fib ) {
1075        fn = 0;  int fn1 = fn; `suspend`;
1076        fn = 1;  int fn2 = fn1;  fn1 = fn; `suspend`;
1077        for () {
1078                fn = fn1 + fn2; fn2 = fn1; fn1 = fn; `suspend`; }
1079}
1080int next( Fib & fib ) with( fib ) { `resume( fib );` return fn; }
1081int main() {
1082        Fib f1, f2;
1083        for ( 10 )
1084                sout | next( f1 ) | next( f2 );
1085}
1086\end{cfa}
1087\end{lrbox}
1088\newbox\myboxB
1089\begin{lrbox}{\myboxB}
1090\begin{python}[aboveskip=0pt,belowskip=0pt]
1091
1092def Fibonacci():
1093        fn = 0; fn1 = fn; `yield fn`  # suspend
1094        fn = 1; fn2 = fn1; fn1 = fn; `yield fn`
1095        while True:
1096                fn = fn1 + fn2; fn2 = fn1; fn1 = fn; `yield fn`
1097
1098
1099f1 = Fibonacci()
1100f2 = Fibonacci()
1101for i in range( 10 ):
1102        print( `next( f1 )`, `next( f2 )` ) # resume
1103
1104\end{python}
1105\end{lrbox}
1106\subfloat[\CFA]{\label{f:Coroutine3States}\usebox\myboxA}
1107\qquad
1108\subfloat[Python]{\label{f:Coroutine1State}\usebox\myboxB}
1109\caption{Fibonacci input coroutine, 3 states, internal variables}
1110\label{f:cfa-fibonacci}
1111\end{figure}
1112\end{comment}
1113
1114\begin{figure}
1115\centering
1116\lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $
1117\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
1118\begin{cfa}
1119`coroutine` Prod {
1120        Cons & c;                       // communication
1121        int N, money, receipt;
1122};
1123void main( Prod & prod ) with( prod ) {
1124        // 1st resume starts here
1125        for ( i; N ) {
1126                int p1 = random( 100 ), p2 = random( 100 );
1127                sout | p1 | " " | p2;
1128                int status = delivery( c, p1, p2 );
1129                sout | " $" | money | nl | status;
1130                receipt += 1;
1131        }
1132        stop( c );
1133        sout | "prod stops";
1134}
1135int payment( Prod & prod, int money ) {
1136        prod.money = money;
1137        `resume( prod );`
1138        return prod.receipt;
1139}
1140void start( Prod & prod, int N, Cons &c ) {
1141        &prod.c = &c;
1142        prod.[N, receipt] = [N, 0];
1143        `resume( prod );`
1144}
1145int main() {
1146        Prod prod;
1147        Cons cons = { prod };
1148        start( prod, 5, cons );
1149}
1150\end{cfa}
1151&
1152\begin{cfa}
1153`coroutine` Cons {
1154        Prod & p;                       // communication
1155        int p1, p2, status;
1156        bool done;
1157};
1158void ?{}( Cons & cons, Prod & p ) {
1159        &cons.p = &p; // reassignable reference
1160        cons.[status, done ] = [0, false];
1161}
1162void main( Cons & cons ) with( cons ) {
1163        // 1st resume starts here
1164        int money = 1, receipt;
1165        for ( ; ! done; ) {
1166                sout | p1 | " " | p2 | nl | " $" | money;
1167                status += 1;
1168                receipt = payment( p, money );
1169                sout | " #" | receipt;
1170                money += 1;
1171        }
1172        sout | "cons stops";
1173}
1174int delivery( Cons & cons, int p1, int p2 ) {
1175        cons.[p1, p2] = [p1, p2];
1176        `resume( cons );`
1177        return cons.status;
1178}
1179void stop( Cons & cons ) {
1180        cons.done = true;
1181        `resume( cons );`
1182}
1183
1184\end{cfa}
1185\end{tabular}
1186\caption{Producer / consumer: resume-resume cycle, bidirectional communication}
1187\label{f:ProdCons}
1188\end{figure}
1189
1190Figure~\ref{f:ProdCons} shows the ping-pong example in Figure~\ref{f:CFAPingPongGen} extended into a producer/consumer symmetric-coroutine performing bidirectional communication.
1191This example is illustrative because both producer/consumer have two interface functions with @resume@s that suspend execution in these interface (helper) functions.
1192The program main creates the producer coroutine, passes it to the consumer coroutine in its initialization, and closes the cycle at the call to @start@ along with the number of items to be produced.
1193The first @resume@ of @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
1194@prod@'s coroutine main starts, creates local-state 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.
1195
1196The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
1197On the first resume, @cons@'s stack is created and initialized, holding local-state variables retained between subsequent activations of the coroutine.
1198The 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).
1199The call from the consumer to @payment@ introduces the cycle between producer and consumer.
1200When @payment@ is called, the consumer copies values into the producer's communication variable and a resume is executed.
1201The context switch restarts the producer at the point where it last context switched, so it continues in @delivery@ after the resume.
1202@delivery@ returns the status value in @prod@'s coroutine main, where the status is printed.
1203The loop then repeats calling @delivery@, where each call resumes the consumer coroutine.
1204The context switch to the consumer continues in @payment@.
1205The consumer increments and returns the receipt to the call in @cons@'s coroutine main.
1206The loop then repeats calling @payment@, where each call resumes the producer coroutine.
1207Figure~\ref{f:ProdConsRuntimeStacks} shows the runtime stacks of the program main, and the coroutine mains for @prod@ and @cons@ during the cycling.
1208
1209\begin{figure}
1210\begin{center}
1211\input{FullProdConsStack.pstex_t}
1212\end{center}
1213\vspace*{-10pt}
1214\caption{Producer / consumer runtime stacks}
1215\label{f:ProdConsRuntimeStacks}
1216
1217\medskip
1218
1219\begin{center}
1220\input{FullCoroutinePhases.pstex_t}
1221\end{center}
1222\vspace*{-10pt}
1223\caption{Ping / Pong coroutine steps}
1224\label{f:PingPongFullCoroutineSteps}
1225\end{figure}
1226
1227Terminating a coroutine cycle is more complex than a generator cycle, because it requires context switching to the program main's \emph{stack} to shutdown the program, whereas generators started by the program main run on its stack.
1228Furthermore, each deallocated coroutine must guarantee all destructors are run for object allocated in the coroutine type \emph{and} allocated on the coroutine's stack at the point of suspension, which can be arbitrarily deep.
1229When a coroutine's main ends, its stack is already unwound so any stack allocated objects with destructors have been finalized.
1230The na\"{i}ve semantics for coroutine-cycle termination is to context switch to the last resumer, like executing a @suspend@/@return@ in a generator.
1231However, for coroutines, the last resumer is \emph{not} implicitly below the current stack frame, as for generators, because each coroutine's stack is independent.
1232Unfortunately, it is impossible to determine statically if a coroutine is in a cycle and unrealistic to check dynamically (graph-cycle problem).
1233Hence, a compromise solution is necessary that works for asymmetric (acyclic) and symmetric (cyclic) coroutines.
1234
1235Our solution is to context switch back to the first resumer (starter) once the coroutine ends.
1236This semantics works well for the most common asymmetric and symmetric coroutine usage patterns.
1237For asymmetric coroutines, it is common for the first resumer (starter) coroutine to be the only resumer.
1238All previous generators converted to coroutines have this property.
1239For symmetric coroutines, it is common for the cycle creator to persist for the lifetime of the cycle.
1240Hence, the starter coroutine is remembered on the first resume and ending the coroutine resumes the starter.
1241Figure~\ref{f:ProdConsRuntimeStacks} shows this semantic by the dashed lines from the end of the coroutine mains: @prod@ starts @cons@ so @cons@ resumes @prod@ at the end, and the program main starts @prod@ so @prod@ resumes the program main at the end.
1242For other scenarios, it is always possible to devise a solution with additional programming effort, such as forcing the cycle forward (backward) to a safe point before starting termination.
1243
1244The producer/consumer example does not illustrate the full power of the starter semantics because @cons@ always ends first.
1245Assume generator @PingPong@ is converted to a coroutine.
1246Figure~\ref{f:PingPongFullCoroutineSteps} shows the creation, starter, and cyclic execution steps of the coroutine version.
1247The program main creates (declares) coroutine instances @ping@ and @pong@.
1248Next, program main resumes @ping@, making it @ping@'s starter, and @ping@'s main resumes @pong@'s main, making it @pong@'s starter.
1249Execution forms a cycle when @pong@ resumes @ping@, and cycles $N$ times.
1250By adjusting $N$ for either @ping@/@pong@, it is possible to have either one finish first, instead of @pong@ always ending first.
1251If @pong@ ends first, it resumes its starter @ping@ in its coroutine main, then @ping@ ends and resumes its starter the program main in function @start@.
1252If @ping@ ends first, it resumes its starter the program main in function @start@.
1253Regardless of the cycle complexity, the starter stack always leads back to the program main, but the stack can be entered at an arbitrary point.
1254Once back at the program main, coroutines @ping@ and @pong@ are deallocated.
1255For generators, deallocation runs the destructors for all objects in the generator type.
1256For coroutines, deallocation deals with objects in the coroutine type and must also run the destructors for any objects pending on the coroutine's stack for any unterminated coroutine.
1257Hence, if a coroutine's destructor detects the coroutine is not ended, it implicitly raises a cancellation exception (uncatchable exception) at the coroutine and resumes it so the cancellation exception can propagate to the root of the coroutine's stack destroying all local variable on the stack.
1258So the \CFA semantics for the generator and coroutine, ensure both can be safely deallocated at any time, regardless of their current state, like any other aggregate object.
1259Explicitly raising normal exceptions at another coroutine can replace flag variables, like @stop@, \eg @prod@ raises a @stop@ exception at @cons@ after it finishes generating values and resumes @cons@, which catches the @stop@ exception to terminate its loop.
1260
1261Finally, there is an interesting effect for @suspend@ with symmetric coroutines.
1262A coroutine must retain its last resumer to suspend back because the resumer is on a different stack.
1263These reverse pointers allow @suspend@ to cycle \emph{backwards}, which may be useful in certain cases.
1264However, there is an anomaly if a coroutine resumes itself, because it overwrites its last resumer with itself, losing the ability to resume the last external resumer.
1265To prevent losing this information, a self-resume does not overwrite the last resumer.
1266
1267
1268\subsection{Generator / Coroutine Implementation}
1269
1270A significant implementation challenge for generators/coroutines (and threads in Section~\ref{s:threads}) is adding extra fields to the custom types and related functions, \eg inserting code after/before the coroutine constructor/destructor and @main@ to create/initialize/de-initialize/destroy any extra fields, \eg stack.
1271There are several solutions to these problem, which follow from the object-oriented flavour of adopting custom types.
1272
1273For object-oriented languages, inheritance is used to provide extra fields and code via explicit inheritance:
1274\begin{cfa}[morekeywords={class,inherits}]
1275class myCoroutine inherits baseCoroutine { ... }
1276\end{cfa}
1277% The problem is that the programming language and its tool chain, \eg debugger, @valgrind@, need to understand @baseCoroutine@ because it infers special property, so type @baseCoroutine@ becomes a de facto keyword and all types inheriting from it are implicitly custom types.
1278The problem is that some special properties are not handled by existing language semantics, \eg the execution of constructors/destructors is in the wrong order to implicitly start threads because the thread must start \emph{after} all constructors as it relies on a completely initialized object, but the inherited constructor runs \emph{before} the derived.
1279Alternatives, such as explicitly starting threads as in Java, are repetitive and forgetting to call start is a common source of errors.
1280An alternative is composition:
1281\begin{cfa}
1282struct myCoroutine {
1283        ... // declaration/communication variables
1284        baseCoroutine dummy; // composition, last declaration
1285}
1286\end{cfa}
1287which also requires an explicit declaration that must be last to ensure correct initialization order.
1288However, there is nothing preventing wrong placement or multiple declarations.
1289
1290\CFA custom types make any special properties explicit to the language and its tool chain, \eg the language code-generator knows where to inject code
1291% and when it is unsafe to perform certain optimizations,
1292and IDEs using simple parsing can find and manipulate types with special properties.
1293The downside of this approach is that it makes custom types a special case in the language.
1294Users wanting to extend custom types or build their own can only do so in ways offered by the language.
1295Furthermore, implementing custom types without language support may display the power of a programming language.
1296\CFA blends the two approaches, providing custom type for idiomatic \CFA code, while extending and building new custom types is still possible, similar to Java concurrency with builtin and library.
1297
1298Part of the mechanism to generalize custom types is the \CFA trait~\cite[\S~2.3]{Moss18}, \eg the definition for custom-type @coroutine@ is anything satisfying the trait @is_coroutine@, and this trait both enforces and restricts the coroutine-interface functions.
1299\begin{cfa}
1300trait is_coroutine( `dtype` T ) {
1301        void main( T & );
1302        coroutine_desc * get_coroutine( T & );
1303};
1304forall( `dtype` T | is_coroutine(T) ) void $suspend$( T & ), resume( T & );
1305\end{cfa}
1306Note, copying generators/coroutines/threads is not meaningful.
1307For example, both the resumer and suspender descriptors can have bidirectional pointers;
1308copying these coroutines does not update the internal pointers so behaviour of both copies would be difficult to understand.
1309Furthermore, two coroutines cannot logically execute on the same stack.
1310A deep coroutine copy, which copies the stack, is also meaningless in an unmanaged language (no garbage collection), like C, because the stack may contain pointers to object within it that require updating for the copy.
1311The \CFA @dtype@ property provides no \emph{implicit} copying operations and the @is_coroutine@ trait provides no \emph{explicit} copying operations, so all coroutines must be passed by reference (pointer).
1312The function definitions ensure there is a statically typed @main@ function that is the starting point (first stack frame) of a coroutine, and a mechanism to get (read) the coroutine descriptor from its handle.
1313The @main@ function has no return value or additional parameters because the coroutine type allows an arbitrary number of interface functions with corresponding arbitrary typed input/output values versus fixed ones.
1314The 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@ function, and possibly redefining \textsf{suspend} and @resume@.
1315
1316The \CFA custom-type @coroutine@ implicitly implements the getter and forward declarations for the coroutine main.
1317\begin{cquote}
1318\begin{tabular}{@{}ccc@{}}
1319\begin{cfa}
1320coroutine MyCor {
1321        int value;
1322
1323};
1324\end{cfa}
1325&
1326{\Large $\Rightarrow$}
1327&
1328\begin{tabular}{@{}ccc@{}}
1329\begin{cfa}
1330struct MyCor {
1331        int value;
1332        coroutine_desc cor;
1333};
1334\end{cfa}
1335&
1336\begin{cfa}
1337static inline coroutine_desc *
1338get_coroutine( MyCor & this ) {
1339        return &this.cor;
1340}
1341\end{cfa}
1342&
1343\begin{cfa}
1344void main( MyCor * this );
1345
1346
1347
1348\end{cfa}
1349\end{tabular}
1350\end{tabular}
1351\end{cquote}
1352The combination of custom types and fundamental @trait@ description of these types allows a concise specification for programmers and tools, while more advanced programmers can have tighter control over memory layout and initialization.
1353
1354Figure~\ref{f:CoroutineMemoryLayout} shows different memory-layout options for a coroutine (where a task is similar).
1355The coroutine handle is the @coroutine@ instance containing programmer specified type global/communication variables across interface functions.
1356The coroutine descriptor contains all implicit declarations needed by the runtime, \eg @suspend@/@resume@, and can be part of the coroutine handle or separate.
1357The coroutine stack can appear in a number of locations and be fixed or variable sized.
1358Hence, the coroutine's stack could be a VLS\footnote{
1359We are examining variable-sized structures (VLS), where fields can be variable-sized structures or arrays.
1360Once allocated, a VLS is fixed sized.}
1361on the allocating stack, provided the allocating stack is large enough.
1362For a VLS stack allocation/deallocation is an inexpensive adjustment of the stack pointer, modulo any stack constructor costs (\eg initial frame setup).
1363For heap stack allocation, allocation/deallocation is an expensive heap allocation (where the heap can be a shared resource), modulo any stack constructor costs.
1364With heap stack allocation, it is also possible to use a split (segmented) stack calling convention, available with gcc and clang, so the stack is variable sized.
1365Currently, \CFA supports stack/heap allocated descriptors but only fixed-sized heap allocated stacks.
1366In \CFA debug-mode, the fixed-sized stack is terminated with a write-only page, which catches most stack overflows.
1367Experience teaching concurrency with \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue for students.
1368Split-stack allocation is under development but requires recompilation of legacy code, which may be impossible.
1369
1370\begin{figure}
1371\centering
1372\input{corlayout.pstex_t}
1373\caption{Coroutine memory layout}
1374\label{f:CoroutineMemoryLayout}
1375\end{figure}
1376
1377
1378\section{Concurrency}
1379\label{s:Concurrency}
1380
1381Concurrency is nondeterministic scheduling of independent sequential execution paths (threads), where each thread has its own stack.
1382A single thread with multiple call stacks, \newterm{coroutining}~\cite{Conway63,Marlin80}, does \emph{not} imply concurrency~\cite[\S~2]{Buhr05a}.
1383In coroutining, coroutines self-schedule the thread across stacks so execution is deterministic.
1384(It is \emph{impossible} to generate a concurrency error when coroutining.)
1385However, coroutines are a stepping stone towards concurrency.
1386
1387The transition to concurrency, even for a single thread with multiple stacks, occurs when coroutines context switch to a \newterm{scheduling coroutine}, introducing non-determinism from the coroutine perspective~\cite[\S~3,]{Buhr05a}.
1388Therefore, a minimal concurrency system requires coroutines \emph{in conjunction with a nondeterministic scheduler}.
1389The resulting execution system now follows a cooperative threading model~\cite{Adya02,libdill}, called \newterm{non-preemptive scheduling}.
1390Adding \newterm{preemption} introduces non-cooperative scheduling, where context switching occurs randomly between any two instructions often based on a timer interrupt, called \newterm{preemptive scheduling}.
1391While a scheduler introduces uncertain execution among explicit context switches, preemption introduces uncertainty by introducing implicit context switches.
1392Uncertainty gives the illusion of parallelism on a single processor and provides a mechanism to access and increase performance on multiple processors.
1393The reason is that the scheduler/runtime have complete knowledge about resources and how to best utilized them.
1394However, the introduction of unrestricted nondeterminism results in the need for \newterm{mutual exclusion} and \newterm{synchronization}, which restrict nondeterminism for correctness;
1395otherwise, it is impossible to write meaningful concurrent programs.
1396Optimal concurrent performance is often obtained by having as much nondeterminism as mutual exclusion and synchronization correctness allow.
1397
1398A scheduler can either be a stackless or stackful.
1399For 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.
1400For 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.
1401The \CFA runtime uses a stackful scheduler for uniformity and security.
1402
1403
1404\subsection{Thread}
1405\label{s:threads}
1406
1407Threading needs the ability to start a thread and wait for its completion.
1408A common API for this ability is @fork@ and @join@.
1409\begin{cquote}
1410\begin{tabular}{@{}lll@{}}
1411\multicolumn{1}{c}{\textbf{Java}} & \multicolumn{1}{c}{\textbf{\Celeven}} & \multicolumn{1}{c}{\textbf{pthreads}} \\
1412\begin{cfa}
1413class MyTask extends Thread {...}
1414mytask t = new MyTask(...);
1415`t.start();` // start
1416// concurrency
1417`t.join();` // wait
1418\end{cfa}
1419&
1420\begin{cfa}
1421class MyTask { ... } // functor
1422MyTask mytask;
1423`thread t( mytask, ... );` // start
1424// concurrency
1425`t.join();` // wait
1426\end{cfa}
1427&
1428\begin{cfa}
1429void * rtn( void * arg ) {...}
1430pthread_t t;  int i = 3;
1431`pthread_create( &t, rtn, (void *)i );` // start
1432// concurrency
1433`pthread_join( t, NULL );` // wait
1434\end{cfa}
1435\end{tabular}
1436\end{cquote}
1437\CFA has a simpler approach using a custom @thread@ type and leveraging declaration semantics (allocation/deallocation), where threads implicitly @fork@ after construction and @join@ before destruction.
1438\begin{cfa}
1439thread MyTask {};
1440void main( MyTask & this ) { ... }
1441int main() {
1442        MyTask team`[10]`; $\C[2.5in]{// allocate stack-based threads, implicit start after construction}$
1443        // concurrency
1444} $\C{// deallocate stack-based threads, implicit joins before destruction}$
1445\end{cfa}
1446This semantic ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
1447For block allocation to arbitrary depth, including recursion, threads are created/destroyed in a lattice structure (tree with top and bottom).
1448Arbitrary topologies are possible using dynamic allocation, allowing threads to outlive their declaration scope, identical to normal dynamic allocation.
1449\begin{cfa}
1450MyTask * factory( int N ) { ... return `anew( N )`; } $\C{// allocate heap-based threads, implicit start after construction}$
1451int main() {
1452        MyTask * team = factory( 10 );
1453        // concurrency
1454        `delete( team );` $\C{// deallocate heap-based threads, implicit joins before destruction}\CRT$
1455}
1456\end{cfa}
1457
1458Figure~\ref{s:ConcurrentMatrixSummation} shows concurrently adding the rows of a matrix and then totalling the subtotals sequentially, after all the row threads have terminated.
1459The program uses heap-based threads because each thread needs different constructor values.
1460(Python provides a simple iteration mechanism to initialize array elements to different values allowing stack allocation.)
1461The allocation/deallocation pattern appears unusual because allocated objects are immediately deallocated without any intervening code.
1462However, for threads, the deletion provides implicit synchronization, which is the intervening code.
1463% While 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.
1464
1465\begin{figure}
1466\begin{cfa}
1467`thread` Adder { int * row, cols, & subtotal; } $\C{// communication variables}$
1468void ?{}( Adder & adder, int row[], int cols, int & subtotal ) {
1469        adder.[ row, cols, &subtotal ] = [ row, cols, &subtotal ];
1470}
1471void main( Adder & adder ) with( adder ) {
1472        subtotal = 0;
1473        for ( c; cols ) { subtotal += row[c]; }
1474}
1475int main() {
1476        const int rows = 10, cols = 1000;
1477        int matrix[rows][cols], subtotals[rows], total = 0;
1478        // read matrix
1479        Adder * adders[rows];
1480        for ( r; rows; ) { $\C{// start threads to sum rows}$
1481                adders[r] = `new( matrix[r], cols, &subtotals[r] );`
1482        }
1483        for ( r; rows ) { $\C{// wait for threads to finish}$
1484                `delete( adders[r] );` $\C{// termination join}$
1485                total += subtotals[r]; $\C{// total subtotal}$
1486        }
1487        sout | total;
1488}
1489\end{cfa}
1490\caption{Concurrent matrix summation}
1491\label{s:ConcurrentMatrixSummation}
1492\end{figure}
1493
1494
1495\subsection{Thread Implementation}
1496
1497Threads in \CFA are user level run by runtime kernel threads (see Section~\ref{s:CFARuntimeStructure}), where user threads provide concurrency and kernel threads provide parallelism.
1498Like coroutines, and for the same design reasons, \CFA provides a custom @thread@ type and a @trait@ to enforce and restrict the task-interface functions.
1499\begin{cquote}
1500\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
1501\begin{cfa}
1502thread myThread {
1503        ... // declaration/communication variables
1504};
1505
1506
1507\end{cfa}
1508&
1509\begin{cfa}
1510trait is_thread( `dtype` T ) {
1511        void main( T & );
1512        thread_desc * get_thread( T & );
1513        void ^?{}( T & `mutex` );
1514};
1515\end{cfa}
1516\end{tabular}
1517\end{cquote}
1518Like coroutines, the @dtype@ property prevents \emph{implicit} copy operations and the @is_thread@ trait provides no \emph{explicit} copy operations, so threads must be passed by reference (pointer).
1519Similarly, the function definitions ensure there is a statically typed @main@ function that is the thread starting point (first stack frame), a mechanism to get (read) the thread descriptor from its handle, and a special destructor to prevent deallocation while the thread is executing.
1520(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitor}.)
1521The difference between the coroutine and thread is that a coroutine borrows a thread from its caller, so the first thread resuming a coroutine creates the coroutine's stack and starts running the coroutine main on the stack;
1522whereas, a thread is scheduling for execution in @main@ immediately after its constructor is run.
1523No return value or additional parameters are necessary for this function because the @thread@ type allows an arbitrary number of interface functions with corresponding arbitrary typed input/output values.
1524
1525
1526\section{Mutual Exclusion / Synchronization}
1527\label{s:MutualExclusionSynchronization}
1528
1529Unrestricted nondeterminism is meaningless as there is no way to know when the result is completed without synchronization.
1530To produce meaningful execution requires clawing back some determinism using mutual exclusion and synchronization, where mutual exclusion provides access control for threads using shared data, and synchronization is a timing relationship among threads~\cite[\S~4]{Buhr05a}.
1531Some concurrent systems eliminate mutable shared-state by switching to stateless communication like message passing~\cite{Thoth,Harmony,V-Kernel,MPI} (Erlang, MPI), channels~\cite{CSP} (CSP,Go), actors~\cite{Akka} (Akka, Scala), or functional techniques (Haskell).
1532However, these approaches introduce a new communication mechanism for concurrency different from the standard communication using function call/return.
1533Hence, a programmer must learn and manipulate two sets of design/programming patterns.
1534While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
1535In contrast, approaches based on stateful models more closely resemble the standard call/return programming model, resulting in a single programming paradigm.
1536
1537At 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}.
1538However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}.
1539A newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
1540While 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.
1541
1542One of the most natural, elegant, and efficient mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor}.
1543First 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}.
1544In 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.
1545For these reasons, \CFA selected monitors as the core high-level concurrency construct, upon which higher-level approaches can be easily constructed.
1546
1547
1548\subsection{Mutual Exclusion}
1549
1550A group of instructions manipulating a specific instance of shared data that must be performed atomically is called a \newterm{critical section}~\cite{Dijkstra65}, which is enforced by \newterm{simple mutual-exclusion}.
1551The generalization is called a \newterm{group critical-section}~\cite{Joung00}, where multiple tasks with the same session use the resource simultaneously and different sessions are segregated, which is enforced by \newterm{complex mutual-exclusion} providing the correct kind and number of threads using a group critical-section.
1552The readers/writer problem~\cite{Courtois71} is an instance of a group critical-section, where readers share a session but writers have a unique session.
1553
1554However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
1555Methods 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.
1556Ease 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.
1557For 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.
1558However, a significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock.
1559Easing composability is another feature higher-level mutual-exclusion mechanisms can offer.
1560
1561
1562\subsection{Synchronization}
1563
1564Synchronization enforces relative ordering of execution, and synchronization tools provide numerous mechanisms to establish these timing relationships.
1565Low-level synchronization primitives offer good performance and flexibility at the cost of ease of use;
1566higher-level mechanisms often simplify usage by adding better coupling between synchronization and data, \eg receive-specific versus receive-any thread in message passing or offering specialized solutions, \eg barrier lock.
1567Often synchronization is used to order access to a critical section, \eg ensuring a waiting writer thread enters the critical section before a calling reader thread.
1568If the calling reader is scheduled before the waiting writer, the reader has barged.
1569Barging 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).
1570Preventing or detecting barging is an involved challenge with low-level locks, which is made easier through higher-level constructs.
1571This challenge is often split into two different approaches: barging avoidance and prevention.
1572Algorithms that unconditionally releasing a lock for competing threads to acquire use barging avoidance during synchronization to force a barging thread to wait;
1573algorithms that conditionally hold locks during synchronization, \eg baton-passing~\cite{Andrews89}, prevent barging completely.
1574
1575
1576\section{Monitor}
1577\label{s:Monitor}
1578
1579A \textbf{monitor} is a set of functions that ensure mutual exclusion when accessing shared state.
1580More precisely, a monitor is a programming technique that implicitly binds mutual exclusion to static function 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).
1581Restricting acquire/release points eases programming, comprehension, and maintenance, at a slight cost in flexibility and efficiency.
1582\CFA uses a custom @monitor@ type and leverages declaration semantics (deallocation) to protect active or waiting threads in a monitor.
1583
1584The following is a \CFA monitor implementation of an atomic counter.
1585\begin{cfa}[morekeywords=nomutex]
1586`monitor` Aint { int cnt; }; $\C[4.25in]{// atomic integer counter}$
1587int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$
1588int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions with int}\CRT$
1589int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; }
1590\end{cfa}
1591% The @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.
1592% (While a constructor may publish its address into a global variable, doing so generates a race-condition.)
1593The prefix increment operation, @++?@, is normally @mutex@, indicating mutual exclusion is necessary during function execution, to protect the incrementing from race conditions, unless there is an atomic increment instruction for the implementation type.
1594The assignment operators provide bidirectional conversion between an atomic and normal integer without accessing field @cnt@;
1595these operations only need @mutex@, if reading/writing the implementation type is not atomic.
1596The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics, which is similar to the \CC template @std::atomic@.
1597\begin{cfa}
1598int i = 0, j = 0, k = 5;
1599Aint x = { 0 }, y = { 0 }, z = { 5 }; $\C{// no mutex required}$
1600++x; ++y; ++z; $\C{// safe increment by multiple threads}$
1601x = 2; y = i; z = k; $\C{// conversions}$
1602i = x; j = y; k = z;
1603\end{cfa}
1604
1605\CFA monitors have \newterm{multi-acquire} semantics so the thread in the monitor may acquire it multiple times without deadlock, allowing recursion and calling other interface functions.
1606\begin{cfa}
1607monitor M { ... } m;
1608void foo( M & mutex m ) { ... } $\C{// acquire mutual exclusion}$
1609void bar( M & mutex m ) { $\C{// acquire mutual exclusion}$
1610        ... `bar( m );` ... `foo( m );` ... $\C{// reacquire mutual exclusion}$
1611}
1612\end{cfa}
1613\CFA monitors also ensure the monitor lock is released regardless of how an acquiring function ends (normal or exceptional), and returning a shared variable is safe via copying before the lock is released.
1614Similar safety is offered by \emph{explicit} mechanisms like \CC RAII;
1615monitor \emph{implicit} safety ensures no programmer usage errors.
1616Furthermore, RAII mechanisms cannot handle complex synchronization within a monitor, where the monitor lock may not be released on function exit because it is passed to an unblocking thread;
1617RAII is purely a mutual-exclusion mechanism (see Section~\ref{s:Scheduling}).
1618
1619
1620\subsection{Monitor Implementation}
1621
1622For the same design reasons, \CFA provides a custom @monitor@ type and a @trait@ to enforce and restrict the monitor-interface functions.
1623\begin{cquote}
1624\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
1625\begin{cfa}
1626monitor M {
1627        ... // shared data
1628};
1629
1630\end{cfa}
1631&
1632\begin{cfa}
1633trait is_monitor( `dtype` T ) {
1634        monitor_desc * get_monitor( T & );
1635        void ^?{}( T & mutex );
1636};
1637\end{cfa}
1638\end{tabular}
1639\end{cquote}
1640The @dtype@ property prevents \emph{implicit} copy operations and the @is_monitor@ trait provides no \emph{explicit} copy operations, so monitors must be passed by reference (pointer).
1641% Copying 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.
1642% Copying 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.
1643Similarly, the function definitions ensures there is a mechanism to get (read) the monitor descriptor from its handle, and a special destructor to prevent deallocation if a thread using the shared data.
1644The custom monitor type also inserts any locks needed to implement the mutual exclusion semantics.
1645
1646
1647\subsection{Mutex Acquisition}
1648\label{s:MutexAcquisition}
1649
1650While the monitor lock provides mutual exclusion for shared data, there are implementation options for when and where the locking/unlocking occurs.
1651(Much of this discussion also applies to basic locks.)
1652For example, a monitor may be passed through multiple helper functions before it is necessary to acquire the monitor's mutual exclusion.
1653
1654The benefit of mandatory monitor qualifiers is self-documentation, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameters is redundant.
1655Instead, the semantics has one qualifier as the default and the other required.
1656For example, make the safe @mutex@ qualifier the default because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
1657Alternatively, make the unsafe \lstinline[morekeywords=nomutex]@nomutex@ qualifier the default because it is the \emph{normal} parameter semantics while @mutex@ parameters are rare.
1658Providing a default qualifier implies knowing whether a parameter is a monitor.
1659Since \CFA relies heavily on traits as an abstraction mechanism, types can coincidentally match the monitor trait but not be a monitor, similar to inheritance where a shape and playing card can both be drawable.
1660For 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@.
1661
1662The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@.
1663The following has monitor parameter types that are composed of multiple objects.
1664\begin{cfa}
1665monitor M { ... }
1666int f1( M & mutex m ); $\C{// single parameter object}$
1667int f2( M * mutex m ); $\C{// single or multiple parameter object}$
1668int f3( M * mutex m[$\,$] ); $\C{// multiple parameter object}$
1669int f4( stack( M * ) & mutex m ); $\C{// multiple parameters object}$
1670\end{cfa}
1671Function @f1@ has a single parameter object, while @f2@'s indirection could be a single or multi-element array, where static array size is often unknown in C.
1672Function @f3@ has a multiple object matrix, and @f4@ a multiple object data structure.
1673While shown shortly, multiple object acquisition is possible, but the number of objects must be statically known.
1674Therefore, \CFA only acquires one monitor per parameter with at most one level of indirection, excluding pointers as it is impossible to statically determine the size.
1675
1676For object-oriented monitors, \eg Java, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
1677\CFA has no receiver, and hence, the explicit @mutex@ qualifier is used to specify which objects acquire mutual exclusion.
1678A positive consequence of this design decision is the ability to support multi-monitor functions,\footnote{
1679While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.}
1680called \newterm{bulk acquire}.
1681\CFA guarantees acquisition order is consistent across calls to @mutex@ functions using the same monitors as arguments, so acquiring multiple monitors is safe from deadlock.
1682Figure~\ref{f:BankTransfer} shows a trivial solution to the bank transfer problem~\cite{BankTransfer}, where two resources must be locked simultaneously, using \CFA monitors with implicit locking and \CC with explicit locking.
1683A \CFA programmer only has to manage when to acquire mutual exclusion;
1684a \CC programmer must select the correct lock and acquisition mechanism from a panoply of locking options.
1685Making good choices for common cases in \CFA simplifies the programming experience and enhances safety.
1686
1687\begin{figure}
1688\centering
1689\begin{lrbox}{\myboxA}
1690\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1691monitor BankAccount {
1692
1693        int balance;
1694} b1 = { 0 }, b2 = { 0 };
1695void deposit( BankAccount & `mutex` b,
1696                        int deposit ) with(b) {
1697        balance += deposit;
1698}
1699void transfer( BankAccount & `mutex` my,
1700        BankAccount & `mutex` your, int me2you ) {
1701
1702        deposit( my, -me2you ); // debit
1703        deposit( your, me2you ); // credit
1704}
1705`thread` Person { BankAccount & b1, & b2; };
1706void main( Person & person ) with(person) {
1707        for ( 10_000_000 ) {
1708                if ( random() % 3 ) deposit( b1, 3 );
1709                if ( random() % 3 ) transfer( b1, b2, 7 );
1710        }
1711}
1712int main() {
1713        `Person p1 = { b1, b2 }, p2 = { b2, b1 };`
1714
1715} // wait for threads to complete
1716\end{cfa}
1717\end{lrbox}
1718
1719\begin{lrbox}{\myboxB}
1720\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1721struct BankAccount {
1722        `recursive_mutex m;`
1723        int balance = 0;
1724} b1, b2;
1725void deposit( BankAccount & b, int deposit ) {
1726        `scoped_lock lock( b.m );`
1727        b.balance += deposit;
1728}
1729void transfer( BankAccount & my,
1730                        BankAccount & your, int me2you ) {
1731        `scoped_lock lock( my.m, your.m );`
1732        deposit( my, -me2you ); // debit
1733        deposit( your, me2you ); // credit
1734}
1735
1736void person( BankAccount & b1, BankAccount & b2 ) {
1737        for ( int i = 0; i < 10$'$000$'$000; i += 1 ) {
1738                if ( random() % 3 ) deposit( b1, 3 );
1739                if ( random() % 3 ) transfer( b1, b2, 7 );
1740        }
1741}
1742int main() {
1743        `thread p1(person, ref(b1), ref(b2)), p2(person, ref(b2), ref(b1));`
1744        `p1.join(); p2.join();`
1745}
1746\end{cfa}
1747\end{lrbox}
1748
1749\subfloat[\CFA]{\label{f:CFABank}\usebox\myboxA}
1750\hspace{3pt}
1751\vrule
1752\hspace{3pt}
1753\subfloat[\CC]{\label{f:C++Bank}\usebox\myboxB}
1754\hspace{3pt}
1755\caption{Bank transfer problem}
1756\label{f:BankTransfer}
1757\end{figure}
1758
1759Users can still force the acquiring order by using @mutex@/\lstinline[morekeywords=nomutex]@nomutex@.
1760\begin{cfa}
1761void foo( M & mutex m1, M & mutex m2 ); $\C{// acquire m1 and m2}$
1762void bar( M & mutex m1, M & /* nomutex */ m2 ) { $\C{// acquire m1}$
1763        ... foo( m1, m2 ); ... $\C{// acquire m2}$
1764}
1765void baz( M & /* nomutex */ m1, M & mutex m2 ) { $\C{// acquire m2}$
1766        ... foo( m1, m2 ); ... $\C{// acquire m1}$
1767}
1768\end{cfa}
1769The bulk-acquire semantics allow @bar@ or @baz@ to acquire a monitor lock and reacquire it in @foo@.
1770The calls to @bar@ and @baz@ acquired the monitors in opposite order, possibly resulting in deadlock.
1771However, this case is the simplest instance of the \emph{nested-monitor problem}~\cite{Lister77}, where monitors are acquired in sequence versus bulk.
1772Detecting the nested-monitor problem requires dynamic tracking of monitor calls, and dealing with it requires rollback semantics~\cite{Dice10}.
1773\CFA does not deal with this fundamental problem.
1774
1775Finally, like Java, \CFA offers an alternative @mutex@ statement to reduce refactoring and naming.
1776\begin{cquote}
1777\renewcommand{\arraystretch}{0.0}
1778\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
1779\multicolumn{1}{c}{\textbf{\lstinline@mutex@ call}} & \multicolumn{1}{c}{\lstinline@mutex@ \textbf{statement}} \\
1780\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1781monitor M { ... };
1782void foo( M & mutex m1, M & mutex m2 ) {
1783        // critical section
1784}
1785void bar( M & m1, M & m2 ) {
1786        foo( m1, m2 );
1787}
1788\end{cfa}
1789&
1790\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1791
1792void bar( M & m1, M & m2 ) {
1793        mutex( m1, m2 ) {       // remove refactoring and naming
1794                // critical section
1795        }
1796}
1797
1798\end{cfa}
1799\end{tabular}
1800\end{cquote}
1801
1802
1803\subsection{Scheduling}
1804\label{s:Scheduling}
1805
1806% There are many aspects of scheduling in a concurrency system, all related to resource utilization by waiting threads, \ie which thread gets the resource next.
1807% Different forms of scheduling include access to processors by threads (see Section~\ref{s:RuntimeStructureCluster}), another is access to a shared resource by a lock or monitor.
1808This section discusses monitor scheduling for waiting threads eligible for entry, \ie which thread gets the shared resource next. (See Section~\ref{s:RuntimeStructureCluster} for scheduling threads on virtual processors.)
1809While monitor mutual-exclusion provides safe access to shared data, the monitor data may indicate that a thread accessing it cannot proceed, \eg a bounded buffer may be full/empty so produce/consumer threads must block.
1810Leaving the monitor and trying again (busy waiting) is impractical for high-level programming.
1811Monitors eliminate busy waiting by providing synchronization to schedule threads needing access to the shared data, where threads block versus spinning.
1812Synchronization is generally achieved with internal~\cite{Hoare74} or external~\cite[\S~2.9.2]{uC++} scheduling.
1813\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.
1814Finally, \CFA monitors do not allow calling threads to barge ahead of signalled threads, which simplifies synchronization among threads in the monitor and increases correctness.
1815If barging is allowed, synchronization between a signaller and signallee is difficult, often requiring additional flags and multiple unblock/block cycles.
1816In fact, signals-as-hints is completely opposite from that proposed by Hoare in the seminal paper on monitors~\cite[p.~550]{Hoare74}.
1817% \begin{cquote}
1818% However, 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.
1819% It 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}
1820% \end{cquote}
1821Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implicit form of self barging.
1822Hence, a \CFA @wait@ statement is not enclosed in a @while@ loop retesting a blocking predicate, which can cause thread starvation due to barging.
1823
1824Figure~\ref{f:MonitorScheduling} shows general internal/external scheduling (for the bounded-buffer example in Figure~\ref{f:InternalExternalScheduling}).
1825External calling threads block on the calling queue, if the monitor is occupied, otherwise they enter in FIFO order.
1826Internal threads block on condition queues via @wait@ and reenter from the condition in FIFO order.
1827Alternatively, internal threads block on urgent from the @signal_block@ or @waitfor@, and reenter implicitly when the monitor becomes empty, \ie, the thread in the monitor exits or waits.
1828
1829There are three signalling mechanisms to unblock waiting threads to enter the monitor.
1830Note, signalling cannot have the signaller and signalled thread in the monitor simultaneously because of the mutual exclusion, so either the signaller or signallee can proceed.
1831For internal scheduling, threads are unblocked from condition queues using @signal@, where the signallee is moved to urgent and the signaller continues (solid line).
1832Multiple signals move multiple signallees to urgent until the condition is empty.
1833When the signaller exits or waits, a thread blocked on urgent is processed before calling threads to prevent barging.
1834(Java conceptually moves the signalled thread to the calling queue, and hence, allows barging.)
1835The alternative unblock is in the opposite order using @signal_block@, where the signaller is moved to urgent and the signallee continues (dashed line), and is implicitly unblocked from urgent when the signallee exits or waits.
1836
1837For external scheduling, the condition queues are not used;
1838instead threads are unblocked directly from the calling queue using @waitfor@ based on function names requesting mutual exclusion.
1839(The linear search through the calling queue to locate a particular call can be reduced to $O(1)$.)
1840The @waitfor@ has the same semantics as @signal_block@, where the signalled thread executes before the signallee, which waits on urgent.
1841Executing multiple @waitfor@s from different signalled functions causes the calling threads to move to urgent.
1842External scheduling requires urgent to be a stack, because the signaller expects to execute immediately after the specified monitor call has exited or waited.
1843Internal scheduling behaves the same for an urgent stack or queue, except for multiple signalling, where the threads unblock from urgent in reverse order from signalling.
1844If the restart order is important, multiple signalling by a signal thread can be transformed into daisy-chain signalling among threads, where each thread signals the next thread.
1845We tried both a stack for @waitfor@ and queue for signalling, but that resulted in complex semantics about which thread enters next.
1846Hence, \CFA uses a single urgent stack to correctly handle @waitfor@ and adequately support both forms of signalling.
1847
1848\begin{figure}
1849\centering
1850% \subfloat[Scheduling Statements] {
1851% \label{fig:SchedulingStatements}
1852% {\resizebox{0.45\textwidth}{!}{\input{CondSigWait.pstex_t}}}
1853\input{CondSigWait.pstex_t}
1854% }% subfloat
1855% \quad
1856% \subfloat[Bulk acquire monitor] {
1857% \label{fig:BulkMonitor}
1858% {\resizebox{0.45\textwidth}{!}{\input{ext_monitor.pstex_t}}}
1859% }% subfloat
1860\caption{Monitor Scheduling}
1861\label{f:MonitorScheduling}
1862\end{figure}
1863
1864Figure~\ref{f:BBInt} shows a \CFA generic bounded-buffer with internal scheduling, where producers/consumers enter the monitor, detect the buffer is full/empty, and block on an appropriate condition variable, @full@/@empty@.
1865The @wait@ function atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the function's parameter list.
1866The appropriate condition variable is signalled to unblock an opposite kind of thread after an element is inserted/removed from the buffer.
1867Signalling is unconditional, because signalling an empty condition variable does nothing.
1868It is common to declare condition variables as monitor fields to prevent shared access, hence no locking is required for access as the conditions are protected by the monitor lock.
1869In \CFA, a condition variable can be created/stored independently.
1870% To still prevent expensive locking on access, a condition variable is tied to a \emph{group} of monitors on first use, called \newterm{branding}, resulting in a low-cost boolean test to detect sharing from other monitors.
1871
1872% Signalling semantics cannot have the signaller and signalled thread in the monitor simultaneously, which means:
1873% \begin{enumerate}
1874% \item
1875% The signalling thread returns immediately and the signalled thread continues.
1876% \item
1877% The signalling thread continues and the signalled thread is marked for urgent unblocking at the next scheduling point (exit/wait).
1878% \item
1879% The signalling thread blocks but is marked for urgent unblocking at the next scheduling point and the signalled thread continues.
1880% \end{enumerate}
1881% The first approach is too restrictive, as it precludes solving a reasonable class of problems, \eg dating service (see Figure~\ref{f:DatingService}).
1882% \CFA supports the next two semantics as both are useful.
1883
1884\begin{figure}
1885\centering
1886\newbox\myboxA
1887\begin{lrbox}{\myboxA}
1888\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1889forall( otype T ) { // distribute forall
1890        monitor Buffer {
1891                `condition` full, empty;
1892                int front, back, count;
1893                T elements[10];
1894        };
1895        void ?{}( Buffer(T) & buffer ) with(buffer) {
1896                front = back = count = 0;
1897        }
1898        void insert( Buffer(T) & mutex buffer, T elem )
1899                                with(buffer) {
1900                if ( count == 10 ) `wait( empty )`;
1901                // insert elem into buffer
1902                `signal( full )`;
1903        }
1904        T remove( Buffer(T) & mutex buffer ) with(buffer) {
1905                if ( count == 0 ) `wait( full )`;
1906                // remove elem from buffer
1907                `signal( empty )`;
1908                return elem;
1909        }
1910}
1911\end{cfa}
1912\end{lrbox}
1913
1914% \newbox\myboxB
1915% \begin{lrbox}{\myboxB}
1916% \begin{cfa}[aboveskip=0pt,belowskip=0pt]
1917% forall( otype T ) { // distribute forall
1918%       monitor Buffer {
1919%
1920%               int front, back, count;
1921%               T elements[10];
1922%       };
1923%       void ?{}( Buffer(T) & buffer ) with(buffer) {
1924%               [front, back, count] = 0;
1925%       }
1926%       T remove( Buffer(T) & mutex buffer ); // forward
1927%       void insert( Buffer(T) & mutex buffer, T elem )
1928%                               with(buffer) {
1929%               if ( count == 10 ) `waitfor( remove, buffer )`;
1930%               // insert elem into buffer
1931%
1932%       }
1933%       T remove( Buffer(T) & mutex buffer ) with(buffer) {
1934%               if ( count == 0 ) `waitfor( insert, buffer )`;
1935%               // remove elem from buffer
1936%
1937%               return elem;
1938%       }
1939% }
1940% \end{cfa}
1941% \end{lrbox}
1942
1943\newbox\myboxB
1944\begin{lrbox}{\myboxB}
1945\begin{cfa}[aboveskip=0pt,belowskip=0pt]
1946monitor ReadersWriter {
1947        int rcnt, wcnt; // readers/writer using resource
1948};
1949void ?{}( ReadersWriter & rw ) with(rw) {
1950        rcnt = wcnt = 0;
1951}
1952void EndRead( ReadersWriter & mutex rw ) with(rw) {
1953        rcnt -= 1;
1954}
1955void EndWrite( ReadersWriter & mutex rw ) with(rw) {
1956        wcnt = 0;
1957}
1958void StartRead( ReadersWriter & mutex rw ) with(rw) {
1959        if ( wcnt > 0 ) `waitfor( EndWrite, rw );`
1960        rcnt += 1;
1961}
1962void StartWrite( ReadersWriter & mutex rw ) with(rw) {
1963        if ( wcnt > 0 ) `waitfor( EndWrite, rw );`
1964        else while ( rcnt > 0 ) `waitfor( EndRead, rw );`
1965        wcnt = 1;
1966}
1967
1968\end{cfa}
1969\end{lrbox}
1970
1971\subfloat[Generic bounded buffer, internal scheduling]{\label{f:BBInt}\usebox\myboxA}
1972\hspace{3pt}
1973\vrule
1974\hspace{3pt}
1975\subfloat[Readers / writer lock, external scheduling]{\label{f:RWExt}\usebox\myboxB}
1976
1977\caption{Internal / external scheduling}
1978\label{f:InternalExternalScheduling}
1979\end{figure}
1980
1981Figure~\ref{f:BBInt} can be transformed into external scheduling by removing the condition variables and signals/waits, and adding the following lines at the locations of the current @wait@s in @insert@/@remove@, respectively.
1982\begin{cfa}[aboveskip=2pt,belowskip=1pt]
1983if ( count == 10 ) `waitfor( remove, buffer )`;       |      if ( count == 0 ) `waitfor( insert, buffer )`;
1984\end{cfa}
1985Here, the producers/consumers detects a full/\-empty buffer and prevents more producers/consumers from entering the monitor until there is a free/empty slot in the buffer.
1986External scheduling is controlled by the @waitfor@ statement, which atomically blocks the calling thread, releases the monitor lock, and restricts the function calls that can next acquire mutual exclusion.
1987If 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.
1988Threads calling excluded functions block outside of (external to) the monitor on the calling queue, versus blocking on condition queues inside of (internal to) the monitor.
1989Figure~\ref{f:RWExt} shows a readers/writer lock written using external scheduling, where a waiting reader detects a writer using the resource and restricts further calls until the writer exits by calling @EndWrite@.
1990The writer does a similar action for each reader or writer using the resource.
1991Note, no new calls to @StarRead@/@StartWrite@ may occur when waiting for the call to @EndRead@/@EndWrite@.
1992External scheduling allows waiting for events from other threads while restricting unrelated events, that would otherwise have to wait on conditions in the monitor.
1993The mechnaism can be done in terms of control flow, \eg Ada @accept@ or \uC @_Accept@, or in terms of data, \eg Go @select@ on channels.
1994While both mechanisms have strengths and weaknesses, this project uses the control-flow mechanism to be consistent with other language features.
1995% Two challenges specific to \CFA for external scheduling are loose object-definitions (see Section~\ref{s:LooseObjectDefinitions}) and multiple-monitor functions (see Section~\ref{s:Multi-MonitorScheduling}).
1996
1997Figure~\ref{f:DatingService} shows a dating service demonstrating non-blocking and blocking signalling.
1998The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers.
1999A thread blocks until an appropriate partner arrives.
2000The complexity is exchanging phone numbers in the monitor because of the mutual-exclusion property.
2001For 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.
2002For 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.
2003The 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;
2004as well, an arriving thread may not find a partner and must wait, which requires a condition variable, and condition variables imply internal scheduling.
2005Furthermore, barging corrupts the dating service during an exchange because a barger may also match and change the phone numbers, invalidating the previous exchange phone number.
2006Putting loops around the @wait@s does not correct the problem;
2007the simple solution must be restructured to account for barging.
2008
2009\begin{figure}
2010\centering
2011\newbox\myboxA
2012\begin{lrbox}{\myboxA}
2013\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2014enum { CCodes = 20 };
2015monitor DS {
2016        int GirlPhNo, BoyPhNo;
2017        condition Girls[CCodes], Boys[CCodes];
2018        `condition exchange;`
2019};
2020int girl( DS & mutex ds, int phNo, int ccode ) {
2021        if ( is_empty( Boys[ccode] ) ) {
2022                wait( Girls[ccode] );
2023                GirlPhNo = phNo;
2024                `signal( exchange );`
2025        } else {
2026                GirlPhNo = phNo;
2027                `signal( Boys[ccode] );`
2028                `wait( exchange );`
2029        }
2030        return BoyPhNo;
2031}
2032int boy( DS & mutex ds, int phNo, int ccode ) {
2033        // as above with boy/girl interchanged
2034}
2035\end{cfa}
2036\end{lrbox}
2037
2038\newbox\myboxB
2039\begin{lrbox}{\myboxB}
2040\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2041
2042monitor DS {
2043        int GirlPhNo, BoyPhNo;
2044        condition Girls[CCodes], Boys[CCodes];
2045
2046};
2047int girl( DS & mutex ds, int phNo, int ccode ) {
2048        if ( is_empty( Boys[ccode] ) ) { // no compatible
2049                wait( Girls[ccode] ); // wait for boy
2050                GirlPhNo = phNo; // make phone number available
2051
2052        } else {
2053                GirlPhNo = phNo; // make phone number available
2054                `signal_block( Boys[ccode] );` // restart boy
2055
2056        } // if
2057        return BoyPhNo;
2058}
2059int boy( DS & mutex ds, int phNo, int ccode ) {
2060        // as above with boy/girl interchanged
2061}
2062\end{cfa}
2063\end{lrbox}
2064
2065\subfloat[\lstinline@signal@]{\label{f:DatingSignal}\usebox\myboxA}
2066\qquad
2067\subfloat[\lstinline@signal_block@]{\label{f:DatingSignalBlock}\usebox\myboxB}
2068\caption{Dating service}
2069\label{f:DatingService}
2070\end{figure}
2071
2072In summation, for internal scheduling, non-blocking signalling (as in the producer/consumer example) is used when the signaller is providing the cooperation for a waiting thread;
2073the 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.
2074The waiter unblocks next from the urgent queue, uses/takes the state, and exits the monitor.
2075Blocking signal is the reverse, where the waiter is providing the cooperation for the signalling thread;
2076the 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.
2077The waiter changes state and exits the monitor, and the signaller unblocks next from the urgent queue to use/take the state.
2078
2079Both internal and external scheduling extend to multiple monitors in a natural way.
2080\begin{cquote}
2081\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
2082\begin{cfa}
2083monitor M { `condition e`; ... };
2084void foo( M & mutex m1, M & mutex m2 ) {
2085        ... wait( `e` ); ...   // wait( e, m1, m2 )
2086        ... wait( `e, m1` ); ...
2087        ... wait( `e, m2` ); ...
2088}
2089\end{cfa}
2090&
2091\begin{cfa}
2092void rtn$\(_1\)$( M & mutex m1, M & mutex m2 );
2093void rtn$\(_2\)$( M & mutex m1 );
2094void bar( M & mutex m1, M & mutex m2 ) {
2095        ... waitfor( `rtn` ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\), m1, m2 )}$
2096        ... waitfor( `rtn, m1` ); ... // $\LstCommentStyle{waitfor( rtn\(_2\), m1 )}$
2097}
2098\end{cfa}
2099\end{tabular}
2100\end{cquote}
2101For @wait( e )@, the default semantics is to atomically block the signaller and release all acquired mutex parameters, \ie @wait( e, m1, m2 )@.
2102To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
2103Wait cannot statically verifies the released monitors are the acquired mutex-parameters without disallowing separately compiled helper functions calling @wait@.
2104While \CC supports bulk locking, @wait@ only accepts a single lock for a condition variable, so bulk locking with condition variables is asymmetric.
2105Finally, a signaller,
2106\begin{cfa}
2107void baz( M & mutex m1, M & mutex m2 ) {
2108        ... signal( e ); ...
2109}
2110\end{cfa}
2111must have acquired at least the same locks as the waiting thread signalled from a condition queue to allow the locks to be passed, and hence, prevent barging.
2112
2113Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex parameters, \ie @waitfor( rtn, m1, m2 )@.
2114To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn, m1 )@.
2115@waitfor@ does statically verify the monitor types passed are the same as the acquired mutex-parameters of the given function or function pointer, hence the function (pointer) prototype must be accessible.
2116% When an overloaded function appears in an @waitfor@ statement, calls to any function with that name are accepted.
2117% The rationale is that members with the same name should perform a similar function, and therefore, all should be eligible to accept a call.
2118Overloaded functions can be disambiguated using a cast
2119\begin{cfa}
2120void rtn( M & mutex m );
2121`int` rtn( M & mutex m );
2122waitfor( (`int` (*)( M & mutex ))rtn, m );
2123\end{cfa}
2124
2125The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock.
2126\begin{cfa}
2127void foo( M & mutex m1, M & mutex m2 ) {
2128        ... wait( `e, m1` ); ...                                $\C{// release m1, keeping m2 acquired )}$
2129void bar( M & mutex m1, M & mutex m2 ) {        $\C{// must acquire m1 and m2 )}$
2130        ... signal( `e` ); ...
2131\end{cfa}
2132The @wait@ only releases @m1@ so the signalling thread cannot acquire @m1@ and @m2@ to enter @bar@ and @signal@ the condition.
2133While deadlock can occur with multiple/nesting acquisition, this is a consequence of locks, and by extension monitors, not being perfectly composable.
2134
2135
2136
2137\subsection{\texorpdfstring{Extended \protect\lstinline@waitfor@}{Extended waitfor}}
2138
2139Figure~\ref{f:ExtendedWaitfor} shows the extended form of the @waitfor@ statement to conditionally accept one of a group of mutex functions, with an optional statement to be performed \emph{after} the mutex function finishes.
2140For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding member(s) must exist.
2141The \emph{conditional-expression} of a @when@ may call a function, but the function must not block or context switch.
2142If there are multiple acceptable mutex calls, selection occurs top-to-bottom (prioritized) among the @waitfor@ clauses, whereas some programming languages with similar mechanisms accept nondeterministically for this case, \eg Go \lstinline[morekeywords=select]@select@.
2143If some accept guards are true and there are no outstanding calls to these members, the acceptor is blocked until a call to one of these members is made.
2144If there is a @timeout@ clause, it provides an upper bound on waiting.
2145If 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.
2146Hence, the terminating @else@ clause allows a conditional attempt to accept a call without blocking.
2147If both @timeout@ and @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered.
2148There is also a traditional future wait queue (not shown) (\eg Microsoft (@WaitForMultipleObjects@)), to wait for a specified number of future elements in the queue.
2149
2150\begin{figure}
2151\centering
2152\begin{cfa}
2153`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
2154        waitfor( $\emph{mutex-member-name}$ ) $\emph{statement}$ $\C{// action after call}$
2155`or` `when` ( $\emph{conditional-expression}$ ) $\C{// any number of functions}$
2156        waitfor( $\emph{mutex-member-name}$ ) $\emph{statement}$
2157`or`    ...
2158`when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
2159        `timeout` $\emph{statement}$ $\C{// optional terminating timeout clause}$
2160`when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
2161        `else`  $\emph{statement}$ $\C{// optional terminating clause}$
2162\end{cfa}
2163\caption{Extended \protect\lstinline@waitfor@}
2164\label{f:ExtendedWaitfor}
2165\end{figure}
2166
2167Note, a group of conditional @waitfor@ clauses is \emph{not} the same as a group of @if@ statements, \eg:
2168\begin{cfa}
2169if ( C1 ) waitfor( mem1 );                       when ( C1 ) waitfor( mem1 );
2170else if ( C2 ) waitfor( mem2 );         or when ( C2 ) waitfor( mem2 );
2171\end{cfa}
2172The left example only accepts @mem1@ if @C1@ is true or only @mem2@ if @C2@ is true.
2173The right example accepts either @mem1@ or @mem2@ if @C1@ and @C2@ are true.
2174
2175An interesting use of @waitfor@ is accepting the @mutex@ destructor to know when an object is deallocated, \eg assume the bounded buffer is restructred from a monitor to a thread with the following @main@.
2176\begin{cfa}
2177void main( Buffer(T) & buffer ) with(buffer) {
2178        for () {
2179                `waitfor( ^?{}, buffer )` break;
2180                or when ( count != 20 ) waitfor( insert, buffer ) { ... }
2181                or when ( count != 0 ) waitfor( remove, buffer ) { ... }
2182        }
2183        // clean up
2184}
2185\end{cfa}
2186When the program main deallocates the buffer, it first calls the buffer's destructor, which is accepted, the destructor runs, and the buffer is deallocated.
2187However, the buffer thread cannot continue after the destructor call because the object is gone;
2188hence, clean up in @main@ cannot occur, which means destructors for local objects are not run.
2189To make this useful capability work, the semantics for accepting the destructor is the same as @signal@, \ie the destructor call is placed on urgent and the acceptor continues execution, which ends the loop, cleans up, and the thread terminates.
2190Then, the destructor caller unblocks from urgent to deallocate the object.
2191Accepting the destructor is the idiomatic way in \CFA to terminate a thread performing direct communication.
2192
2193
2194\subsection{Bulk Barging Prevention}
2195
2196Figure~\ref{f:BulkBargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signalling semantics.
2197The complexity begins at the end of the inner @mutex@ statement, where the semantics of internal scheduling need to be extended for multiple monitors.
2198The problem is that bulk acquire is used in the inner @mutex@ statement where one of the monitors is already acquired.
2199When 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.
2200However, both the signalling and waiting threads W1 and W2 need some subset of monitors @m1@ and @m2@.
2201\begin{cquote}
2202condition c: (order 1) W2(@m2@), W1(@m1@,@m2@)\ \ \ or\ \ \ (order 2) W1(@m1@,@m2@), W2(@m2@) \\
2203S: acq. @m1@ $\rightarrow$ acq. @m1,m2@ $\rightarrow$ @signal(c)@ $\rightarrow$ rel. @m2@ $\rightarrow$ pass @m2@ unblock W2 (order 2) $\rightarrow$ rel. @m1@ $\rightarrow$ pass @m1,m2@ unblock W1 \\
2204\hspace*{2.75in}$\rightarrow$ rel. @m1@ $\rightarrow$ pass @m1,m2@ unblock W1 (order 1)
2205\end{cquote}
2206
2207\begin{figure}
2208\newbox\myboxA
2209\begin{lrbox}{\myboxA}
2210\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2211monitor M m1, m2;
2212condition c;
2213mutex( m1 ) { // $\LstCommentStyle{\color{red}outer}$
2214        ...
2215        mutex( m1, m2 ) { // $\LstCommentStyle{\color{red}inner}$
2216                ... `signal( c )`; ...
2217                // m1, m2 still acquired
2218        } // $\LstCommentStyle{\color{red}release m2}$
2219        // m1 acquired
2220} // release m1
2221\end{cfa}
2222\end{lrbox}
2223
2224\newbox\myboxB
2225\begin{lrbox}{\myboxB}
2226\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2227
2228
2229mutex( m1 ) {
2230        ...
2231        mutex( m1, m2 ) {
2232                ... `wait( c )`; // release m1, m2
2233                // m1, m2 reacquired
2234        } // $\LstCommentStyle{\color{red}release m2}$
2235        // m1 acquired
2236} // release m1
2237\end{cfa}
2238\end{lrbox}
2239
2240\newbox\myboxC
2241\begin{lrbox}{\myboxC}
2242\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2243
2244
2245mutex( m2 ) {
2246        ... `wait( c )`; // release m2
2247        // m2 reacquired
2248} // $\LstCommentStyle{\color{red}release m2}$
2249
2250
2251
2252
2253\end{cfa}
2254\end{lrbox}
2255
2256\begin{cquote}
2257\subfloat[Signalling Thread (S)]{\label{f:SignallingThread}\usebox\myboxA}
2258\hspace{3\parindentlnth}
2259\subfloat[Waiting Thread (W1)]{\label{f:WaitingThread}\usebox\myboxB}
2260\hspace{2\parindentlnth}
2261\subfloat[Waiting Thread (W2)]{\label{f:OtherWaitingThread}\usebox\myboxC}
2262\end{cquote}
2263\caption{Bulk Barging Prevention}
2264\label{f:BulkBargingPrevention}
2265\end{figure}
2266
2267One scheduling solution is for the signaller S 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.
2268However, this solution is inefficient if W2 waited first and can be immediate passed @m2@ when released, while S retains @m1@ until completion of the outer mutex statement.
2269If W1 waited first, the signaller must retain @m1@ amd @m2@ until completion of the outer mutex statement and then pass both to W1.
2270% Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
2271To support this efficient semantics (and prevent barging), the implementation maintains a list of monitors acquired for each blocked thread.
2272When a signaller exits or waits in a monitor function/statement, the front waiter on urgent is unblocked if all its monitors are released.
2273Implementing a fast subset check for the necessary released monitors is important.
2274% The 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.
2275
2276
2277\subsection{Loose Object Definitions}
2278\label{s:LooseObjectDefinitions}
2279
2280In an object-oriented programming language, a class includes an exhaustive list of operations.
2281A new class can add members via static inheritance but the subclass still has an exhaustive list of operations.
2282(Dynamic member adding, \eg JavaScript~\cite{JavaScript}, is not considered.)
2283In the object-oriented scenario, the type and all its operators are always present at compilation (even separate compilation), so it is possible to number the operations in a bit mask and use an $O(1)$ compare with a similar bit mask created for the operations specified in a @waitfor@.
2284
2285However, in \CFA, monitor functions can be statically added/removed in translation units, making a fast subset check difficult.
2286\begin{cfa}
2287        monitor M { ... }; // common type, included in .h file
2288translation unit 1
2289        void `f`( M & mutex m );
2290        void g( M & mutex m ) { waitfor( `f`, m ); }
2291translation unit 2
2292        void `f`( M & mutex m ); $\C{// replacing f and g for type M in this translation unit}$
2293        void `g`( M & mutex m );
2294        void h( M & mutex m ) { waitfor( `f`, m ) or waitfor( `g`, m ); } $\C{// extending type M in this translation unit}$
2295\end{cfa}
2296The @waitfor@ statements in each translation unit cannot form a unique bit-mask because the monitor type does not carry that information.
2297Hence, function pointers are used to identify the functions listed in the @waitfor@ statement, stored in a variable-sized array.
2298Then, the same implementation approach used for the urgent stack is used for the calling queue.
2299Each caller has a list of monitors acquired, and the @waitfor@ statement performs a (usually short) linear search matching functions in the @waitfor@ list with called functions, and then verifying the associated mutex locks can be transfers.
2300(A possible way to construct a dense mapping is at link or load-time.)
2301
2302
2303\subsection{Multi-Monitor Scheduling}
2304\label{s:Multi-MonitorScheduling}
2305
2306External scheduling, like internal scheduling, becomes significantly more complex for multi-monitor semantics.
2307Even in the simplest case, new semantics need to be established.
2308\begin{cfa}
2309monitor M { ... };
2310void f( M & mutex m1 );
2311void g( M & mutex m1, M & mutex m2 ) { `waitfor( f );` } $\C{// pass m1 or m2 to f?}$
2312\end{cfa}
2313The solution is for the programmer to disambiguate:
2314\begin{cfa}
2315waitfor( f, `m2` ); $\C{// wait for call to f with argument m2}$
2316\end{cfa}
2317Both locks are acquired by function @g@, so when function @f@ is called, the lock for monitor @m2@ is passed from @g@ to @f@, while @g@ still holds lock @m1@.
2318This behaviour can be extended to the multi-monitor @waitfor@ statement.
2319\begin{cfa}
2320monitor M { ... };
2321void f( M & mutex m1, M & mutex m2 );
2322void g( M & mutex m1, M & mutex m2 ) { waitfor( f, `m1, m2` ); $\C{// wait for call to f with arguments m1 and m2}$
2323\end{cfa}
2324Again, the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired by the accepting function.
2325Also, the order of the monitors in a @waitfor@ statement is unimportant.
2326
2327Figure~\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.
2328For both examples, the set of monitors is disjoint so unblocking is impossible.
2329
2330\begin{figure}
2331\centering
2332\begin{lrbox}{\myboxA}
2333\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2334monitor M1 {} m11, m12;
2335monitor M2 {} m2;
2336condition c;
2337void f( M1 & mutex m1, M2 & mutex m2 ) {
2338        signal( c );
2339}
2340void g( M1 & mutex m1, M2 & mutex m2 ) {
2341        wait( c );
2342}
2343g( `m11`, m2 ); // block on wait
2344f( `m12`, m2 ); // cannot fulfil
2345\end{cfa}
2346\end{lrbox}
2347
2348\begin{lrbox}{\myboxB}
2349\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2350monitor M1 {} m11, m12;
2351monitor M2 {} m2;
2352
2353void f( M1 & mutex m1, M2 & mutex m2 ) {
2354
2355}
2356void g( M1 & mutex m1, M2 & mutex m2 ) {
2357        waitfor( f, m1, m2 );
2358}
2359g( `m11`, m2 ); // block on accept
2360f( `m12`, m2 ); // cannot fulfil
2361\end{cfa}
2362\end{lrbox}
2363\subfloat[Internal scheduling]{\label{f:InternalScheduling}\usebox\myboxA}
2364\hspace{3pt}
2365\vrule
2366\hspace{3pt}
2367\subfloat[External scheduling]{\label{f:ExternalScheduling}\usebox\myboxB}
2368\caption{Unmatched \protect\lstinline@mutex@ sets}
2369\label{f:UnmatchedMutexSets}
2370\end{figure}
2371
2372
2373\subsection{\texorpdfstring{\protect\lstinline@mutex@ Threads}{mutex Threads}}
2374
2375Threads in \CFA can also be monitors to allow \emph{direct communication} among threads, \ie threads can have mutex functions that are called by other threads.
2376Hence, all monitor features are available when using threads.
2377Figure~\ref{f:DirectCommunication} shows a comparison of direct call communication in \CFA with direct channel communication in Go.
2378(Ada provides a similar mechanism to the \CFA direct communication.)
2379The program main in both programs communicates directly with the other thread versus indirect communication where two threads interact through a passive monitor.
2380Both direct and indirection thread communication are valuable tools in structuring concurrent programs.
2381
2382\begin{figure}
2383\centering
2384\begin{lrbox}{\myboxA}
2385\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2386
2387struct Msg { int i, j; };
2388thread GoRtn { int i;  float f;  Msg m; };
2389void mem1( GoRtn & mutex gortn, int i ) { gortn.i = i; }
2390void mem2( GoRtn & mutex gortn, float f ) { gortn.f = f; }
2391void mem3( GoRtn & mutex gortn, Msg m ) { gortn.m = m; }
2392void ^?{}( GoRtn & mutex ) {}
2393
2394void main( GoRtn & gortn ) with( gortn ) {  // thread starts
2395
2396        for () {
2397
2398                `waitfor( mem1, gortn )` sout | i;  // wait for calls
2399                or `waitfor( mem2, gortn )` sout | f;
2400                or `waitfor( mem3, gortn )` sout | m.i | m.j;
2401                or `waitfor( ^?{}, gortn )` break;
2402
2403        }
2404
2405}
2406int main() {
2407        GoRtn gortn; $\C[2.0in]{// start thread}$
2408        `mem1( gortn, 0 );` $\C{// different calls}\CRT$
2409        `mem2( gortn, 2.5 );`
2410        `mem3( gortn, (Msg){1, 2} );`
2411
2412
2413} // wait for completion
2414\end{cfa}
2415\end{lrbox}
2416
2417\begin{lrbox}{\myboxB}
2418\begin{Go}[aboveskip=0pt,belowskip=0pt]
2419func main() {
2420        type Msg struct{ i, j int }
2421
2422        ch1 := make( chan int )
2423        ch2 := make( chan float32 )
2424        ch3 := make( chan Msg )
2425        hand := make( chan string )
2426        shake := make( chan string )
2427        gortn := func() { $\C[1.5in]{// thread starts}$
2428                var i int;  var f float32;  var m Msg
2429                L: for {
2430                        select { $\C{// wait for messages}$
2431                          case `i = <- ch1`: fmt.Println( i )
2432                          case `f = <- ch2`: fmt.Println( f )
2433                          case `m = <- ch3`: fmt.Println( m )
2434                          case `<- hand`: break L $\C{// sentinel}$
2435                        }
2436                }
2437                `shake <- "SHAKE"` $\C{// completion}$
2438        }
2439
2440        go gortn() $\C{// start thread}$
2441        `ch1 <- 0` $\C{// different messages}$
2442        `ch2 <- 2.5`
2443        `ch3 <- Msg{1, 2}`
2444        `hand <- "HAND"` $\C{// sentinel value}$
2445        `<- shake` $\C{// wait for completion}\CRT$
2446}
2447\end{Go}
2448\end{lrbox}
2449
2450\subfloat[\CFA]{\label{f:CFAwaitfor}\usebox\myboxA}
2451\hspace{3pt}
2452\vrule
2453\hspace{3pt}
2454\subfloat[Go]{\label{f:Gochannel}\usebox\myboxB}
2455\caption{Direct communication}
2456\label{f:DirectCommunication}
2457\end{figure}
2458
2459\begin{comment}
2460The following shows an example of two threads directly calling each other and accepting calls from each other in a cycle.
2461\begin{cfa}
2462\end{cfa}
2463\vspace{-0.8\baselineskip}
2464\begin{cquote}
2465\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
2466\begin{cfa}
2467thread Ping {} pi;
2468void ping( Ping & mutex ) {}
2469void main( Ping & pi ) {
2470        for ( 10 ) {
2471                `waitfor( ping, pi );`
2472                `pong( po );`
2473        }
2474}
2475int main() {}
2476\end{cfa}
2477&
2478\begin{cfa}
2479thread Pong {} po;
2480void pong( Pong & mutex ) {}
2481void main( Pong & po ) {
2482        for ( 10 ) {
2483                `ping( pi );`
2484                `waitfor( pong, po );`
2485        }
2486}
2487
2488\end{cfa}
2489\end{tabular}
2490\end{cquote}
2491% \lstMakeShortInline@%
2492% \caption{Threads ping/pong using external scheduling}
2493% \label{f:pingpong}
2494% \end{figure}
2495Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start (and possibly complete) before the program main starts.
2496\end{comment}
2497
2498
2499\subsection{Execution Properties}
2500
2501Table~\ref{t:ObjectPropertyComposition} shows how the \CFA high-level constructs cover 3 fundamental execution properties: thread, stateful function, and mutual exclusion.
2502Case 1 is a basic object, with none of the new execution properties.
2503Case 2 allows @mutex@ calls to Case 1 to protect shared data.
2504Case 3 allows stateful functions to suspend/resume but restricts operations because the state is stackless.
2505Case 4 allows @mutex@ calls to Case 3 to protect shared data.
2506Cases 5 and 6 are the same as 3 and 4 without restriction because the state is stackful.
2507Cases 7 and 8 are rejected because a thread cannot execute without a stackful state in a preemptive environment when context switching from the signal handler.
2508Cases 9 and 10 have a stackful thread without and with @mutex@ calls.
2509For situations where threads do not require direct communication, case 9 provides faster creation/destruction by eliminating @mutex@ setup.
2510
2511\begin{table}
2512\caption{Object property composition}
2513\centering
2514\label{t:ObjectPropertyComposition}
2515\renewcommand{\arraystretch}{1.25}
2516%\setlength{\tabcolsep}{5pt}
2517\begin{tabular}{c|c||l|l}
2518\multicolumn{2}{c||}{object properties} & \multicolumn{2}{c}{mutual exclusion} \\
2519\hline
2520thread  & stateful                              & \multicolumn{1}{c|}{No} & \multicolumn{1}{c}{Yes} \\
2521\hline
2522\hline
2523No              & No                                    & \textbf{1}\ \ \ aggregate type                & \textbf{2}\ \ \ @monitor@ aggregate type \\
2524\hline
2525No              & Yes (stackless)               & \textbf{3}\ \ \ @generator@                   & \textbf{4}\ \ \ @monitor@ @generator@ \\
2526\hline
2527No              & Yes (stackful)                & \textbf{5}\ \ \ @coroutine@                   & \textbf{6}\ \ \ @monitor@ @coroutine@ \\
2528\hline
2529Yes             & No / Yes (stackless)  & \textbf{7}\ \ \ {\color{red}rejected} & \textbf{8}\ \ \ {\color{red}rejected} \\
2530\hline
2531Yes             & Yes (stackful)                & \textbf{9}\ \ \ @thread@                              & \textbf{10}\ \ @monitor@ @thread@ \\
2532\end{tabular}
2533\end{table}
2534
2535
2536\subsection{Low-level Locks}
2537
2538For 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.
2539Some of these low-level mechanism are used in the \CFA runtime, but we strongly advocate using high-level mechanisms whenever possible.
2540
2541
2542% \section{Parallelism}
2543% \label{s:Parallelism}
2544%
2545% Historically, computer performance was about processor speeds.
2546% However, with heat dissipation being a direct consequence of speed increase, parallelism is the new source for increased performance~\cite{Sutter05, Sutter05b}.
2547% Therefore, high-performance applications must care about parallelism, which requires concurrency.
2548% The lowest-level approach of parallelism is to use \newterm{kernel threads} in combination with semantics like @fork@, @join@, \etc.
2549% However, kernel threads are better as an implementation tool because of complexity and higher cost.
2550% Therefore, different abstractions are often layered onto kernel threads to simplify them, \eg pthreads.
2551%
2552%
2553% \subsection{User Threads}
2554%
2555% A direct improvement on kernel threads is user threads, \eg Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
2556% This approach provides an interface that matches the language paradigms, gives more control over concurrency by the language runtime, and an abstract (and portable) interface to the underlying kernel threads across operating systems.
2557% In many cases, user threads can be used on a much larger scale (100,000 threads).
2558% Like kernel threads, user threads support preemption, which maximizes nondeterminism, but increases the potential for concurrency errors: race, livelock, starvation, and deadlock.
2559% \CFA adopts user-threads to provide more flexibility and a low-cost mechanism to build any other concurrency approach, \eg thread pools and actors~\cite{Actors}.
2560%
2561% A variant of user thread is \newterm{fibres}, which removes preemption, \eg Go~\cite{Go} @goroutine@s.
2562% Like functional programming, which removes mutation and its associated problems, removing preemption from concurrency reduces nondeterminism, making race and deadlock errors more difficult to generate.
2563% However, preemption is necessary for fairness and to reduce tail-latency.
2564% For concurrency that relies on spinning, if all cores spin the system is livelocked, whereas preemption breaks the livelock.
2565
2566
2567\begin{comment}
2568\subsection{Thread Pools}
2569
2570In contrast to direct threading is indirect \newterm{thread pools}, \eg Java @executor@, where small jobs (work units) are inserted into a work pool for execution.
2571If the jobs are dependent, \ie interact, there is an implicit/explicit dependency graph that ties them together.
2572While removing direct concurrency, and hence the amount of context switching, thread pools significantly limit the interaction that can occur among jobs.
2573Indeed, jobs should not block because that also blocks the underlying thread, which effectively means the CPU utilization, and therefore throughput, suffers.
2574While 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.
2575As well, concurrency errors return, which threads pools are suppose to mitigate.
2576
2577\begin{figure}
2578\centering
2579\begin{tabular}{@{}l|l@{}}
2580\begin{cfa}
2581struct Adder {
2582    int * row, cols;
2583};
2584int operator()() {
2585        subtotal = 0;
2586        for ( int c = 0; c < cols; c += 1 )
2587                subtotal += row[c];
2588        return subtotal;
2589}
2590void ?{}( Adder * adder, int row[$\,$], int cols, int & subtotal ) {
2591        adder.[rows, cols, subtotal] = [rows, cols, subtotal];
2592}
2593
2594
2595
2596
2597\end{cfa}
2598&
2599\begin{cfa}
2600int main() {
2601        const int rows = 10, cols = 10;
2602        int matrix[rows][cols], subtotals[rows], total = 0;
2603        // read matrix
2604        Executor executor( 4 ); // kernel threads
2605        Adder * adders[rows];
2606        for ( r; rows ) { // send off work for executor
2607                adders[r] = new( matrix[r], cols, &subtotal[r] );
2608                executor.send( *adders[r] );
2609        }
2610        for ( r; rows ) {       // wait for results
2611                delete( adders[r] );
2612                total += subtotals[r];
2613        }
2614        sout | total;
2615}
2616\end{cfa}
2617\end{tabular}
2618\caption{Executor}
2619\end{figure}
2620\end{comment}
2621
2622
2623\section{Runtime Structure}
2624\label{s:CFARuntimeStructure}
2625
2626Figure~\ref{f:RunTimeStructure} illustrates the runtime structure of a \CFA program.
2627In 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.
2628An executing thread is illustrated by its containment in a processor.
2629
2630\begin{figure}
2631\centering
2632\input{RunTimeStructure}
2633\caption{\CFA Runtime structure}
2634\label{f:RunTimeStructure}
2635\end{figure}
2636
2637
2638\subsection{Cluster}
2639\label{s:RuntimeStructureCluster}
2640
2641A \newterm{cluster} is a collection of threads and virtual processors (abstract kernel-thread) that execute the (user) threads from its own ready queue (like an OS executing kernel threads).
2642The purpose of a cluster is to control the amount of parallelism that is possible among threads, plus scheduling and other execution defaults.
2643The default cluster-scheduler is single-queue multi-server, which provides automatic load-balancing of threads on processors.
2644However, the design allows changing the scheduler, \eg multi-queue multi-server with work-stealing/sharing across the virtual processors.
2645If several clusters exist, both threads and virtual processors, can be explicitly migrated from one cluster to another.
2646No automatic load balancing among clusters is performed by \CFA.
2647
2648When 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.
2649The user cluster is created to contain the application user-threads.
2650Having all threads execute on the one cluster often maximizes utilization of processors, which minimizes runtime.
2651However, because of limitations of scheduling requirements (real-time), NUMA architecture, heterogeneous hardware, or issues with the underlying operating system, multiple clusters are sometimes necessary.
2652
2653
2654\subsection{Virtual Processor}
2655\label{s:RuntimeStructureProcessor}
2656
2657A virtual processor is implemented by a kernel thread (\eg UNIX process), which are scheduled for execution on a hardware processor by the underlying operating system.
2658Programs may use more virtual processors than hardware processors.
2659On a multiprocessor, kernel threads are distributed across the hardware processors resulting in virtual processors executing in parallel.
2660(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.)
2661The \CFA runtime attempts to block unused processors and unblock processors as the system load increases;
2662balancing the workload with processors is difficult because it requires future knowledge, \ie what will the applicaton workload do next.
2663Preemption occurs on virtual processors rather than user threads, via operating-system interrupts.
2664Thus virtual processors execute user threads, where preemption frequency applies to a virtual processor, so preemption occurs randomly across the executed user threads.
2665Turning off preemption transforms user threads into fibres.
2666
2667
2668\begin{comment}
2669\section{Implementation}
2670\label{s:Implementation}
2671
2672A primary implementation challenge is avoiding contention from dynamically allocating memory because of bulk acquire, \eg the internal-scheduling design is (almost) free of allocations.
2673All 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.
2674Furthermore, several bulk-acquire operations need a variable amount of memory.
2675This 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.
2676
2677In \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.
2678When a mutex call is made, pointers to the concerned monitors are aggregated into a variable-length array and sorted.
2679This array persists for the entire duration of the mutual exclusion and is used extensively for synchronization operations.
2680
2681To improve performance and simplicity, context switching occurs inside a function call, so only callee-saved registers are copied onto the stack and then the stack register is switched;
2682the corresponding registers are then restored for the other context.
2683Note, the instruction pointer is untouched since the context switch is always inside the same function.
2684Experimental results (not presented) for a stackless or stackful scheduler (1 versus 2 context switches) (see Section~\ref{s:Concurrency}) show the performance is virtually equivalent, because both approaches are dominated by locking to prevent a race condition.
2685
2686All kernel threads (@pthreads@) created a stack.
2687Each \CFA virtual processor is implemented as a coroutine and these coroutines run directly on the kernel-thread stack, effectively stealing this stack.
2688The exception to this rule is the program main, \ie the initial kernel thread that is given to any program.
2689In 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.
2690\end{comment}
2691
2692
2693\subsection{Preemption}
2694
2695Nondeterministic preemption provides fairness from long-running threads, and forces concurrent programmers to write more robust programs, rather than relying on code between cooperative scheduling to be atomic.
2696This atomic reliance can fail on multi-core machines, because execution across cores is nondeterministic.
2697A different reason for not supporting preemption is that it significantly complicates the runtime system, \eg Microsoft runtime does not support interrupts and on Linux systems, interrupts are complex (see below).
2698Preemption is normally handled by setting a countdown timer on each virtual processor.
2699When the timer expires, an interrupt is delivered, and the interrupt handler resets the countdown 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.
2700Multiple signal handlers may be pending.
2701When 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.
2702The 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;
2703therefore, the same signal mask is required for all virtual processors in a cluster.
2704Because preemption frequency is usually long (1 millisecond) performance cost is negligible.
2705
2706Linux switched a decade ago from specific to arbitrary process signal-delivery for applications with multiple kernel threads.
2707\begin{cquote}
2708A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
2709If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which it will deliver the signal.
2710SIGNAL(7) - Linux Programmer's Manual
2711\end{cquote}
2712Hence, the timer-expiry signal, which is generated \emph{externally} by the Linux kernel to an application, is delivered to any of its Linux subprocesses (kernel threads).
2713To ensure each virtual processor receives a preemption signal, a discrete-event simulation is run on a special virtual processor, and only it sets and receives timer events.
2714Virtual processors register an expiration time with the discrete-event simulator, which is inserted in sorted order.
2715The simulation sets the countdown 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.
2716Processing a preemption event sends an \emph{internal} @SIGUSR1@ signal to the registered virtual processor, which is always delivered to that processor.
2717
2718
2719\subsection{Debug Kernel}
2720
2721There are two versions of the \CFA runtime kernel: debug and non-debug.
2722The 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.
2723After a program is debugged, the non-debugging version can be used to significantly decrease space and increase performance.
2724
2725
2726\section{Performance}
2727\label{s:Performance}
2728
2729To verify the implementation of the \CFA runtime, a series of microbenchmarks are performed comparing \CFA with pthreads, Java OpenJDK-9, Go 1.12.6 and \uC 7.0.0.
2730For comparison, the package must be multi-processor (M:N), which excludes libdill/libmil~\cite{libdill} (M:1)), and use a shared-memory programming model, \eg not message passing.
2731The benchmark computer is an AMD Opteron\texttrademark\ 6380 NUMA 64-core, 8 socket, 2.5 GHz processor, running Ubuntu 16.04.6 LTS, and \CFA/\uC are compiled with gcc 6.5.
2732
2733All benchmarks are run using the following harness. (The Java harness is augmented to circumvent JIT issues.)
2734\begin{cfa}
2735unsigned int N = 10_000_000;
2736#define BENCH( `run` ) Time before = getTimeNsec();  `run;`  Duration result = (getTimeNsec() - before) / N;
2737\end{cfa}
2738The method used to get time is @clock_gettime( CLOCK_REALTIME )@.
2739Each benchmark is performed @N@ times, where @N@ varies depending on the benchmark;
2740the total time is divided by @N@ to obtain the average time for a benchmark.
2741Each benchmark experiment is run 31 times.
2742All omitted tests for other languages are functionally identical to the \CFA tests and available online~\cite{CforallBenchMarks}.
2743% tar --exclude=.deps --exclude=Makefile --exclude=Makefile.in --exclude=c.c --exclude=cxx.cpp --exclude=fetch_add.c -cvhf benchmark.tar benchmark
2744
2745\paragraph{Object Creation}
2746
2747Object creation is measured by creating/deleting the specific kind of concurrent object.
2748Figure~\ref{f:creation} shows the code for \CFA, with results in Table~\ref{tab:creation}.
2749The 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.
2750
2751\begin{multicols}{2}
2752\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2753\begin{cfa}
2754@thread@ MyThread {};
2755void @main@( MyThread & ) {}
2756int main() {
2757        BENCH( for ( N ) { @MyThread m;@ } )
2758        sout | result`ns;
2759}
2760\end{cfa}
2761\captionof{figure}{\CFA object-creation benchmark}
2762\label{f:creation}
2763
2764\columnbreak
2765
2766\vspace*{-16pt}
2767\captionof{table}{Object creation comparison (nanoseconds)}
2768\label{tab:creation}
2769
2770\begin{tabular}[t]{@{}r*{3}{D{.}{.}{5.2}}@{}}
2771\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
2772\CFA Coroutine Lazy             & 13.2          & 13.1          & 0.44          \\
2773\CFA Coroutine Eager    & 531.3         & 536.0         & 26.54         \\
2774\CFA Thread                             & 2074.9        & 2066.5        & 170.76        \\
2775\uC Coroutine                   & 89.6          & 90.5          & 1.83          \\
2776\uC Thread                              & 528.2         & 528.5         & 4.94          \\
2777Goroutine                               & 4068.0        & 4113.1        & 414.55        \\
2778Java Thread                             & 103848.5      & 104295.4      & 2637.57       \\
2779Pthreads                                & 33112.6       & 33127.1       & 165.90
2780\end{tabular}
2781\end{multicols}
2782
2783
2784\paragraph{Context-Switching}
2785
2786In procedural programming, the cost of a function call is important as modularization (refactoring) increases.
2787(In many cases, a compiler inlines function calls to eliminate this cost.)
2788Similarly, when modularization extends to coroutines/tasks, the time for a context switch becomes a relevant factor.
2789The coroutine test is from resumer to suspender and from suspender to resumer, which is two context switches.
2790The thread test is using yield to enter and return from the runtime kernel, which is two context switches.
2791The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling.
2792Figure~\ref{f:ctx-switch} only shows the \CFA code for coroutines/threads (other systems are similar) with all results in Table~\ref{tab:ctx-switch}.
2793
2794\begin{multicols}{2}
2795\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2796\begin{cfa}[aboveskip=0pt,belowskip=0pt]
2797@coroutine@ C {} c;
2798void main( C & ) { for ( ;; ) { @suspend;@ } }
2799int main() { // coroutine test
2800        BENCH( for ( N ) { @resume( c );@ } )
2801        sout | result`ns;
2802}
2803int main() { // task test
2804        BENCH( for ( N ) { @yield();@ } )
2805        sout | result`ns;
2806}
2807\end{cfa}
2808\captionof{figure}{\CFA context-switch benchmark}
2809\label{f:ctx-switch}
2810
2811\columnbreak
2812
2813\vspace*{-16pt}
2814\captionof{table}{Context switch comparison (nanoseconds)}
2815\label{tab:ctx-switch}
2816\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
2817\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
2818C function              & 1.8   & 1.8   & 0.01  \\
2819\CFA generator  & 2.4   & 2.2   & 0.25  \\
2820\CFA Coroutine  & 36.2  & 36.2  & 0.25  \\
2821\CFA Thread             & 93.2  & 93.5  & 2.09  \\
2822\uC Coroutine   & 52.0  & 52.1  & 0.51  \\
2823\uC Thread              & 96.2  & 96.3  & 0.58  \\
2824Goroutine               & 141.0 & 141.3 & 3.39  \\
2825Java Thread             & 374.0 & 375.8 & 10.38 \\
2826Pthreads Thread & 361.0 & 365.3 & 13.19
2827\end{tabular}
2828\end{multicols}
2829
2830
2831\paragraph{Mutual-Exclusion}
2832
2833Uncontented mutual exclusion, which frequently occurs, is measured by entering/leaving a critical section.
2834For monitors, entering and leaving a monitor function is measured.
2835To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a @pthread_mutex@ lock is also measured.
2836Figure~\ref{f:mutex} shows the code for \CFA with all results in Table~\ref{tab:mutex}.
2837Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2838
2839\begin{multicols}{2}
2840\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2841\begin{cfa}
2842@monitor@ M {} m1/*, m2, m3, m4*/;
2843void __attribute__((noinline))
2844do_call( M & @mutex m/*, m2, m3, m4*/@ ) {}
2845int main() {
2846        BENCH(
2847                for( N ) do_call( m1/*, m2, m3, m4*/ );
2848        )
2849        sout | result`ns;
2850}
2851\end{cfa}
2852\captionof{figure}{\CFA acquire/release mutex benchmark}
2853\label{f:mutex}
2854
2855\columnbreak
2856
2857\vspace*{-16pt}
2858\captionof{table}{Mutex comparison (nanoseconds)}
2859\label{tab:mutex}
2860\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
2861\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
2862test and test-and-test lock             & 19.1  & 18.9  & 0.40  \\
2863\CFA @mutex@ function, 1 arg.   & 45.9  & 46.6  & 1.45  \\
2864\CFA @mutex@ function, 2 arg.   & 105.0 & 104.7 & 3.08  \\
2865\CFA @mutex@ function, 4 arg.   & 165.0 & 167.6 & 5.65  \\
2866\uC @monitor@ member rtn.               & 54.0  & 53.7  & 0.82  \\
2867Java synchronized method                & 31.0  & 31.1  & 0.50  \\
2868Pthreads Mutex Lock                             & 33.6  & 32.6  & 1.14
2869\end{tabular}
2870\end{multicols}
2871
2872
2873\paragraph{External Scheduling}
2874
2875External scheduling is measured using a cycle of two threads calling and accepting the call using the @waitfor@ statement.
2876Figure~\ref{f:ext-sched} shows the code for \CFA, with results in Table~\ref{tab:ext-sched}.
2877Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2878
2879\begin{multicols}{2}
2880\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2881\vspace*{-16pt}
2882\begin{cfa}
2883volatile int go = 0;
2884@monitor@ M {} m;
2885thread T {};
2886void __attribute__((noinline))
2887do_call( M & @mutex@ ) {}
2888void main( T & ) {
2889        while ( go == 0 ) { yield(); }
2890        while ( go == 1 ) { do_call( m ); }
2891}
2892int __attribute__((noinline))
2893do_wait( M & @mutex@ m ) {
2894        go = 1; // continue other thread
2895        BENCH( for ( N ) { @waitfor( do_call, m );@ } )
2896        go = 0; // stop other thread
2897        sout | result`ns;
2898}
2899int main() {
2900        T t;
2901        do_wait( m );
2902}
2903\end{cfa}
2904\captionof{figure}{\CFA external-scheduling benchmark}
2905\label{f:ext-sched}
2906
2907\columnbreak
2908
2909\vspace*{-16pt}
2910\captionof{table}{External-scheduling comparison (nanoseconds)}
2911\label{tab:ext-sched}
2912\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
2913\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
2914\CFA @waitfor@, 1 @monitor@     & 376.4 & 376.8 & 7.63  \\
2915\CFA @waitfor@, 2 @monitor@     & 491.4 & 492.0 & 13.31 \\
2916\CFA @waitfor@, 4 @monitor@     & 681.0 & 681.7 & 19.10 \\
2917\uC @_Accept@                           & 331.1 & 331.4 & 2.66
2918\end{tabular}
2919\end{multicols}
2920
2921
2922\paragraph{Internal Scheduling}
2923
2924Internal scheduling is measured using a cycle of two threads signalling and waiting.
2925Figure~\ref{f:int-sched} shows the code for \CFA, with results in Table~\ref{tab:int-sched}.
2926Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
2927Java 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.
2928
2929\begin{multicols}{2}
2930\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
2931\begin{cfa}
2932volatile int go = 0;
2933@monitor@ M { @condition c;@ } m;
2934void __attribute__((noinline))
2935do_call( M & @mutex@ a1 ) { @signal( c );@ }
2936thread T {};
2937void main( T & this ) {
2938        while ( go == 0 ) { yield(); }
2939        while ( go == 1 ) { do_call( m ); }
2940}
2941int  __attribute__((noinline))
2942do_wait( M & mutex m ) with(m) {
2943        go = 1; // continue other thread
2944        BENCH( for ( N ) { @wait( c );@ } );
2945        go = 0; // stop other thread
2946        sout | result`ns;
2947}
2948int main() {
2949        T t;
2950        do_wait( m );
2951}
2952\end{cfa}
2953\captionof{figure}{\CFA Internal-scheduling benchmark}
2954\label{f:int-sched}
2955
2956\columnbreak
2957
2958\vspace*{-16pt}
2959\captionof{table}{Internal-scheduling comparison (nanoseconds)}
2960\label{tab:int-sched}
2961\bigskip
2962
2963\begin{tabular}{@{}r*{3}{D{.}{.}{5.2}}@{}}
2964\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
2965\CFA @signal@, 1 @monitor@      & 372.6         & 374.3         & 14.17         \\
2966\CFA @signal@, 2 @monitor@      & 492.7         & 494.1         & 12.99         \\
2967\CFA @signal@, 4 @monitor@      & 749.4         & 750.4         & 24.74         \\
2968\uC @signal@                            & 320.5         & 321.0         & 3.36          \\
2969Java @notify@                           & 10160.5       & 10169.4       & 267.71        \\
2970Pthreads Cond. Variable         & 4949.6        & 5065.2        & 363
2971\end{tabular}
2972\end{multicols}
2973
2974
2975\section{Conclusion}
2976
2977Advanced control-flow will always be difficult, especially when there is temporal ordering and nondeterminism.
2978However, many systems exacerbate the difficulty through their presentation mechanisms.
2979This paper shows it is possible to present a hierarchy of control-flow features, generator, coroutine, thread, and monitor, providing an integrated set of high-level, efficient, and maintainable control-flow features.
2980Eliminated from \CFA are spurious wakeup and barging, which are nonintuitive and lead to errors, and having to work with a bewildering set of low-level locks and acquisition techniques.
2981\CFA high-level race-free monitors and tasks provide the core mechanisms for mutual exclusion and synchronization, without having to resort to magic qualifiers like @volatile@/@atomic@.
2982Extending these mechanisms to handle high-level deadlock-free bulk acquire across both mutual exclusion and synchronization is a unique contribution.
2983The \CFA runtime 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.
2984The M:N model is judged to be efficient and provide greater flexibility than a 1:1 threading model.
2985These concepts and the \CFA runtime-system are written in the \CFA language, extensively leveraging the \CFA type-system, which demonstrates the expressiveness of the \CFA language.
2986Performance 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.
2987C programmers should feel comfortable using these mechanisms for developing complex control-flow in applications, with the ability to obtain maximum available performance by selecting mechanisms at the appropriate level of need.
2988
2989
2990\section{Future Work}
2991
2992While control flow in \CFA has a strong start, development is still underway to complete a number of missing features.
2993
2994\paragraph{Flexible Scheduling}
2995\label{futur:sched}
2996
2997An important part of concurrency is scheduling.
2998Different scheduling algorithms can affect performance (both in terms of average and variation).
2999However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
3000One solution is to offer various tuning options, allowing the scheduler to be adjusted to the requirements of the workload.
3001However, to be truly flexible, a pluggable scheduler is necessary.
3002Currently, 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~\cite{Buhr00b}.
3003
3004\paragraph{Non-Blocking I/O}
3005\label{futur:nbio}
3006
3007Many modern workloads are not bound by computation but IO operations, a common case being web servers and XaaS~\cite{XaaS} (anything as a service).
3008These types of workloads require significant engineering to amortizing costs of blocking IO-operations.
3009At 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.
3010Current 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.
3011However, these solutions lead to code that is hard to create, read and maintain.
3012A 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.
3013A non-blocking I/O library is currently under development for \CFA.
3014
3015\paragraph{Other Concurrency Tools}
3016\label{futur:tools}
3017
3018While monitors offer flexible and powerful concurrency for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
3019Examples of such tools can include futures and promises~\cite{promises}, executors and actors.
3020These additional features are useful for applications that can be constructed without shared data and direct blocking.
3021As well, new \CFA extensions should make it possible to create a uniform interface for virtually all mutual exclusion, including monitors and low-level locks.
3022
3023\paragraph{Implicit Threading}
3024\label{futur:implcit}
3025
3026Basic 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.
3027This type of concurrency can be achieved both at the language level and at the library level.
3028The canonical example of implicit concurrency is concurrent nested @for@ loops, which are amenable to divide and conquer algorithms~\cite{uC++book}.
3029The \CFA language features should make it possible to develop a reasonable number of implicit concurrency mechanism to solve basic HPC data-concurrency problems.
3030However, implicit concurrency is a restrictive solution with significant limitations, so it can never replace explicit concurrent programming.
3031
3032
3033\section{Acknowledgements}
3034
3035The authors would like to recognize the design assistance of Aaron Moss, Rob Schluntz, Andrew Beach and Michael Brooks on the features described in this paper.
3036Funding 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.
3037
3038{%
3039\fontsize{9bp}{12bp}\selectfont%
3040\bibliography{pl,local}
3041}%
3042
3043\end{document}
3044
3045% Local Variables: %
3046% tab-width: 4 %
3047% fill-column: 120 %
3048% compile-command: "make" %
3049% End: %
Note: See TracBrowser for help on using the repository browser.