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

arm-ehjacob/cs343-translationnew-astnew-ast-unique-expr
Last change on this file since bbdb0c6 was 9b4483a0, checked in by Peter A. Buhr <pabuhr@…>, 21 months ago

replace pseudo-generator benchmark results with real ones

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