source: doc/papers/concurrency/Paper.tex @ bd12159

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

complete draft for second version of concurrency paper

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