source: doc/papers/concurrency/Paper.tex @ 27125d0

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

update concurrency paper to address referee comments and generate responses to comments

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