Ignore:
Timestamp:
Jan 7, 2021, 3:27:00 PM (5 years ago)
Author:
Thierry Delisle <tdelisle@…>
Branches:
ADT, arm-eh, ast-experimental, enum, forall-pointer-decay, jacob/cs343-translation, master, new-ast-unique-expr, pthread-emulation, qualifiedEnum, stuck-waitfor-destruct
Children:
2b4daf2, 64aeca0
Parents:
3c64c668 (diff), eef8dfb (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' into park_unpark

File:
1 edited

Legend:

Unmodified
Added
Removed
  • doc/papers/concurrency/Paper.tex

    r3c64c668 r58fe85a  
    6161\newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
    6262\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
     63\newcommand{\Csharp}{C\raisebox{-0.7ex}{\large$^\sharp$}\xspace} % C# symbolic name
    6464
    6565%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     
    9999\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
    100100
    101 % Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
    102 % The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
     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}
    103103% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
    104104\newcommand{\newtermFontInline}{\emph}
     
    110110\newcommand{\abbrevFont}{\textit}                       % set empty for no italics
    111111\@ifundefined{eg}{
    112 \newcommand{\EG}{\abbrevFont{e}\abbrevFont{g}}
     112%\newcommand{\EG}{\abbrevFont{e}\abbrevFont{g}}
     113\newcommand{\EG}{for example}
    113114\newcommand*{\eg}{%
    114115        \@ifnextchar{,}{\EG}%
     
    117118}}{}%
    118119\@ifundefined{ie}{
    119 \newcommand{\IE}{\abbrevFont{i}\abbrevFont{e}}
     120%\newcommand{\IE}{\abbrevFont{i}\abbrevFont{e}}
     121\newcommand{\IE}{that is}
    120122\newcommand*{\ie}{%
    121123        \@ifnextchar{,}{\IE}%
     
    127129\newcommand*{\etc}{%
    128130        \@ifnextchar{.}{\ETC}%
    129         {\ETC.\xspace}%
     131                {\ETC.\xspace}%
    130132}}{}%
    131133\@ifundefined{etal}{
    132134\newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}}
    133135\newcommand*{\etal}{%
    134         \@ifnextchar{.}{\protect\ETAL}%
    135                 {\protect\ETAL.\xspace}%
     136        \@ifnextchar{.}{\ETAL}%
     137                {\ETAL.\xspace}%
    136138}}{}%
    137139\@ifundefined{viz}{
     
    163165                __float80, float80, __float128, float128, forall, ftype, generator, _Generic, _Imaginary, __imag, __imag__,
    164166                inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or,
    165                 otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread,
     167                otype, restrict, resume, __restrict, __restrict__, __signed, __signed__, _Static_assert, suspend, thread,
    166168                _Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__,
    167169                virtual, __volatile, __volatile__, waitfor, when, with, zero_t},
    168170        moredirectives={defined,include_next},
    169171        % replace/adjust listing characters that look bad in sanserif
    170         literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
     172        literate={-}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1
    171173                {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
    172174                {<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1
     
    197199                _Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
    198200                _Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
    199 }
    200 \lstdefinelanguage{Golang}{
    201         morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
    202         morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
    203                 bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
    204         morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
    205         morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
    206         morekeywords=[5]{Println,Printf,Error,},
    207         sensitive=true,
    208         morecomment=[l]{//},
    209         morecomment=[s]{/*}{*/},
    210         morestring=[b]',
    211         morestring=[b]",
    212         morestring=[s]{`}{`},
    213201}
    214202
     
    238226{}
    239227\lstnewenvironment{C++}[1][]                            % use C++ style
    240 {\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
     228{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`}}\lstset{#1}}
    241229{}
    242230\lstnewenvironment{uC++}[1][]
    243 {\lstset{#1}}
     231{\lstset{language=uC++,moredelim=**[is][\protect\color{red}]{`}{`}}\lstset{#1}}
    244232{}
    245233\lstnewenvironment{Go}[1][]
    246 {\lstset{language=Golang,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
     234{\lstset{language=Golang,moredelim=**[is][\protect\color{red}]{`}{`}}\lstset{#1}}
    247235{}
    248236\lstnewenvironment{python}[1][]
    249 {\lstset{language=python,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
     237{\lstset{language=python,moredelim=**[is][\protect\color{red}]{`}{`}}\lstset{#1}}
     238{}
     239\lstnewenvironment{java}[1][]
     240{\lstset{language=java,moredelim=**[is][\protect\color{red}]{`}{`}}\lstset{#1}}
    250241{}
    251242
     
    262253}
    263254
    264 \newbox\myboxA
    265 \newbox\myboxB
    266 \newbox\myboxC
    267 \newbox\myboxD
     255\newsavebox{\myboxA}
     256\newsavebox{\myboxB}
     257\newsavebox{\myboxC}
     258\newsavebox{\myboxD}
    268259
    269260\title{\texorpdfstring{Advanced Control-flow and Concurrency in \protect\CFA}{Advanced Control-flow in Cforall}}
     
    275266\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}
    276267
    277 \corres{*Peter A. Buhr, Cheriton School of Computer Science, University of Waterloo, 200 University Avenue West, Waterloo, ON, N2L 3G1, Canada. \email{pabuhr{\char`\@}uwaterloo.ca}}
     268\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}}
    278269
    279270% \fundingInfo{Natural Sciences and Engineering Research Council of Canada}
    280271
    281272\abstract[Summary]{
    282 \CFA is a polymorphic, non-object-oriented, concurrent, backwards-compatible extension of the C programming language.
     273\CFA is a polymorphic, nonobject-oriented, concurrent, backwards compatible extension of the C programming language.
    283274This paper discusses the design philosophy and implementation of its advanced control-flow and concurrent/parallel features, along with the supporting runtime written in \CFA.
    284 These features are created from scratch as ISO C has only low-level and/or unimplemented concurrency, so C programmers continue to rely on library features like pthreads.
     275These 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.
    285276\CFA introduces modern language-level control-flow mechanisms, like generators, coroutines, user-level threading, and monitors for mutual exclusion and synchronization.
    286277% Library extension for executors, futures, and actors are built on these basic mechanisms.
    287278The runtime provides significant programmer simplification and safety by eliminating spurious wakeup and monitor barging.
    288 The runtime also ensures multiple monitors can be safely acquired \emph{simultaneously} (deadlock free), and this feature is fully integrated with all monitor synchronization mechanisms.
     279The 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.
    289280All control-flow features integrate with the \CFA polymorphic type-system and exception handling, while respecting the expectations and style of C programmers.
    290281Experimental results show comparable performance of the new features with similar mechanisms in other concurrent programming languages.
    291282}%
    292283
    293 \keywords{generator, coroutine, concurrency, parallelism, thread, monitor, runtime, C, \CFA (Cforall)}
     284\keywords{C \CFA (Cforall) coroutine concurrency generator monitor parallelism runtime thread}
    294285
    295286
    296287\begin{document}
    297 \linenumbers                                            % comment out to turn off line numbering
     288%\linenumbers                           % comment out to turn off line numbering
    298289
    299290\maketitle
     
    302293\section{Introduction}
    303294
    304 This paper discusses the design philosophy and implementation of advanced language-level control-flow and concurrent/parallel features in \CFA~\cite{Moss18,Cforall} and its runtime, which is written entirely in \CFA.
    305 \CFA is a modern, polymorphic, non-object-oriented\footnote{
    306 \CFA has features often associated with object-oriented programming languages, such as constructors, destructors, virtuals and simple inheritance.
    307 However, functions \emph{cannot} be nested in structures, so there is no lexical binding between a structure and set of functions (member/method) implemented by an implicit \lstinline@this@ (receiver) parameter.},
    308 backwards-compatible extension of the C programming language.
    309 In many ways, \CFA is to C as Scala~\cite{Scala} is to Java, providing a \emph{research vehicle} for new typing and control-flow capabilities on top of a highly popular programming language allowing immediate dissemination.
    310 Within the \CFA framework, new control-flow features are created from scratch because ISO \Celeven defines only a subset of the \CFA extensions, where the overlapping features are concurrency~\cite[\S~7.26]{C11}.
    311 However, \Celeven concurrency is largely wrappers for a subset of the pthreads library~\cite{Butenhof97,Pthreads}, and \Celeven and pthreads concurrency is simple, based on thread fork/join in a function and mutex/condition locks, which is low-level and error-prone;
    312 no high-level language concurrency features are defined.
    313 Interestingly, almost a decade after publication of the \Celeven standard, neither gcc-8, clang-9 nor msvc-19 (most recent versions) support the \Celeven include @threads.h@, indicating little interest in the C11 concurrency approach (possibly because the effort to add concurrency to \CC).
    314 Finally, while the \Celeven standard does not state a threading model, the historical association with pthreads suggests implementations would adopt kernel-level threading (1:1)~\cite{ThreadModel}.
    315 
     295\CFA~\cite{Moss18,Cforall} is a modern, polymorphic, nonobject-oriented\footnote{
     296\CFA has object-oriented features, such as constructors, destructors, and simple trait/interface inheritance.
     297% Go interfaces, Rust traits, Swift Protocols, Haskell Type Classes and Java Interfaces.
     298% "Trait inheritance" works for me. "Interface inheritance" might also be a good choice, and distinguish clearly from implementation inheritance.
     299% 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.
     300% 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".
     301However, functions \emph{cannot} be nested in structures and there is no mechanism to designate a function parameter as a receiver, \lstinline@this@, parameter.},
     302, backward-compatible extension of the C programming language.
     303In 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{
     304The 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.}
     305allowing immediate dissemination.
     306This 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.
     307
     308% The call/return extensions retain state between callee and caller versus losing the callee's state on return;
     309% the concurrency extensions allow high-level management of threads.
     310
     311The \CFA control-flow framework extends ISO \Celeven~\cite{C11} with new call/return and concurrent/parallel control-flow.
     312Call/return control-flow with argument and parameter passing appeared in the first programming languages.
     313Over the past 50 years, call/return has been augmented with features like static and dynamic call, exceptions (multilevel return) and generators/coroutines (see Section~\ref{s:StatefulFunction}).
     314While \CFA has mechanisms for dynamic call (algebraic effects~\cite{Zhang19}) and exceptions\footnote{
     315\CFA exception handling will be presented in a separate paper.
     316The 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++}}
     317, this work only discusses retaining state between calls via generators and coroutines.
     318\newterm{Coroutining} was introduced by Conway~\cite{Conway63}, 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}.
     319Coroutining is sequential execution requiring direct handoff among coroutines, \ie only the programmer is controlling execution order.
     320If 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}.
     321Coroutines are only a stepping stone toward concurrency where the commonality is that coroutines and threads retain state between calls.
     322
     323\Celeven and \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}
     324Interestingly, 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).
     325While 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.
    316326In contrast, there has been a renewed interest during the past decade in user-level (M:N, green) threading in old and new programming languages.
    317 As multi-core hardware became available in the 1980/90s, both user and kernel threading were examined.
     327As multicore hardware became available in the 1980/1990s, both user and kernel threading were examined.
    318328Kernel 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}.
    319329Libraries like pthreads were developed for C, and the Solaris operating-system switched from user (JDK 1.1~\cite{JDK1.1}) to kernel threads.
    320 As a result, languages like Java, Scala, Objective-C~\cite{obj-c-book}, \CCeleven~\cite{C11}, and C\#~\cite{Csharp} adopt the 1:1 kernel-threading model, with a variety of presentation mechanisms.
    321 From 2000 onwards, languages like Go~\cite{Go}, Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, D~\cite{D}, and \uC~\cite{uC++,uC++book} have championed the M:N user-threading model, and many user-threading libraries have appeared~\cite{Qthreads,MPC,Marcel}, including putting green threads back into Java~\cite{Quasar}.
    322 The main argument for user-level threading is that it is lighter weight than kernel threading (locking and context switching do not cross the kernel boundary), so there is less restriction on programming styles that encourage large numbers of threads performing medium work units to facilitate load balancing by the runtime~\cite{Verch12}.
     330As 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.
     331From 2000 onward, 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}.
     332The 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}.
    323333As well, user-threading facilitates a simpler concurrency approach using thread objects that leverage sequential patterns versus events with call-backs~\cite{Adya02,vonBehren03}.
    324 Finally, performant user-threading implementations (both time and space) meet or exceed direct kernel-threading implementations, while achieving the programming advantages of high concurrency levels and safety.
    325 
    326 A further effort over the past two decades is the development of language memory models to deal with the conflict between language features and compiler/hardware optimizations, \ie some language features are unsafe in the presence of aggressive sequential optimizations~\cite{Buhr95a,Boehm05}.
    327 The consequence is that a language must provide sufficient tools to program around safety issues, as inline and library code is all sequential to the compiler.
    328 One solution is low-level qualifiers and functions (\eg @volatile@ and atomics) allowing \emph{programmers} to explicitly write safe (race-free~\cite{Boehm12}) programs.
    329 A safer solution is high-level language constructs so the \emph{compiler} knows the optimization boundaries, and hence, provides implicit safety.
    330 This problem is best known with respect to concurrency, but applies to other complex control-flow, like exceptions\footnote{
    331 \CFA exception handling will be presented in a separate paper.
    332 The key feature that dovetails with this paper is nonlocal exceptions allowing exceptions to be raised across stacks, with synchronous exceptions raised among coroutines and asynchronous exceptions raised among threads, similar to that in \uC~\cite[\S~5]{uC++}
    333 } and coroutines.
    334 Finally, language solutions allow matching constructs with language paradigm, \ie imperative and functional languages often have different presentations of the same concept to fit their programming model.
     334Finally, 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.
     335
     336A 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}.
     337The 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.
     338One solution is low-level qualifiers and functions, \eg @volatile@ and atomics, allowing \emph{programmers} to explicitly write safe, race-free~\cite{Boehm12} programs.
     339A 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.
     340While the optimization problem is best known with respect to concurrency, it applies to other complex control-flows like exceptions and coroutines.
     341As 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.
    335342
    336343Finally, it is important for a language to provide safety over performance \emph{as the default}, allowing careful reduction of safety for performance when necessary.
    337 Two concurrency violations of this philosophy are \emph{spurious wakeup} (random wakeup~\cite[\S~8]{Buhr05a}) and \emph{barging}\footnote{
    338 The notion of competitive succession instead of direct handoff, \ie a lock owner releases the lock and an arriving thread acquires it ahead of preexisting waiter threads.
    339 } (signals-as-hints~\cite[\S~8]{Buhr05a}), where one is a consequence of the other, \ie once there is spurious wakeup, signals-as-hints follow.
    340 However, spurious wakeup is \emph{not} a foundational concurrency property~\cite[\S~8]{Buhr05a}, it is a performance design choice.
    341 Similarly, signals-as-hints are often a performance decision.
    342 We argue removing spurious wakeup and signals-as-hints make concurrent programming significantly safer because it removes local non-determinism and matches with programmer expectation.
    343 (Author experience teaching concurrency is that students are highly confused by these semantics.)
    344 Clawing back performance, when local non-determinism is unimportant, should be an option not the default.
    345 
    346 \begin{comment}
    347 Most augmented traditional (Fortran 18~\cite{Fortran18}, Cobol 14~\cite{Cobol14}, Ada 12~\cite{Ada12}, Java 11~\cite{Java11}) and new languages (Go~\cite{Go}, Rust~\cite{Rust}, and D~\cite{D}), except \CC, diverge from C with different syntax and semantics, only interoperate indirectly with C, and are not systems languages, for those with managed memory.
    348 As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten.
    349 While \CC, like \CFA, takes an evolutionary approach to extend C, \CC's constantly growing complex and interdependent features-set (\eg objects, inheritance, templates, etc.) mean idiomatic \CC code is difficult to use from C, and C programmers must expend significant effort learning \CC.
    350 Hence, rewriting and retraining costs for these languages, even \CC, are prohibitive for companies with a large C software-base.
    351 \CFA with its orthogonal feature-set, its high-performance runtime, and direct access to all existing C libraries circumvents these problems.
    352 \end{comment}
    353 
    354 \CFA embraces user-level threading, language extensions for advanced control-flow, and safety as the default.
    355 We present comparative examples so the reader can judge if the \CFA control-flow extensions are better and safer than those in other concurrent, imperative programming languages, and perform experiments to show the \CFA runtime is competitive with other similar mechanisms.
     344Two concurrency violations of this philosophy are \emph{spurious} or \emph{random wakeup}~\cite[\S~9]{Buhr05a}, and \emph{barging}\footnote{
     345Barging is competitive succession instead of direct handoff, \ie after a lock is released both arriving and preexisting waiter threads compete to acquire the lock.
     346Hence, 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.
     347} or signals-as-hints~\cite[\S~8]{Buhr05a}, where one is a consequence of the other, \ie once there is spurious wakeup, barging follows.
     348(Author experience teaching concurrency is that students are confused by these semantics.)
     349However, spurious wakeup is \emph{not} a foundational concurrency property~\cite[\S~9]{Buhr05a};
     350it is a performance design choice.
     351We argue removing spurious wakeup and signals-as-hints make concurrent programming simpler and safer as there is less local nondeterminism to manage.
     352If barging acquisition is allowed, its specialized performance advantage should be available as an option not the default.
     353
     354\CFA embraces language extensions for advanced control-flow, user-level threading, and safety as the default.
     355We 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.
    356356The main contributions of this work are:
    357 \begin{itemize}[topsep=3pt,itemsep=1pt]
     357\begin{itemize}[topsep=3pt,itemsep=0pt]
    358358\item
    359 language-level generators, coroutines and user-level threading, which respect the expectations of C programmers.
     359a set of fundamental execution properties that dictate which language-level control-flow features need to be supported,
     360
    360361\item
    361 monitor synchronization without barging, and the ability to safely acquiring multiple monitors \emph{simultaneously} (deadlock free), while seamlessly integrating these capabilities with all monitor synchronization mechanisms.
     362integration of these language-level control-flow features, while respecting the style and expectations of C programmers,
     363
    362364\item
    363 providing statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features.
     365monitor 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,
     366
     367\item
     368providing statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features,
     369
    364370% \item
    365371% library extensions for executors, futures, and actors built on the basic mechanisms.
     372
    366373\item
    367 a runtime system with no spurious wakeup.
     374a runtime system without spurious wake-up and no performance loss,
     375
    368376\item
    369 a dynamic partitioning mechanism to segregate the execution environment for specialized requirements.
     377a 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.
     378
    370379% \item
    371 % a non-blocking I/O library
     380% a nonblocking I/O library
     381
    372382\item
    373 experimental results showing comparable performance of the new features with similar mechanisms in other programming languages.
     383experimental results showing comparable performance of the \CFA features with similar mechanisms in other languages.
    374384\end{itemize}
    375385
    376 Section~\ref{s:StatefulFunction} begins advanced control by introducing sequential functions that retain data and execution state between calls, which produces constructs @generator@ and @coroutine@.
    377 Section~\ref{s:Concurrency} begins concurrency, or how to create (fork) and destroy (join) a thread, which produces the @thread@ construct.
    378 Section~\ref{s:MutualExclusionSynchronization} discusses the two mechanisms to restricted nondeterminism when controlling shared access to resources (mutual exclusion) and timing relationships among threads (synchronization).
     386Section~\ref{s:FundamentalExecutionProperties} presents the compositional hierarchy of execution properties directing the design of control-flow features in \CFA.
     387Section~\ref{s:StatefulFunction} begins advanced control by introducing sequential functions that retain data and execution state between calls producing constructs @generator@ and @coroutine@.
     388Section~\ref{s:Concurrency} begins concurrency, or how to create (fork) and destroy (join) a thread producing the @thread@ construct.
     389Section~\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.
    379390Section~\ref{s:Monitor} shows how both mutual exclusion and synchronization are safely embedded in the @monitor@ and @thread@ constructs.
    380 Section~\ref{s:CFARuntimeStructure} describes the large-scale mechanism to structure (cluster) threads and virtual processors (kernel threads).
    381 Section~\ref{s:Performance} uses a series of microbenchmarks to compare \CFA threading with pthreads, Java OpenJDK-9, Go 1.12.6 and \uC 7.0.0.
     391Section~\ref{s:CFARuntimeStructure} describes the large-scale mechanism to structure threads and virtual processors (kernel threads).
     392Section~\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.
     393
     394
     395\section{Fundamental Execution Properties}
     396\label{s:FundamentalExecutionProperties}
     397
     398The features in a programming language should be composed of a set of fundamental properties rather than an ad hoc collection chosen by the designers.
     399To 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++}).
     400The fundamental properties are execution state, thread, and mutual-exclusion/synchronization.
     401These 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.
     402While 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.
     403As 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.
     404If a compositional feature is missing, a programmer has too few fundamental properties resulting in a complex and/or inefficient solution.
     405
     406In detail, the fundamental properties are:
     407\begin{description}[leftmargin=\parindent,topsep=3pt,parsep=0pt]
     408\item[\newterm{execution state}:]
     409It is the state information needed by a control-flow feature to initialize and manage both compute data and execution location(s), and de-initialize.
     410For example, 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.
     411State is retained in fixed-sized aggregate structures (objects) and dynamic-sized stack(s), often allocated in the heap(s) managed by the runtime system.
     412The 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.
     413Control-flow transfers among execution states in multiple ways, such as function call, context switch, asynchronous await, etc.
     414Because 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.
     415% An execution-state is related to the notion of a process continuation \cite{Hieb90}.
     416
     417\item[\newterm{threading}:]
     418It is execution of code that occurs independently of other execution, where an individual thread's execution is sequential.
     419Multiple threads provide \emph{concurrent execution};
     420concurrent execution becomes parallel when run on multiple processing units, \eg hyper-threading, cores, or sockets.
     421A programmer needs mechanisms to create, block and unblock, and join with a thread, even if these basic mechanisms are supplied indirectly through high-level features.
     422
     423\item[\newterm{mutual-exclusion / synchronization (MES)}:]
     424It is the concurrency mechanism to perform an action without interruption and establish timing relationships among multiple threads.
     425We contented these two properties are independent, \ie mutual exclusion cannot provide synchronization and vice versa without introducing additional threads~\cite[\S~4]{Buhr05a}.
     426Limiting MES functionality results in contrived solutions and inefficiency on multicore von Neumann computers where shared memory is a foundational aspect of its design.
     427\end{description}
     428These properties are fundamental as 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.
     429
     430
     431\subsection{Structuring execution properties}
     432
     433Programming languages seldom present the fundamental execution properties directly to programmers.
     434Instead, the properties are packaged into higher-level constructs that encapsulate details and provide safety to these low-level mechanisms.
     435Interestingly, language designers often pick and choose among these execution properties proving a varying subset of constructs.
     436
     437Table~\ref{t:ExecutionPropertyComposition} shows all combinations of the three fundamental execution properties available to language designers.
     438(When doing combination case-analysis, not all combinations are meaningful.)
     439The 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.
     440To 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.
     441For table entries missing these minimal components, the property is borrowed from the invoker (caller).
     442Each 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.
     443
     444\begin{table}
     445\caption{Execution property composition}
     446\centering
     447\label{t:ExecutionPropertyComposition}
     448\renewcommand{\arraystretch}{1.25}
     449%\setlength{\tabcolsep}{5pt}
     450\vspace*{-5pt}
     451\begin{tabular}{c|c||l|l}
     452\multicolumn{2}{c||}{Execution properties} & \multicolumn{2}{c}{Mutual exclusion / synchronization} \\
     453\hline
     454stateful                        & thread        & \multicolumn{1}{c|}{No} & \multicolumn{1}{c}{Yes} \\
     455\hline
     456\hline
     457No                                      & No            & \textbf{1}\ \ \ @struct@                              & \textbf{2}\ \ \ @mutex@ @struct@              \\
     458\hline
     459Yes (stackless)         & No            & \textbf{3}\ \ \ @generator@                   & \textbf{4}\ \ \ @mutex@ @generator@   \\
     460\hline
     461Yes (stackful)          & No            & \textbf{5}\ \ \ @coroutine@                   & \textbf{6}\ \ \ @mutex@ @coroutine@   \\
     462\hline
     463No                                      & Yes           & \textbf{7}\ \ \ {\color{red}rejected} & \textbf{8}\ \ \ {\color{red}rejected} \\
     464\hline
     465Yes (stackless)         & Yes           & \textbf{9}\ \ \ {\color{red}rejected} & \textbf{10}\ \ \ {\color{red}rejected} \\
     466\hline
     467Yes (stackful)          & Yes           & \textbf{11}\ \ \ @thread@                             & \textbf{12}\ \ @mutex@ @thread@               \\
     468\end{tabular}
     469\vspace*{-8pt}
     470\end{table}
     471
     472Case 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.
     473Structures are a foundational mechanism for data organization, and access functions provide interface abstraction and code sharing in all programming languages.
     474Case 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).
     475A @mutex@ structure, often called a \newterm{monitor}, provides a high-level interface for race-free access of shared data in concurrent programming languages.
     476Case 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.
     477A stackless structure, often called a \newterm{generator} or \emph{iterator}, is \newterm{stackless} because it still borrows the caller's stack and thread, but the stack is used only to preserve state across its callees not callers.
     478Generators provide the first step toward directly solving problems like finite-state machines (FSMs) that retain data and execution state between calls, whereas normal functions restart on each call.
     479Case 4 is cases 2 and 3 with thread safety during execution of the generator's access functions.
     480A @mutex@ generator extends generators into the concurrent domain.
     481Cases 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.
     482A 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.
     483A coroutine extends the state retained between calls beyond the generator's structure to arbitrary call depth in the access functions.
     484Cases 7, 8, 9 and 10 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.
     485For cases 9 and 10, the stackless frame is not growable, precluding accepting nested calls, making calls, blocking as it requires calls, or preemption as it requires pushing an interrupt frame, all of which compound to require an unknown amount of execution state.
     486Hence, if this kind of uninterruptable thread exists, it must execute to completion, \ie computation only, which severely restricts runtime management.
     487Cases 11 and 12 are a stackful thread with and without safe access to shared state.
     488A thread is the language mechanism to start another thread of control in a program with growable execution state for call/return execution.
     489In general, language constructs with more execution properties increase the cost of creation and execution along with complexity of usage.
     490
     491Given 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.
     492Table~\ref{t:ExecutionPropertyComposition} then suggests the optimal language feature needed for implementing a programming problem.
     493The following sections describe how \CFA fills in \emph{all} the nonrejected table entries with language features, while other programming languages may only provide a subset of the table.
     494
     495
     496\subsection{Design requirements}
     497
     498The following design requirements largely stem from building \CFA on top of C.
     499\begin{itemize}[topsep=3pt,parsep=0pt]
     500\item
     501All communication must be statically type checkable for early detection of errors and efficient code generation.
     502This requirement is consistent with the fact that C is a statically typed programming language.
     503
     504\item
     505Direct interaction among language features must be possible allowing any feature to be selected without restricting comm\-unication.
     506For example, many concurrent languages do not provide direct communication calls among threads, \ie threads only communicate indirectly through monitors, channels, messages, and/or futures.
     507Indirect communication increases the number of objects, consuming more resources, and requires additional synchronization and possibly data transfer.
     508
     509\item
     510All communication is performed using function calls, \ie data are transmitted from argument to parameter and results are returned from function calls.
     511Alternative forms of communication, such as call-backs, message passing, channels, or communication ports, step outside of C's normal form of communication.
     512
     513\item
     514All stateful features must follow the same declaration scopes and lifetimes as other language data.
     515For C that means at program startup, during block and function activation, and on demand using dynamic allocation.
     516
     517\item
     518MES 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.
     519Furthermore, reducing synchronization scope by encapsulating it within language constructs further reduces errors in concurrent programs.
     520
     521\item
     522Both synchronous and asynchronous communication are needed.
     523However, 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.
     524
     525\item
     526Synchronization 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.
     527Otherwise, certain concurrency problems are difficult, \eg web server, disk scheduling, and the amount of concurrency is inhibited~\cite{Gentleman81}.
     528\end{itemize}
     529We have satisfied these requirements in \CFA while maintaining backwards compatibility with the huge body of legacy C programs.
     530% In contrast, other new programming languages must still access C programs (\eg operating-system service routines), but do so through fragile C interfaces.
     531
     532
     533\subsection{Asynchronous await / call}
     534
     535Asynchronous 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).
     536The caller detects the action's completion through a \newterm{future} or \newterm{promise}.
     537The benefit is asynchronous caller execution with respect to the callee until future resolution.
     538For 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.
     539When the caller needs the promise to be fulfilled, it executes @await@.
     540A promise-completion call-back can be part of the callee action or the caller is rescheduled;
     541in either case, the call back is executed after the promise is fulfilled.
     542While 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.
     543Specifically, 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.
     544Note, @async-await@ is just syntactic-sugar over the event engine so it does not solve these deficiencies.
     545For multithreaded 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.
     546The problem is when concurrent work-units need to interact and/or block as this effects the executor by stopping threads.
     547While 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.
    382548
    383549
     
    385551\label{s:StatefulFunction}
    386552
    387 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.
    388 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.
    389 This capability is accomplished by retaining a data/execution \emph{closure} between invocations.
    390 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.
    391 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.
    392 Hence, refactoring a stackless coroutine may require changing it to stackful.
    393 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.
    394 As well, activating a stateful function is \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles).
    395 A fixed closure activated by modified call/return is faster than a variable closure activated by context switching.
    396 Additionally, any storage management for the closure (especially in unmanaged languages, \ie no garbage collection) must also be factored into design and performance.
    397 Therefore, selecting between stackless and stackful semantics is a tradeoff between programming requirements and performance, where stackless is faster and stackful is more general.
    398 Note, creation cost is amortized across usage, so activation cost is usually the dominant factor.
     553A \emph{stateful function} has the ability to remember state between calls, where state can be either data or execution, \eg plugin, device driver, FSM.
     554A 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.
     555However, 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.
     556Hence, 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}.
     557For 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.
     558The 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.
     559Note, a subset of generator state is a function \emph{closure}, \ie the technique of capturing lexical references when returning a nested function.
     560A 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.
     561For 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.
     562
     563There are two styles of activating a stateful function, \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles).
     564These 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.
     565Selecting 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.
     566Additionally, storage management for the closure/stack must be factored into design and performance, especially in unmanaged languages without garbage collection.
     567Note, creation cost (closure/stack) is amortized across usage, so activation cost (resume/suspend) is usually the dominant factor.
     568
     569% 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.
     570% 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.
     571% 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.
     572% 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.
     573% Hence, refactoring a stackless coroutine may require changing it to stackful.
     574% 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.
     575% As well, activating a stateful function is \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles).
     576% A fixed closure activated by modified call/return is faster than a variable closure activated by context switching.
     577% Additionally, any storage management for the closure (especially in unmanaged languages, \ie no garbage collection) must also be factored into design and performance.
     578% Therefore, selecting between stackless and stackful semantics is a tradeoff between programming requirements and performance, where stackless is faster and stackful is more general.
     579% nppNote, creation cost is amortized across usage, so activation cost is usually the dominant factor.
     580
     581For 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}.
     582\begin{center}
     583\begin{tabular}{@{}l|l|l@{}}
     584\multicolumn{1}{@{}c|}{Python asymmetric generator} & \multicolumn{1}{c|}{\uC symmetric coroutine} & \multicolumn{1}{c@{}}{Pthreads thread} \\
     585\hline
     586\begin{python}
     587`def Gen():` $\LstCommentStyle{\color{red}// function}$
     588        ... yield val ...
     589gen = Gen()
     590for i in range( 10 ):
     591        print( next( gen ) )
     592\end{python}
     593&
     594\begin{uC++}
     595`_Coroutine Cycle {` $\LstCommentStyle{\color{red}// class}$
     596        Cycle * p;
     597        void main() { p->cycle(); }
     598        void cycle() { resume(); }  `};`
     599Cycle c1, c2; c1.p=&c2; c2.p=&c1; c1.cycle();
     600\end{uC++}
     601&
     602\begin{cfa}
     603void * `rtn`( void * arg ) { ... }
     604int i = 3, rc;
     605pthread_t t; $\C{// thread id}$
     606$\LstCommentStyle{\color{red}// function pointer}$
     607rc=pthread_create(&t, `rtn`, (void *)i);
     608\end{cfa}
     609\end{tabular}
     610\end{center}
     611\CFA's preferred presentation model for generators/coroutines/threads is a hybrid of functions and classes, giving an object-oriented flavor.
     612Essentially, the generator/coroutine/thread function is semantically coupled with a generator/coroutine/thread custom type via the type's name.
     613The custom type solves several issues, while accessing the underlying mechanisms used by the custom types is still allowed for flexibility reasons.
     614Each custom type is discussed in detail in the following sections.
     615
     616
     617\subsection{Generator}
     618
     619Stackless 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.
     620The \CFA goal is to achieve this performance target, possibly at the cost of some semantic complexity.
     621A series of different kinds of generators and their implementation demonstrate how this goal is accomplished.\footnote{
     622The \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()|.
     623Operator \lstinline+|+ is overloaded for printing, like bit-shift \lstinline|<<| in \CC.
     624The \CFA \lstinline|with| clause opens an aggregate scope making its fields directly accessible, like Pascal \lstinline|with|, but using parallel semantics;
     625multiple aggregates may be opened.
     626\CFA has rebindable references \lstinline|int i, & ip = i, j; `&ip = &j;`| and nonrebindable references \lstinline|int i, & `const` ip = i, j; `&ip = &j;` // disallowed|.
     627}%
    399628
    400629\begin{figure}
     
    410639
    411640
     641
     642
    412643        int fn = f->fn; f->fn = f->fn1;
    413644                f->fn1 = f->fn + fn;
    414645        return fn;
    415 
    416646}
    417647int main() {
     
    432662void `main(Fib & fib)` with(fib) {
    433663
     664
    434665        [fn1, fn] = [1, 0];
    435666        for () {
     
    451682\begin{cfa}[aboveskip=0pt,belowskip=0pt]
    452683typedef struct {
    453         int fn1, fn;  void * `next`;
     684        int `restart`, fn1, fn;
    454685} Fib;
    455 #define FibCtor { 1, 0, NULL }
     686#define FibCtor { `0`, 1, 0 }
    456687Fib * comain( Fib * f ) {
    457         if ( f->next ) goto *f->next;
    458         f->next = &&s1;
     688        `static void * states[] = {&&s0, &&s1};`
     689        `goto *states[f->restart];`
     690  s0: f->`restart` = 1;
    459691        for ( ;; ) {
    460692                return f;
    461693          s1:; int fn = f->fn + f->fn1;
    462                         f->fn1 = f->fn; f->fn = fn;
     694                f->fn1 = f->fn; f->fn = fn;
    463695        }
    464696}
     
    472704\end{lrbox}
    473705
    474 \subfloat[C asymmetric generator]{\label{f:CFibonacci}\usebox\myboxA}
     706\subfloat[C]{\label{f:CFibonacci}\usebox\myboxA}
    475707\hspace{3pt}
    476708\vrule
    477709\hspace{3pt}
    478 \subfloat[\CFA asymmetric generator]{\label{f:CFAFibonacciGen}\usebox\myboxB}
     710\subfloat[\CFA]{\label{f:CFAFibonacciGen}\usebox\myboxB}
    479711\hspace{3pt}
    480712\vrule
    481713\hspace{3pt}
    482 \subfloat[C generator implementation]{\label{f:CFibonacciSim}\usebox\myboxC}
    483 \caption{Fibonacci (output) asymmetric generator}
     714\subfloat[C generated code for \CFA version]{\label{f:CFibonacciSim}\usebox\myboxC}
     715\caption{Fibonacci output asymmetric generator}
    484716\label{f:FibonacciAsymmetricGenerator}
    485717
     
    493725};
    494726void ?{}( Fmt & fmt ) { `resume(fmt);` } // constructor
    495 void ^?{}( Fmt & f ) with(f) { $\C[1.75in]{// destructor}$
     727void ^?{}( Fmt & f ) with(f) { $\C[2.25in]{// destructor}$
    496728        if ( g != 0 || b != 0 ) sout | nl; }
    497729void `main( Fmt & f )` with(f) {
     
    499731                for ( ; g < 5; g += 1 ) { $\C{// groups}$
    500732                        for ( ; b < 4; b += 1 ) { $\C{// blocks}$
    501                                 `suspend;` $\C{// wait for character}$
    502                                 while ( ch == '\n' ) `suspend;` // ignore
    503                                 sout | ch;                                              // newline
    504                         } sout | " ";  // block spacer
    505                 } sout | nl; // group newline
     733                                do { `suspend;` $\C{// wait for character}$
     734                                while ( ch == '\n' ); // ignore newline
     735                                sout | ch;                      $\C{// print character}$
     736                        } sout | " ";  $\C{// block separator}$
     737                } sout | nl; $\C{// group separator}$
    506738        }
    507739}
     
    521753\begin{cfa}[aboveskip=0pt,belowskip=0pt]
    522754typedef struct {
    523         void * next;
     755        int `restart`, g, b;
    524756        char ch;
    525         int g, b;
    526757} Fmt;
    527758void comain( Fmt * f ) {
    528         if ( f->next ) goto *f->next;
    529         f->next = &&s1;
     759        `static void * states[] = {&&s0, &&s1};`
     760        `goto *states[f->restart];`
     761  s0: f->`restart` = 1;
    530762        for ( ;; ) {
    531763                for ( f->g = 0; f->g < 5; f->g += 1 ) {
    532764                        for ( f->b = 0; f->b < 4; f->b += 1 ) {
    533                                 return;
    534                           s1:;  while ( f->ch == '\n' ) return;
     765                                do { return;  s1: ;
     766                                } while ( f->ch == '\n' );
    535767                                printf( "%c", f->ch );
    536768                        } printf( " " );
     
    539771}
    540772int main() {
    541         Fmt fmt = { NULL };  comain( &fmt ); // prime
     773        Fmt fmt = { `0` };  comain( &fmt ); // prime
    542774        for ( ;; ) {
    543775                scanf( "%c", &fmt.ch );
     
    550782\end{lrbox}
    551783
    552 \subfloat[\CFA asymmetric generator]{\label{f:CFAFormatGen}\usebox\myboxA}
    553 \hspace{3pt}
     784\subfloat[\CFA]{\label{f:CFAFormatGen}\usebox\myboxA}
     785\hspace{35pt}
    554786\vrule
    555787\hspace{3pt}
    556 \subfloat[C generator simulation]{\label{f:CFormatSim}\usebox\myboxB}
     788\subfloat[C generated code for \CFA version]{\label{f:CFormatGenImpl}\usebox\myboxB}
    557789\hspace{3pt}
    558 \caption{Formatter (input) asymmetric generator}
     790\caption{Formatter input asymmetric generator}
    559791\label{f:FormatterAsymmetricGenerator}
    560792\end{figure}
    561793
    562 Stateful functions appear as generators, coroutines, and threads, where presentations are based on function objects or pointers~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}.
    563 For example, Python presents generators as a function object:
    564 \begin{python}
    565 def Gen():
    566         ... `yield val` ...
    567 gen = Gen()
    568 for i in range( 10 ):
    569         print( next( gen ) )
    570 \end{python}
    571 Boost presents coroutines in terms of four functor object-types:
    572 \begin{cfa}
    573 asymmetric_coroutine<>::pull_type
    574 asymmetric_coroutine<>::push_type
    575 symmetric_coroutine<>::call_type
    576 symmetric_coroutine<>::yield_type
    577 \end{cfa}
    578 and many languages present threading using function pointers, @pthreads@~\cite{Butenhof97}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}, \eg pthreads:
    579 \begin{cfa}
    580 void * rtn( void * arg ) { ... }
    581 int i = 3, rc;
    582 pthread_t t; $\C{// thread id}$
    583 `rc = pthread_create( &t, rtn, (void *)i );` $\C{// create and initialized task, type-unsafe input parameter}$
    584 \end{cfa}
    585 % void mycor( pthread_t cid, void * arg ) {
    586 %       int * value = (int *)arg;                               $\C{// type unsafe, pointer-size only}$
    587 %       // thread body
    588 % }
    589 % int main() {
    590 %       int input = 0, output;
    591 %       coroutine_t cid = coroutine_create( &mycor, (void *)&input ); $\C{// type unsafe, pointer-size only}$
    592 %       coroutine_resume( cid, (void *)input, (void **)&output ); $\C{// type unsafe, pointer-size only}$
    593 % }
    594 \CFA's preferred presentation model for generators/coroutines/threads is a hybrid of objects and functions, with an object-oriented flavour.
    595 Essentially, the generator/coroutine/thread function is semantically coupled with a generator/coroutine/thread custom type.
    596 The custom type solves several issues, while accessing the underlying mechanisms used by the custom types is still allowed.
    597 
    598 
    599 \subsection{Generator}
    600 
    601 Stackless generators have the potential to be very small and fast, \ie as small and fast as function call/return for both creation and execution.
    602 The \CFA goal is to achieve this performance target, possibly at the cost of some semantic complexity.
    603 A series of different kinds of generators and their implementation demonstrate how this goal is accomplished.
    604 
    605 Figure~\ref{f:FibonacciAsymmetricGenerator} shows an unbounded asymmetric generator for an infinite sequence of Fibonacci numbers written in C and \CFA, with a simple C implementation for the \CFA version.
     794Figure~\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.
    606795This generator is an \emph{output generator}, producing a new result on each resumption.
    607796To 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.
    608 An additional requirement is the ability to create an arbitrary number of generators (of any kind), \ie retaining one state in global variables is insufficient;
     797An additional requirement is the ability to create an arbitrary number of generators of any kind, \ie retaining one state in global variables is insufficient;
    609798hence, state is retained in a closure between calls.
    610799Figure~\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.
    611800The C version only has the middle execution state because the top execution state is declaration initialization.
    612801Figure~\ref{f:CFAFibonacciGen} shows the \CFA approach, which also has a manual closure, but replaces the structure with a custom \CFA @generator@ type.
    613 This generator type is then connected to a function that \emph{must be named \lstinline|main|},\footnote{
    614 The name \lstinline|main| has special meaning in C, specifically the function where a program starts execution.
    615 Hence, overloading this name for other starting points (generator/coroutine/thread) is a logical extension.}
    616 called a \emph{generator main},which takes as its only parameter a reference to the generator type.
     802Each generator type must have a function named \lstinline|main|,
     803% \footnote{
     804% The name \lstinline|main| has special meaning in C, specifically the function where a program starts execution.
     805% Leveraging starting semantics to this name for generator/coroutine/thread is a logical extension.}
     806called 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.
    617807The generator main contains @suspend@ statements that suspend execution without ending the generator versus @return@.
    618 For the Fibonacci generator-main,\footnote{
    619 The \CFA \lstinline|with| opens an aggregate scope making its fields directly accessible, like Pascal \lstinline|with|, but using parallel semantics.
    620 Multiple aggregates may be opened.}
    621 the top initialization state appears at the start and the middle execution state is denoted by statement @suspend@.
     808For the Fibonacci generator-main, the top initialization state appears at the start and the middle execution state is denoted by statement @suspend@.
    622809Any local variables in @main@ \emph{are not retained} between calls;
    623810hence local variables are only for temporary computations \emph{between} suspends.
     
    627814Resuming an ended (returned) generator is undefined.
    628815Function @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.
    629 Figure~\ref{f:CFibonacciSim} shows the C implementation of the \CFA generator only needs one additional field, @next@, to handle retention of execution state.
    630 The computed @goto@ at the start of the generator main, which branches after the previous suspend, adds very little cost to the resume call.
    631 Finally, an explicit generator type provides both design and performance benefits, such as multiple type-safe interface functions taking and returning arbitrary types.\footnote{
    632 The \CFA operator syntax uses \lstinline|?| to denote operands, which allows precise definitions for pre, post, and infix operators, \eg \lstinline|++?|, \lstinline|?++|, and \lstinline|?+?|, in addition \lstinline|?\{\}| denotes a constructor, as in \lstinline|foo `f` = `\{`...`\}`|, \lstinline|^?\{\}| denotes a destructor, and \lstinline|?()| is \CC function call \lstinline|operator()|.
    633 }%
     816Figure~\ref{f:CFibonacciSim} shows the C implementation of the \CFA asymmetric generator.
     817Only one execution-state field, @restart@, is needed to subscript the suspension points in the generator.
     818At 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}.
     819Next, the computed @goto@ selects the last suspend point and branches to it.
     820The cost of setting @restart@ and branching via the computed @goto@ adds very little cost to the suspend and resume calls.
     821
     822An advantage of the \CFA explicit generator type is the ability to allow multiple type-safe interface functions taking and returning arbitrary types.
    634823\begin{cfa}
    635824int ?()( Fib & fib ) { return `resume( fib )`.fn; } $\C[3.9in]{// function-call interface}$
    636 int ?()( Fib & fib, int N ) { for ( N - 1 ) `fib()`; return `fib()`; } $\C{// use function-call interface to skip N values}$
    637 double ?()( Fib & fib ) { return (int)`fib()` / 3.14159; } $\C{// different return type, cast prevents recursive call}\CRT$
    638 sout | (int)f1() | (double)f1() | f2( 2 ); // alternative interface, cast selects call based on return type, step 2 values
     825int ?()( Fib & fib, int N ) { for ( N - 1 ) `fib()`; return `fib()`; } $\C{// add parameter to skip N values}$
     826double ?()( Fib & fib ) { return (int)`fib()` / 3.14159; } $\C{// different return type, cast prevents recursive call}$
     827Fib f;  int i;  double d;
     828i = f();  i = f( 2 );  d = f();                                         $\C{// alternative interfaces}\CRT$
    639829\end{cfa}
    640830Now, the generator can be a separately compiled opaque-type only accessed through its interface functions.
    641831For 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.
    642832
    643 Having to manually create the generator closure by moving local-state variables into the generator type is an additional programmer burden.
    644 (This restriction is removed by the coroutine in Section~\ref{s:Coroutine}.)
    645 This requirement follows from the generality of variable-size local-state, \eg local state with a variable-length array requires dynamic allocation because the array size is unknown at compile time.
     833\begin{figure}
     834%\centering
     835\newbox\myboxA
     836\begin{lrbox}{\myboxA}
     837\begin{python}[aboveskip=0pt,belowskip=0pt]
     838def Fib():
     839        fn1, fn = 0, 1
     840        while True:
     841                `yield fn1`
     842                fn1, fn = fn, fn1 + fn
     843f1 = Fib()
     844f2 = Fib()
     845for i in range( 10 ):
     846        print( next( f1 ), next( f2 ) )
     847
     848
     849
     850
     851
     852
     853
     854
     855
     856
     857\end{python}
     858\end{lrbox}
     859
     860\newbox\myboxB
     861\begin{lrbox}{\myboxB}
     862\begin{python}[aboveskip=0pt,belowskip=0pt]
     863def Fmt():
     864        try:
     865                while True:                                             $\C[2.5in]{\# until destructor call}$
     866                        for g in range( 5 ):            $\C{\# groups}$
     867                                for b in range( 4 ):    $\C{\# blocks}$
     868                                        while True:
     869                                                ch = (yield)    $\C{\# receive from send}$
     870                                                if '\n' not in ch: $\C{\# ignore newline}$
     871                                                        break
     872                                        print( ch, end='' )     $\C{\# print character}$
     873                                print( '  ', end='' )   $\C{\# block separator}$
     874                        print()                                         $\C{\# group separator}$
     875        except GeneratorExit:                           $\C{\# destructor}$
     876                if g != 0 | b != 0:                             $\C{\# special case}$
     877                        print()
     878fmt = Fmt()
     879`next( fmt )`                                                   $\C{\# prime, next prewritten}$
     880for i in range( 41 ):
     881        `fmt.send( 'a' );`                                      $\C{\# send to yield}$
     882\end{python}
     883\end{lrbox}
     884
     885\hspace{30pt}
     886\subfloat[Fibonacci]{\label{f:PythonFibonacci}\usebox\myboxA}
     887\hspace{3pt}
     888\vrule
     889\hspace{3pt}
     890\subfloat[Formatter]{\label{f:PythonFormatter}\usebox\myboxB}
     891\caption{Python generator}
     892\label{f:PythonGenerator}
     893\end{figure}
     894
     895Having 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}).
     896This 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.
    646897However, dynamic allocation significantly increases the cost of generator creation/destruction and is a showstopper for embedded real-time programming.
    647898But 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.
    648 With respect to safety, we believe static analysis can discriminate local state from temporary variables in a generator, \ie variable usage spanning @suspend@, and generate a compile-time error.
    649 Finally, our current experience is that most generator problems have simple data state, including local state, but complex execution state, so the burden of creating the generator type is small.
    650 As well, C programmers are not afraid of this kind of semantic programming requirement, if it results in very small, fast generators.
     899With 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.
     900Our 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.
     901As well, C programmers are not afraid of this kind of semantic programming requirement, if it results in very small and fast generators.
    651902
    652903Figure~\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.
     
    669920The 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.
    670921The destructor provides a newline, if formatted text ends with a full line.
    671 Figure~\ref{f:CFormatSim} shows the C implementation of the \CFA input generator with one additional field and the computed @goto@.
    672 For contrast, Figure~\ref{f:PythonFormatter} shows the equivalent Python format generator with the same properties as the Fibonacci generator.
    673 
    674 Figure~\ref{f:DeviceDriverGen} shows a \emph{killer} asymmetric generator, a device-driver, because device drivers caused 70\%-85\% of failures in Windows/Linux~\cite{Swift05}.
    675 Device drives follow the pattern of simple data state but complex execution state, \ie finite state-machine (FSM) parsing a protocol.
    676 For example, the following protocol:
     922Figure~\ref{f:CFormatGenImpl} shows the C implementation of the \CFA input generator with one additional field and the computed @goto@.
     923For contrast, Figure~\ref{f:PythonFormatter} shows the equivalent Python format generator with the same properties as the \CFA format generator.
     924
     925% https://dl-acm-org.proxy.lib.uwaterloo.ca/
     926
     927An 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}
     928Swift \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;
     929however, the calls do not retain execution state, and hence always start from the top.
     930The alternative approach for implementing device drivers is using stack-ripping.
     931However, 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.
     932
     933Figure~\ref{f:DeviceDriverGen} shows the generator advantages in implementing a simple network device-driver with the following protocol:
    677934\begin{center}
    678935\ldots\, STX \ldots\, message \ldots\, ESC ETX \ldots\, message \ldots\, ETX 2-byte crc \ldots
    679936\end{center}
    680 is a network message beginning with the control character STX, ending with an ETX, and followed by a 2-byte cyclic-redundancy check.
     937where the network message begins with the control character STX, ends with an ETX, and is followed by a two-byte cyclic-redundancy check.
    681938Control characters may appear in a message if preceded by an ESC.
    682939When 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.
    683 The device driver returns a status code of its current state, and when a complete message is obtained, the operating system knows the message is in the message buffer.
    684 Hence, the device driver is an input/output generator.
    685 
    686 Note, the cost of creating and resuming the device-driver generator, @Driver@, is virtually identical to call/return, so performance in an operating-system kernel is excellent.
    687 As well, the data state is small, where variables @byte@ and @msg@ are communication variables for passing in message bytes and returning the message, and variables @lnth@, @crc@, and @sum@ are local variable that must be retained between calls and are manually hoisted into the generator type.
    688 % Manually, detecting and hoisting local-state variables is easy when the number is small.
    689 In contrast, the execution state is large, with one @resume@ and seven @suspend@s.
    690 Hence, the key benefits of the generator are correctness, safety, and maintenance because the execution states are transcribed directly into the programming language rather than using a table-driven approach.
    691 Because FSMs can be complex and frequently occur in important domains, direct generator support is important in a system programming language.
     940The 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.
     941Hence, 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.
     942The 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.
     943% The conclusion is that FSMs are complex and occur in important domains, so direct generator support is important in a system programming language.
    692944
    693945\begin{figure}
    694946\centering
    695 \newbox\myboxA
    696 \begin{lrbox}{\myboxA}
    697 \begin{python}[aboveskip=0pt,belowskip=0pt]
    698 def Fib():
    699         fn1, fn = 0, 1
    700         while True:
    701                 `yield fn1`
    702                 fn1, fn = fn, fn1 + fn
    703 f1 = Fib()
    704 f2 = Fib()
    705 for i in range( 10 ):
    706         print( next( f1 ), next( f2 ) )
    707 
    708 
    709 
    710 
    711 
    712 
    713 \end{python}
    714 \end{lrbox}
    715 
    716 \newbox\myboxB
    717 \begin{lrbox}{\myboxB}
    718 \begin{python}[aboveskip=0pt,belowskip=0pt]
    719 def Fmt():
    720         try:
    721                 while True:
    722                         for g in range( 5 ):
    723                                 for b in range( 4 ):
    724                                         print( `(yield)`, end='' )
    725                                 print( '  ', end='' )
    726                         print()
    727         except GeneratorExit:
    728                 if g != 0 | b != 0:
    729                         print()
    730 fmt = Fmt()
    731 `next( fmt )`                    # prime, next prewritten
    732 for i in range( 41 ):
    733         `fmt.send( 'a' );`      # send to yield
    734 \end{python}
    735 \end{lrbox}
    736 \subfloat[Fibonacci]{\label{f:PythonFibonacci}\usebox\myboxA}
    737 \hspace{3pt}
    738 \vrule
    739 \hspace{3pt}
    740 \subfloat[Formatter]{\label{f:PythonFormatter}\usebox\myboxB}
    741 \caption{Python generator}
    742 \label{f:PythonGenerator}
    743 
    744 \bigskip
    745 
    746947\begin{tabular}{@{}l|l@{}}
    747948\begin{cfa}[aboveskip=0pt,belowskip=0pt]
     
    750951`generator` Driver {
    751952        Status status;
    752         unsigned char byte, * msg; // communication
    753         unsigned int lnth, sum;      // local state
    754         unsigned short int crc;
     953        char byte, * msg; // communication
     954        int lnth, sum;      // local state
     955        short int crc;
    755956};
    756957void ?{}( Driver & d, char * m ) { d.msg = m; }
     
    797998\end{figure}
    798999
    799 Figure~\ref{f:CFAPingPongGen} shows a symmetric generator, where the generator resumes another generator, forming a resume/resume cycle.
     1000Generators can also have symmetric activation using resume/resume to create control-flow cycles among generators.
    8001001(The trivial cycle is a generator resuming itself.)
    8011002This control flow is similar to recursion for functions but without stack growth.
    802 The steps for symmetric control-flow are creating, executing, and terminating the cycle.
     1003Figure~\ref{f:PingPongFullCoroutineSteps} shows the steps for symmetric control-flow using for the ping/pong program in Figure~\ref{f:CFAPingPongGen}.
     1004The program starts by creating the generators, @ping@ and @pong@, and then assigns the partners that form the cycle.
    8031005Constructing 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.
    8041006(This issue occurs for any cyclic data structure.)
    805 % The example creates all the generators and then assigns the partners that form the cycle.
    806 % Alternatively, the constructor can assign the partners as they are declared, except the first, and the first-generator partner is set after the last generator declaration to close the cycle.
    807 Once the cycle is formed, the program main resumes one of the generators, and the generators can then traverse an arbitrary cycle using @resume@ to activate partner generator(s).
     1007% (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.)
     1008Once 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).
    8081009Terminating 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).
     1010Note, the creator and starter may be different, \eg if the creator calls another function that starts the cycle.
    8091011The starting stack-frame is below the last active generator because the resume/resume cycle does not grow the stack.
    810 Also, since local variables are not retained in the generator function, it does not contain any objects with destructors that must be called, so the  cost is the same as a function return.
    811 Destructor cost occurs when the generator instance is deallocated, which is easily controlled by the programmer.
    812 
    813 Figure~\ref{f:CPingPongSim} shows the implementation of the symmetric generator, where the complexity is the @resume@, which needs an extension to the calling convention to perform a forward rather than backward jump.
    814 This jump-starts at the top of the next generator main to re-execute the normal calling convention to make space on the stack for its local variables.
    815 However, before the jump, the caller must reset its stack (and any registers) equivalent to a @return@, but subsequently jump forward.
    816 This semantics is basically a tail-call optimization, which compilers already perform.
    817 The example shows the assembly code to undo the generator's entry code before the direct jump.
    818 This assembly code depends on what entry code is generated, specifically if there are local variables and the level of optimization.
    819 To provide this new calling convention requires a mechanism built into the compiler, which is beyond the scope of \CFA at this time.
    820 Nevertheless, it is possible to hand generate any symmetric generators for proof of concept and performance testing.
    821 A compiler could also eliminate other artifacts in the generator simulation to further increase performance, \eg LLVM has various coroutine support~\cite{CoroutineTS}, and \CFA can leverage this support should it fork @clang@.
     1012Also, 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.
     1013Destructor cost occurs when the generator instance is deallocated by the creator.
     1014
     1015\begin{figure}
     1016\centering
     1017\input{FullCoroutinePhases.pstex_t}
     1018\vspace*{-10pt}
     1019\caption{Symmetric coroutine steps: Ping / Pong}
     1020\label{f:PingPongFullCoroutineSteps}
     1021\end{figure}
    8221022
    8231023\begin{figure}
     
    8261026\begin{cfa}[aboveskip=0pt,belowskip=0pt]
    8271027`generator PingPong` {
     1028        int N, i;                               // local state
    8281029        const char * name;
    829         int N;
    830         int i;                          // local state
    8311030        PingPong & partner; // rebindable reference
    8321031};
    8331032
    8341033void `main( PingPong & pp )` with(pp) {
     1034
     1035
    8351036        for ( ; i < N; i += 1 ) {
    8361037                sout | name | i;
     
    8501051\begin{cfa}[escapechar={},aboveskip=0pt,belowskip=0pt]
    8511052typedef struct PingPong {
     1053        int restart, N, i;
    8521054        const char * name;
    853         int N, i;
    8541055        struct PingPong * partner;
    855         void * next;
    8561056} PingPong;
    857 #define PPCtor(name, N) {name,N,0,NULL,NULL}
     1057#define PPCtor(name, N) {0, N, 0, name, NULL}
    8581058void comain( PingPong * pp ) {
    859         if ( pp->next ) goto *pp->next;
    860         pp->next = &&cycle;
     1059        static void * states[] = {&&s0, &&s1};
     1060        goto *states[pp->restart];
     1061  s0: pp->restart = 1;
    8611062        for ( ; pp->i < pp->N; pp->i += 1 ) {
    8621063                printf( "%s %d\n", pp->name, pp->i );
    8631064                asm( "mov  %0,%%rdi" : "=m" (pp->partner) );
    8641065                asm( "mov  %rdi,%rax" );
    865                 asm( "popq %rbx" );
     1066                asm( "add  $16, %rsp" );
     1067                asm( "popq %rbp" );
    8661068                asm( "jmp  comain" );
    867           cycle: ;
     1069          s1: ;
    8681070        }
    8691071}
     
    8811083\end{figure}
    8821084
    883 Finally, part of this generator work was inspired by the recent \CCtwenty generator proposal~\cite{C++20Coroutine19} (which they call coroutines).
     1085Figure~\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.
     1086Before 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.
     1087The @jmp comain@ restarts the function but with a different parameter, so the new call's behavior depends on the state of the coroutine type, \ie branch to restart location with different data state.
     1088While 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 (\ie the parameter to the function never changes during the forward calls).
     1089However, this assembler code depends on what entry code is generated, specifically if there are local variables and the level of optimization.
     1090Hence, 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@.
     1091For 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.
     1092
     1093Finally, 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.
    8841094Our work provides the same high-performance asymmetric generators as \CCtwenty, and extends their work with symmetric generators.
    8851095An 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:
     
    8961106\label{s:Coroutine}
    8971107
    898 Stackful coroutines extend generator semantics, \ie there is an implicit closure and @suspend@ may appear in a helper function called from the coroutine main.
    899 A coroutine is specified by replacing @generator@ with @coroutine@ for the type.
    900 Coroutine generality results in higher cost for creation, due to dynamic stack allocation, execution, due to context switching among stacks, and terminating, due to possible stack unwinding and dynamic stack deallocation.
     1108Stackful 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.
     1109Note, simulating coroutines with stacks of generators, \eg Python with @yield from@ cannot handle symmetric control-flow.
     1110Furthermore, all stack components must be of generators, so it is impossible to call a library function passing a generator that yields.
     1111Creating a generator copy of the library function maybe impossible because the library function is opaque.
     1112
     1113A \CFA coroutine is specified by replacing @generator@ with @coroutine@ for the type.
     1114Coroutine 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.
    9011115A series of different kinds of coroutines and their implementations demonstrate how coroutines extend generators.
    9021116
    9031117First, the previous generator examples are converted to their coroutine counterparts, allowing local-state variables to be moved from the generator type into the coroutine main.
    904 \begin{description}
    905 \item[Fibonacci]
    906 Move the declaration of @fn1@ to the start of coroutine main.
     1118Now the coroutine type only contains communication variables between interface functions and the coroutine main.
     1119\begin{center}
     1120\begin{tabular}{@{}l|l|l|l@{}}
     1121\multicolumn{1}{c|}{Fibonacci} & \multicolumn{1}{c|}{Formatter} & \multicolumn{1}{c|}{Device Driver} & \multicolumn{1}{c}{PingPong} \\
     1122\hline
    9071123\begin{cfa}[xleftmargin=0pt]
    908 void main( Fib & fib ) with(fib) {
     1124void main( Fib & fib ) ...
    9091125        `int fn1;`
    910 \end{cfa}
    911 \item[Formatter]
    912 Move the declaration of @g@ and @b@ to the for loops in the coroutine main.
     1126
     1127
     1128\end{cfa}
     1129&
    9131130\begin{cfa}[xleftmargin=0pt]
    9141131for ( `g`; 5 ) {
    9151132        for ( `b`; 4 ) {
    916 \end{cfa}
    917 \item[Device Driver]
    918 Move the declaration of @lnth@ and @sum@ to their points of initialization.
     1133
     1134
     1135\end{cfa}
     1136&
    9191137\begin{cfa}[xleftmargin=0pt]
    920         status = CONT;
    921         `unsigned int lnth = 0, sum = 0;`
    922         ...
    923         `unsigned short int crc = byte << 8;`
    924 \end{cfa}
    925 \item[PingPong]
    926 Move the declaration of @i@ to the for loop in the coroutine main.
     1138status = CONT;
     1139`int lnth = 0, sum = 0;`
     1140...
     1141`short int crc = byte << 8;`
     1142\end{cfa}
     1143&
    9271144\begin{cfa}[xleftmargin=0pt]
    928 void main( PingPong & pp ) with(pp) {
     1145void main( PingPong & pp ) ...
    9291146        for ( `i`; N ) {
    930 \end{cfa}
    931 \end{description}
     1147
     1148
     1149\end{cfa}
     1150\end{tabular}
     1151\end{center}
    9321152It 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.
    9331153\begin{cfa}
    934 unsigned int Crc() {
    935         `suspend;`
    936         unsigned short int crc = byte << 8;
    937         `suspend;`
    938         status = (crc | byte) == sum ? MSG : ECRC;
     1154int Crc() {
     1155        `suspend;`  short int crc = byte << 8;
     1156        `suspend;`  status = (crc | byte) == sum ? MSG : ECRC;
    9391157        return crc;
    9401158}
    9411159\end{cfa}
    942 A call to this function is placed at the end of the driver's coroutine-main.
    943 For complex finite-state machines, refactoring is part of normal program abstraction, especially when code is used in multiple places.
     1160A call to this function is placed at the end of the device driver's coroutine-main.
     1161For complex FSMs, refactoring is part of normal program abstraction, especially when code is used in multiple places.
    9441162Again, this complexity is usually associated with execution state rather than data state.
    9451163
    9461164\begin{comment}
    947 Figure~\ref{f:Coroutine3States} creates a @coroutine@ type, @`coroutine` Fib { int fn; }@, which provides communication, @fn@, for the \newterm{coroutine main}, @main@, which runs on the coroutine stack, and possibly multiple interface functions, \eg @next@.
    948 Like 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.
     1165Figure~\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@.
     1166Like 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.
    9491167The 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@.
    950 The interface function @next@, takes a Fibonacci instance and context switches to it using @resume@;
     1168The interface function @restart@, takes a Fibonacci instance and context switches to it using @resume@;
    9511169on restart, the Fibonacci field, @fn@, contains the next value in the sequence, which is returned.
    9521170The first @resume@ is special because it allocates the coroutine stack and cocalls its coroutine main on that stack;
     
    11141332\begin{figure}
    11151333\centering
    1116 \lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $
    11171334\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
    11181335\begin{cfa}
    11191336`coroutine` Prod {
    1120         Cons & c;                       // communication
     1337        Cons & c;                       $\C[1.5in]{// communication}$
    11211338        int N, money, receipt;
    11221339};
    11231340void main( Prod & prod ) with( prod ) {
    1124         // 1st resume starts here
    1125         for ( i; N ) {
     1341        for ( i; N ) {          $\C{// 1st resume}\CRT$
    11261342                int p1 = random( 100 ), p2 = random( 100 );
    1127                 sout | p1 | " " | p2;
    11281343                int status = delivery( c, p1, p2 );
    1129                 sout | " $" | money | nl | status;
    11301344                receipt += 1;
    11311345        }
    11321346        stop( c );
    1133         sout | "prod stops";
    11341347}
    11351348int payment( Prod & prod, int money ) {
     
    11521365\begin{cfa}
    11531366`coroutine` Cons {
    1154         Prod & p;                       // communication
     1367        Prod & p;                       $\C[1.5in]{// communication}$
    11551368        int p1, p2, status;
    11561369        bool done;
    11571370};
    11581371void ?{}( Cons & cons, Prod & p ) {
    1159         &cons.p = &p; // reassignable reference
     1372        &cons.p = &p;           $\C{// reassignable reference}$
    11601373        cons.[status, done ] = [0, false];
    11611374}
    11621375void main( Cons & cons ) with( cons ) {
    1163         // 1st resume starts here
    1164         int money = 1, receipt;
     1376        int money = 1, receipt; $\C{// 1st resume}\CRT$
    11651377        for ( ; ! done; ) {
    1166                 sout | p1 | " " | p2 | nl | " $" | money;
    11671378                status += 1;
    11681379                receipt = payment( p, money );
    1169                 sout | " #" | receipt;
    11701380                money += 1;
    11711381        }
    1172         sout | "cons stops";
    11731382}
    11741383int delivery( Cons & cons, int p1, int p2 ) {
     
    11891398
    11901399Figure~\ref{f:ProdCons} shows the ping-pong example in Figure~\ref{f:CFAPingPongGen} extended into a producer/consumer symmetric-coroutine performing bidirectional communication.
    1191 This example is illustrative because both producer/consumer have two interface functions with @resume@s that suspend execution in these interface (helper) functions.
     1400This example is illustrative because both producer and consumer have two interface functions with @resume@s that suspend execution in these interface functions.
    11921401The 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.
    1193 The first @resume@ of @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it.
    1194 @prod@'s coroutine main starts, creates local-state variables that are retained between coroutine activations, and executes $N$ iterations, each generating two random values, calling the consumer to deliver the values, and printing the status returned from the consumer.
    1195 
    1196 The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
    1197 On the first resume, @cons@'s stack is created and initialized, holding local-state variables retained between subsequent activations of the coroutine.
    1198 The consumer iterates until the @done@ flag is set, prints the values delivered by the producer, increments status, and calls back to the producer via @payment@, and on return from @payment@, prints the receipt from the producer and increments @money@ (inflation).
    1199 The call from the consumer to @payment@ introduces the cycle between producer and consumer.
    1200 When @payment@ is called, the consumer copies values into the producer's communication variable and a resume is executed.
    1201 The context switch restarts the producer at the point where it last context switched, so it continues in @delivery@ after the resume.
    1202 @delivery@ returns the status value in @prod@'s coroutine main, where the status is printed.
    1203 The loop then repeats calling @delivery@, where each call resumes the consumer coroutine.
    1204 The context switch to the consumer continues in @payment@.
    1205 The consumer increments and returns the receipt to the call in @cons@'s coroutine main.
    1206 The loop then repeats calling @payment@, where each call resumes the producer coroutine.
     1402The 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.
     1403@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.
     1404The producer's call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status.
     1405Similarly on the first resume, @cons@'s stack is created and initialized, holding local-state variables retained between subsequent activations of the coroutine.
     1406The symmetric coroutine cycle forms when the consumer calls the producer's @payment@ function, which resumes the producer in the consumer's delivery function.
     1407When the producer calls @delivery@ again, it resumes the consumer in the @payment@ function.
     1408Both interface functions then return to their corresponding coroutine-main functions for the next cycle.
    12071409Figure~\ref{f:ProdConsRuntimeStacks} shows the runtime stacks of the program main, and the coroutine mains for @prod@ and @cons@ during the cycling.
     1410As 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.
    12081411
    12091412\begin{figure}
     
    12141417\caption{Producer / consumer runtime stacks}
    12151418\label{f:ProdConsRuntimeStacks}
    1216 
    1217 \medskip
    1218 
    1219 \begin{center}
    1220 \input{FullCoroutinePhases.pstex_t}
    1221 \end{center}
    1222 \vspace*{-10pt}
    1223 \caption{Ping / Pong coroutine steps}
    1224 \label{f:PingPongFullCoroutineSteps}
    12251419\end{figure}
    12261420
    12271421Terminating 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.
    1228 Furthermore, each deallocated coroutine must guarantee all destructors are run for object allocated in the coroutine type \emph{and} allocated on the coroutine's stack at the point of suspension, which can be arbitrarily deep.
    1229 When a coroutine's main ends, its stack is already unwound so any stack allocated objects with destructors have been finalized.
    1230 The na\"{i}ve semantics for coroutine-cycle termination is to context switch to the last resumer, like executing a @suspend@/@return@ in a generator.
     1422Furthermore, each deallocated coroutine must execute all destructors for objects allocated in the coroutine type \emph{and} allocated on the coroutine's stack at the point of suspension, which can be arbitrarily deep.
     1423In 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.
     1424% (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.)
     1425When the consumer's main ends, its stack is already unwound so any stack allocated objects with destructors are finalized.
     1426The question now is where does control continue?
     1427
     1428The 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.
    12311429However, for coroutines, the last resumer is \emph{not} implicitly below the current stack frame, as for generators, because each coroutine's stack is independent.
    12321430Unfortunately, it is impossible to determine statically if a coroutine is in a cycle and unrealistic to check dynamically (graph-cycle problem).
    12331431Hence, a compromise solution is necessary that works for asymmetric (acyclic) and symmetric (cyclic) coroutines.
    1234 
    1235 Our solution is to context switch back to the first resumer (starter) once the coroutine ends.
     1432Our solution is to retain a coroutine's starter (first resumer), and context switch back to the starter when the coroutine ends.
     1433Hence, 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}).
    12361434This semantics works well for the most common asymmetric and symmetric coroutine usage patterns.
    1237 For asymmetric coroutines, it is common for the first resumer (starter) coroutine to be the only resumer.
    1238 All previous generators converted to coroutines have this property.
    1239 For symmetric coroutines, it is common for the cycle creator to persist for the lifetime of the cycle.
    1240 Hence, the starter coroutine is remembered on the first resume and ending the coroutine resumes the starter.
    1241 Figure~\ref{f:ProdConsRuntimeStacks} shows this semantic by the dashed lines from the end of the coroutine mains: @prod@ starts @cons@ so @cons@ resumes @prod@ at the end, and the program main starts @prod@ so @prod@ resumes the program main at the end.
    1242 For other scenarios, it is always possible to devise a solution with additional programming effort, such as forcing the cycle forward (backward) to a safe point before starting termination.
    1243 
    1244 The producer/consumer example does not illustrate the full power of the starter semantics because @cons@ always ends first.
    1245 Assume generator @PingPong@ is converted to a coroutine.
    1246 Figure~\ref{f:PingPongFullCoroutineSteps} shows the creation, starter, and cyclic execution steps of the coroutine version.
    1247 The program main creates (declares) coroutine instances @ping@ and @pong@.
    1248 Next, program main resumes @ping@, making it @ping@'s starter, and @ping@'s main resumes @pong@'s main, making it @pong@'s starter.
    1249 Execution forms a cycle when @pong@ resumes @ping@, and cycles $N$ times.
    1250 By adjusting $N$ for either @ping@/@pong@, it is possible to have either one finish first, instead of @pong@ always ending first.
    1251 If @pong@ ends first, it resumes its starter @ping@ in its coroutine main, then @ping@ ends and resumes its starter the program main in function @start@.
    1252 If @ping@ ends first, it resumes its starter the program main in function @start@.
    1253 Regardless of the cycle complexity, the starter stack always leads back to the program main, but the stack can be entered at an arbitrary point.
    1254 Once back at the program main, coroutines @ping@ and @pong@ are deallocated.
    1255 For generators, deallocation runs the destructors for all objects in the generator type.
    1256 For coroutines, deallocation deals with objects in the coroutine type and must also run the destructors for any objects pending on the coroutine's stack for any unterminated coroutine.
    1257 Hence, if a coroutine's destructor detects the coroutine is not ended, it implicitly raises a cancellation exception (uncatchable exception) at the coroutine and resumes it so the cancellation exception can propagate to the root of the coroutine's stack destroying all local variable on the stack.
    1258 So the \CFA semantics for the generator and coroutine, ensure both can be safely deallocated at any time, regardless of their current state, like any other aggregate object.
    1259 Explicitly raising normal exceptions at another coroutine can replace flag variables, like @stop@, \eg @prod@ raises a @stop@ exception at @cons@ after it finishes generating values and resumes @cons@, which catches the @stop@ exception to terminate its loop.
    1260 
    1261 Finally, there is an interesting effect for @suspend@ with symmetric coroutines.
    1262 A coroutine must retain its last resumer to suspend back because the resumer is on a different stack.
    1263 These reverse pointers allow @suspend@ to cycle \emph{backwards}, which may be useful in certain cases.
    1264 However, there is an anomaly if a coroutine resumes itself, because it overwrites its last resumer with itself, losing the ability to resume the last external resumer.
    1265 To prevent losing this information, a self-resume does not overwrite the last resumer.
    1266 
    1267 
    1268 \subsection{Generator / Coroutine Implementation}
    1269 
    1270 A significant implementation challenge for generators/coroutines (and threads in Section~\ref{s:threads}) is adding extra fields to the custom types and related functions, \eg inserting code after/before the coroutine constructor/destructor and @main@ to create/initialize/de-initialize/destroy any extra fields, \eg stack.
    1271 There are several solutions to these problem, which follow from the object-oriented flavour of adopting custom types.
     1435For asymmetric coroutines, it is common for the first resumer (starter) coroutine to be the only resumer;
     1436for symmetric coroutines, it is common for the cycle creator to persist for the lifetime of the cycle.
     1437For 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.
     1438
     1439Note, the producer/consumer example does not illustrate the full power of the starter semantics because @cons@ always ends first.
     1440Assume generator @PingPong@ in Figure~\ref{f:PingPongSymmetricGenerator} is converted to a coroutine.
     1441Unlike generators, coroutines have a starter structure with multiple levels, where the program main starts @ping@ and @ping@ starts @pong@.
     1442By adjusting $N$ for either @ping@ or @pong@, it is possible to have either finish first.
     1443If @pong@ ends first, it resumes its starter @ping@ in its coroutine main, then @ping@ ends and resumes its starter the program main on return;
     1444if @ping@ ends first, it resumes its starter the program main on return.
     1445Regardless of the cycle complexity, the starter structure always leads back to the program main, but the path can be entered at an arbitrary point.
     1446Once back at the program main (creator), coroutines @ping@ and @pong@ are deallocated, running 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.
     1447Hence, the \CFA termination semantics for the generator and coroutine ensure correct deallocation semantics, regardless of the coroutine's state (terminated or active), like any other aggregate object.
     1448
     1449
     1450\subsection{Generator / coroutine implementation}
     1451
     1452A 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.
     1453There are several solutions to this problem, which follow from the object-oriented flavor of adopting custom types.
    12721454
    12731455For object-oriented languages, inheritance is used to provide extra fields and code via explicit inheritance:
     
    12761458\end{cfa}
    12771459% 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.
    1278 The problem is that some special properties are not handled by existing language semantics, \eg the execution of constructors/destructors is in the wrong order to implicitly start threads because the thread must start \emph{after} all constructors as it relies on a completely initialized object, but the inherited constructor runs \emph{before} the derived.
     1460The 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.
    12791461Alternatives, such as explicitly starting threads as in Java, are repetitive and forgetting to call start is a common source of errors.
    12801462An alternative is composition:
     
    12941476Users wanting to extend custom types or build their own can only do so in ways offered by the language.
    12951477Furthermore, implementing custom types without language support may display the power of a programming language.
    1296 \CFA blends the two approaches, providing custom type for idiomatic \CFA code, while extending and building new custom types is still possible, similar to Java concurrency with builtin and library.
     1478\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.
    12971479
    12981480Part 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.
     
    13041486forall( `dtype` T | is_coroutine(T) ) void $suspend$( T & ), resume( T & );
    13051487\end{cfa}
    1306 Note, copying generators/coroutines/threads is not meaningful.
    1307 For example, both the resumer and suspender descriptors can have bidirectional pointers;
    1308 copying these coroutines does not update the internal pointers so behaviour of both copies would be difficult to understand.
    1309 Furthermore, two coroutines cannot logically execute on the same stack.
    1310 A deep coroutine copy, which copies the stack, is also meaningless in an unmanaged language (no garbage collection), like C, because the stack may contain pointers to object within it that require updating for the copy.
    1311 The \CFA @dtype@ property provides no \emph{implicit} copying operations and the @is_coroutine@ trait provides no \emph{explicit} copying operations, so all coroutines must be passed by reference (pointer).
    1312 The function definitions ensure there is a statically typed @main@ function that is the starting point (first stack frame) of a coroutine, and a mechanism to get (read) the coroutine descriptor from its handle.
    1313 The @main@ function has no return value or additional parameters because the coroutine type allows an arbitrary number of interface functions with corresponding arbitrary typed input/output values versus fixed ones.
     1488Note, copying generators, coroutines, and threads is undefined because multiple 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.
     1489The \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.
     1490The 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.
     1491The @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.
    13141492The 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@.
    13151493
     
    13521530The 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.
    13531531
    1354 Figure~\ref{f:CoroutineMemoryLayout} shows different memory-layout options for a coroutine (where a task is similar).
    1355 The coroutine handle is the @coroutine@ instance containing programmer specified type global/communication variables across interface functions.
     1532Figure~\ref{f:CoroutineMemoryLayout} shows different memory-layout options for a coroutine (where a thread is similar).
     1533The coroutine handle is the @coroutine@ instance containing programmer specified type global and communication variables across interface functions.
    13561534The coroutine descriptor contains all implicit declarations needed by the runtime, \eg @suspend@/@resume@, and can be part of the coroutine handle or separate.
    13571535The coroutine stack can appear in a number of locations and be fixed or variable sized.
    1358 Hence, the coroutine's stack could be a VLS\footnote{
    1359 We are examining variable-sized structures (VLS), where fields can be variable-sized structures or arrays.
    1360 Once allocated, a VLS is fixed sized.}
     1536Hence, the coroutine's stack could be a variable-length structure (VLS)
     1537% \footnote{
     1538% We are examining VLSs, where fields can be variable-sized structures or arrays.
     1539% Once allocated, a VLS is fixed sized.}
    13611540on the allocating stack, provided the allocating stack is large enough.
    1362 For a VLS stack allocation/deallocation is an inexpensive adjustment of the stack pointer, modulo any stack constructor costs (\eg initial frame setup).
    1363 For heap stack allocation, allocation/deallocation is an expensive heap allocation (where the heap can be a shared resource), modulo any stack constructor costs.
    1364 With heap stack allocation, it is also possible to use a split (segmented) stack calling convention, available with gcc and clang, so the stack is variable sized.
    1365 Currently, \CFA supports stack/heap allocated descriptors but only fixed-sized heap allocated stacks.
     1541For a VLS stack allocation and deallocation is an inexpensive adjustment of the stack pointer, modulo any stack constructor costs to initial frame setup.
     1542For 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.
     1543It 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.
     1544Currently, \CFA supports stack and heap allocated descriptors but only fixed-sized heap allocated stacks.
    13661545In \CFA debug-mode, the fixed-sized stack is terminated with a write-only page, which catches most stack overflows.
    13671546Experience teaching concurrency with \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue for students.
    1368 Split-stack allocation is under development but requires recompilation of legacy code, which may be impossible.
     1547Split-stack allocation is under development but requires recompilation of legacy code, which is not always possible.
    13691548
    13701549\begin{figure}
     
    13801559
    13811560Concurrency is nondeterministic scheduling of independent sequential execution paths (threads), where each thread has its own stack.
    1382 A single thread with multiple call stacks, \newterm{coroutining}~\cite{Conway63,Marlin80}, does \emph{not} imply concurrency~\cite[\S~2]{Buhr05a}.
    1383 In coroutining, coroutines self-schedule the thread across stacks so execution is deterministic.
     1561A single thread with multiple stacks, \ie coroutining, does \emph{not} imply concurrency~\cite[\S~3]{Buhr05a}.
     1562Coroutining self-schedule the thread across stacks so execution is deterministic.
    13841563(It is \emph{impossible} to generate a concurrency error when coroutining.)
    1385 However, coroutines are a stepping stone towards concurrency.
    1386 
    1387 The 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}.
     1564
     1565The 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}.
    13881566Therefore, a minimal concurrency system requires coroutines \emph{in conjunction with a nondeterministic scheduler}.
    1389 The resulting execution system now follows a cooperative threading model~\cite{Adya02,libdill}, called \newterm{non-preemptive scheduling}.
    1390 Adding \newterm{preemption} introduces non-cooperative scheduling, where context switching occurs randomly between any two instructions often based on a timer interrupt, called \newterm{preemptive scheduling}.
    1391 While a scheduler introduces uncertain execution among explicit context switches, preemption introduces uncertainty by introducing implicit context switches.
     1567The 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.
     1568Adding \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.
    13921569Uncertainty gives the illusion of parallelism on a single processor and provides a mechanism to access and increase performance on multiple processors.
    1393 The reason is that the scheduler/runtime have complete knowledge about resources and how to best utilized them.
    1394 However, the introduction of unrestricted nondeterminism results in the need for \newterm{mutual exclusion} and \newterm{synchronization}, which restrict nondeterminism for correctness;
     1570The reason is that the scheduler and runtime have complete knowledge about resources and how to best utilized them.
     1571However, 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;
    13951572otherwise, it is impossible to write meaningful concurrent programs.
    13961573Optimal concurrent performance is often obtained by having as much nondeterminism as mutual exclusion and synchronization correctness allow.
    13971574
    1398 A scheduler can either be a stackless or stackful.
     1575A scheduler can also be stackless or stackful.
    13991576For 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.
    14001577For 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.
     
    14051582\label{s:threads}
    14061583
    1407 Threading needs the ability to start a thread and wait for its completion.
    1408 A common API for this ability is @fork@ and @join@.
    1409 \begin{cquote}
    1410 \begin{tabular}{@{}lll@{}}
    1411 \multicolumn{1}{c}{\textbf{Java}} & \multicolumn{1}{c}{\textbf{\Celeven}} & \multicolumn{1}{c}{\textbf{pthreads}} \\
    1412 \begin{cfa}
    1413 class MyTask extends Thread {...}
    1414 mytask t = new MyTask(...);
     1584Threading (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@.
     1585\vspace{4pt}
     1586\par\noindent
     1587\begin{tabular}{@{}l|l|l@{}}
     1588\multicolumn{1}{c|}{\textbf{Java}} & \multicolumn{1}{c|}{\textbf{\Celeven}} & \multicolumn{1}{c}{\textbf{pthreads}} \\
     1589\hline
     1590\begin{cfa}
     1591class MyThread extends Thread {...}
     1592mythread t = new MyThread(...);
    14151593`t.start();` // start
    14161594// concurrency
     
    14191597&
    14201598\begin{cfa}
    1421 class MyTask { ... } // functor
    1422 MyTask mytask;
    1423 `thread t( mytask, ... );` // start
     1599class MyThread { ... } // functor
     1600MyThread mythread;
     1601`thread t( mythread, ... );` // start
    14241602// concurrency
    14251603`t.join();` // wait
     
    14341612\end{cfa}
    14351613\end{tabular}
    1436 \end{cquote}
    1437 \CFA has a simpler approach using a custom @thread@ type and leveraging declaration semantics (allocation/deallocation), where threads implicitly @fork@ after construction and @join@ before destruction.
    1438 \begin{cfa}
    1439 thread MyTask {};
    1440 void main( MyTask & this ) { ... }
     1614\vspace{1pt}
     1615\par\noindent
     1616\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.
     1617\begin{cfa}
     1618thread MyThread {};
     1619void main( MyThread & this ) { ... }
    14411620int main() {
    1442         MyTask team`[10]`; $\C[2.5in]{// allocate stack-based threads, implicit start after construction}$
     1621        MyThread team`[10]`; $\C[2.5in]{// allocate stack-based threads, implicit start after construction}$
    14431622        // concurrency
    14441623} $\C{// deallocate stack-based threads, implicit joins before destruction}$
    14451624\end{cfa}
    1446 This semantic ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
    1447 For block allocation to arbitrary depth, including recursion, threads are created/destroyed in a lattice structure (tree with top and bottom).
     1625This semantic ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic termination synchronization.
     1626For block allocation to arbitrary depth, including recursion, threads are created and destroyed in a lattice structure (tree with top and bottom).
    14481627Arbitrary topologies are possible using dynamic allocation, allowing threads to outlive their declaration scope, identical to normal dynamic allocation.
    14491628\begin{cfa}
    1450 MyTask * factory( int N ) { ... return `anew( N )`; } $\C{// allocate heap-based threads, implicit start after construction}$
     1629MyThread * factory( int N ) { ... return `anew( N )`; } $\C{// allocate heap-based threads, implicit start after construction}$
    14511630int main() {
    1452         MyTask * team = factory( 10 );
     1631        MyThread * team = factory( 10 );
    14531632        // concurrency
    1454         `delete( team );` $\C{// deallocate heap-based threads, implicit joins before destruction}\CRT$
     1633        `adelete( team );` $\C{// deallocate heap-based threads, implicit joins before destruction}\CRT$
    14551634}
    14561635\end{cfa}
     
    14931672
    14941673
    1495 \subsection{Thread Implementation}
     1674\subsection{Thread implementation}
    14961675
    14971676Threads 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.
    1498 Like coroutines, and for the same design reasons, \CFA provides a custom @thread@ type and a @trait@ to enforce and restrict the task-interface functions.
     1677Like coroutines, and for the same design reasons, \CFA provides a custom @thread@ type and a @trait@ to enforce and restrict the thread-interface functions.
    14991678\begin{cquote}
    15001679\begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}}
     
    15161695\end{tabular}
    15171696\end{cquote}
    1518 Like coroutines, the @dtype@ property prevents \emph{implicit} copy operations and the @is_thread@ trait provides no \emph{explicit} copy operations, so threads must be passed by reference (pointer).
    1519 Similarly, the function definitions ensure there is a statically typed @main@ function that is the thread starting point (first stack frame), a mechanism to get (read) the thread descriptor from its handle, and a special destructor to prevent deallocation while the thread is executing.
     1697Like 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.
     1698Similarly, 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.
    15201699(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitor}.)
    15211700The 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;
    15221701whereas, a thread is scheduling for execution in @main@ immediately after its constructor is run.
    1523 No return value or additional parameters are necessary for this function because the @thread@ type allows an arbitrary number of interface functions with corresponding arbitrary typed input/output values.
     1702No 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.
    15241703
    15251704
     
    15271706\label{s:MutualExclusionSynchronization}
    15281707
    1529 Unrestricted nondeterminism is meaningless as there is no way to know when the result is completed without synchronization.
     1708Unrestricted nondeterminism is meaningless as there is no way to know when a result is completed and safe to access.
    15301709To 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}.
    1531 Some concurrent systems eliminate mutable shared-state by switching to stateless communication like message passing~\cite{Thoth,Harmony,V-Kernel,MPI} (Erlang, MPI), channels~\cite{CSP} (CSP,Go), actors~\cite{Akka} (Akka, Scala), or functional techniques (Haskell).
     1710The shared data protected by mutual exclusion 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.
     1711Without 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.
     1712Preventing or detecting barging is a challenge with low-level locks, but made easier through higher-level constructs.
     1713This challenge is often split into two different approaches: barging \emph{avoidance} and \emph{prevention}.
     1714Approaches 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;
     1715approaches that conditionally hold locks during synchronization, \eg baton-passing~\cite{Andrews89}, prevent barging completely.
     1716
     1717At 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}.
     1718However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}.
     1719A significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock.
     1720Easing composability is another feature higher-level mutual-exclusion mechanisms can offer.
     1721Some 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).
    15321722However, these approaches introduce a new communication mechanism for concurrency different from the standard communication using function call/return.
    1533 Hence, a programmer must learn and manipulate two sets of design/programming patterns.
     1723Hence, a programmer must learn and manipulate two sets of design and programming patterns.
    15341724While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
    1535 In contrast, approaches based on stateful models more closely resemble the standard call/return programming model, resulting in a single programming paradigm.
    1536 
    1537 At the lowest level, concurrent control is implemented by atomic operations, upon which different kinds of locking mechanisms are constructed, \eg semaphores~\cite{Dijkstra68b}, barriers, and path expressions~\cite{Campbell74}.
    1538 However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}.
    1539 A newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
    1540 While this approach is pursued in hardware~\cite{Nakaike15} and system languages, like \CC~\cite{Cpp-Transactions}, the performance and feature set is still too restrictive to be the main concurrency paradigm for system languages, which is why it is rejected as the core paradigm for concurrency in \CFA.
    1541 
    1542 One of the most natural, elegant, and efficient mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor}.
    1543 First 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}.
    1544 In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as mutex locks or semaphores to simulate monitors.
    1545 For these reasons, \CFA selected monitors as the core high-level concurrency construct, upon which higher-level approaches can be easily constructed.
    1546 
    1547 
    1548 \subsection{Mutual Exclusion}
    1549 
    1550 A group of instructions manipulating a specific instance of shared data that must be performed atomically is called a \newterm{critical section}~\cite{Dijkstra65}, which is enforced by \newterm{simple mutual-exclusion}.
    1551 The generalization is called a \newterm{group critical-section}~\cite{Joung00}, where multiple tasks with the same session use the resource simultaneously and different sessions are segregated, which is enforced by \newterm{complex mutual-exclusion} providing the correct kind and number of threads using a group critical-section.
    1552 The readers/writer problem~\cite{Courtois71} is an instance of a group critical-section, where readers share a session but writers have a unique session.
    1553 
    1554 However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use.
    1555 Methods range from low-level locks, which are fast and flexible but require significant attention for correctness, to higher-level concurrency techniques, which sacrifice some performance to improve ease of use.
    1556 Ease of use comes by either guaranteeing some problems cannot occur, \eg deadlock free, or by offering a more explicit coupling between shared data and critical section.
    1557 For example, the \CC @std::atomic<T>@ offers an easy way to express mutual-exclusion on a restricted set of operations, \eg reading/writing, for numerical types.
    1558 However, a significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock.
    1559 Easing composability is another feature higher-level mutual-exclusion mechanisms can offer.
    1560 
    1561 
    1562 \subsection{Synchronization}
    1563 
    1564 Synchronization enforces relative ordering of execution, and synchronization tools provide numerous mechanisms to establish these timing relationships.
    1565 Low-level synchronization primitives offer good performance and flexibility at the cost of ease of use;
    1566 higher-level mechanisms often simplify usage by adding better coupling between synchronization and data, \eg receive-specific versus receive-any thread in message passing or offering specialized solutions, \eg barrier lock.
    1567 Often synchronization is used to order access to a critical section, \eg ensuring a waiting writer thread enters the critical section before a calling reader thread.
    1568 If the calling reader is scheduled before the waiting writer, the reader has barged.
    1569 Barging can result in staleness/freshness problems, where a reader barges ahead of a writer and reads temporally stale data, or a writer barges ahead of another writer overwriting data with a fresh value preventing the previous value from ever being read (lost computation).
    1570 Preventing or detecting barging is an involved challenge with low-level locks, which is made easier through higher-level constructs.
    1571 This challenge is often split into two different approaches: barging avoidance and prevention.
    1572 Algorithms that unconditionally releasing a lock for competing threads to acquire use barging avoidance during synchronization to force a barging thread to wait;
    1573 algorithms that conditionally hold locks during synchronization, \eg baton-passing~\cite{Andrews89}, prevent barging completely.
     1725In contrast, approaches based on shared-state models more closely resemble the standard call and return programming model, resulting in a single programming paradigm.
     1726Finally, a newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
     1727While 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.
    15741728
    15751729
     
    15771731\label{s:Monitor}
    15781732
    1579 A \textbf{monitor} is a set of functions that ensure mutual exclusion when accessing shared state.
    1580 More precisely, a monitor is a programming technique that implicitly binds mutual exclusion to static function scope, as opposed to locks, where mutual-exclusion is defined by acquire/release calls, independent of lexical context (analogous to block and heap storage allocation).
    1581 Restricting acquire/release points eases programming, comprehension, and maintenance, at a slight cost in flexibility and efficiency.
    1582 \CFA uses a custom @monitor@ type and leverages declaration semantics (deallocation) to protect active or waiting threads in a monitor.
    1583 
    1584 The following is a \CFA monitor implementation of an atomic counter.
    1585 \begin{cfa}[morekeywords=nomutex]
    1586 `monitor` Aint { int cnt; }; $\C[4.25in]{// atomic integer counter}$
    1587 int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$
    1588 int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions with int}\CRT$
    1589 int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; }
    1590 \end{cfa}
    1591 % The @Aint@ constructor, @?{}@, uses the \lstinline[morekeywords=nomutex]@nomutex@ qualifier indicating mutual exclusion is unnecessary during construction because an object is inaccessible (private) until after it is initialized.
    1592 % (While a constructor may publish its address into a global variable, doing so generates a race-condition.)
    1593 The prefix increment operation, @++?@, is normally @mutex@, indicating mutual exclusion is necessary during function execution, to protect the incrementing from race conditions, unless there is an atomic increment instruction for the implementation type.
    1594 The assignment operators provide bidirectional conversion between an atomic and normal integer without accessing field @cnt@;
    1595 these operations only need @mutex@, if reading/writing the implementation type is not atomic.
    1596 The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics, which is similar to the \CC template @std::atomic@.
    1597 \begin{cfa}
     1733One 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).
     1734First 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}.
     1735In 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.
     1736For these reasons, \CFA selected monitors as the core high-level concurrency construct, upon which higher-level approaches can be easily constructed.
     1737
     1738Figure~\ref{f:AtomicCounter} compares a \CFA and Java monitor implementing an atomic counter.
     1739(Like other concurrent programming languages, \CFA and Java have performant specializations for the basic types using atomic instructions.)
     1740A \newterm{monitor} is a set of functions that ensure mutual exclusion when accessing shared state.
     1741(Note, in \CFA, @monitor@ is short-hand for @mutex struct@.)
     1742More 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).
     1743Restricting acquire and release points eases programming, comprehension, and maintenance, at a slight cost in flexibility and efficiency.
     1744As for other special types, \CFA has a custom @monitor@ type.
     1745
     1746\begin{figure}
     1747\centering
     1748
     1749\begin{lrbox}{\myboxA}
     1750\begin{cfa}[aboveskip=0pt,belowskip=0pt]
     1751`monitor` Aint { // atomic integer counter
     1752        int cnt;
     1753};
     1754int ++?( Aint & `mutex` this ) with(this) { return ++cnt; }
     1755int ?=?( Aint & `mutex` lhs, int rhs ) with(lhs) { cnt = rhs; }
     1756int ?=?(int & lhs, Aint & rhs) with(rhs) { lhs = cnt; }
     1757
    15981758int i = 0, j = 0, k = 5;
    1599 Aint x = { 0 }, y = { 0 }, z = { 5 }; $\C{// no mutex required}$
    1600 ++x; ++y; ++z; $\C{// safe increment by multiple threads}$
    1601 x = 2; y = i; z = k; $\C{// conversions}$
    1602 i = x; j = y; k = z;
    1603 \end{cfa}
    1604 
    1605 \CFA monitors have \newterm{multi-acquire} semantics so the thread in the monitor may acquire it multiple times without deadlock, allowing recursion and calling other interface functions.
    1606 \begin{cfa}
    1607 monitor M { ... } m;
    1608 void foo( M & mutex m ) { ... } $\C{// acquire mutual exclusion}$
    1609 void bar( M & mutex m ) { $\C{// acquire mutual exclusion}$
    1610         ... `bar( m );` ... `foo( m );` ... $\C{// reacquire mutual exclusion}$
    1611 }
    1612 \end{cfa}
    1613 \CFA monitors also ensure the monitor lock is released regardless of how an acquiring function ends (normal or exceptional), and returning a shared variable is safe via copying before the lock is released.
    1614 Similar safety is offered by \emph{explicit} mechanisms like \CC RAII;
    1615 monitor \emph{implicit} safety ensures no programmer usage errors.
    1616 Furthermore, 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;
     1759Aint x = { 0 }, y = { 0 }, z = { 5 }; // no mutex
     1760++x; ++y; ++z;     // mutex
     1761x = 2; y = i; z = k;  // mutex
     1762i = x; j = y; k = z;  // no mutex
     1763\end{cfa}
     1764\end{lrbox}
     1765
     1766\begin{lrbox}{\myboxB}
     1767\begin{java}[aboveskip=0pt,belowskip=0pt]
     1768class Aint {
     1769    private int cnt;
     1770    public Aint( int init ) { cnt = init; }
     1771    `synchronized` public int inc() { return ++cnt; }
     1772    `synchronized` public void set( int rhs ) {cnt=rhs;}
     1773    public int get() { return cnt; }
     1774}
     1775int i = 0, j = 0, k = 5;
     1776Aint x=new Aint(0), y=new Aint(0), z=new Aint(5);
     1777x.inc(); y.inc(); z.inc();
     1778x.set( 2 ); y.set( i ); z.set( k );
     1779i = x.get(); j = y.get(); k = z.get();
     1780\end{java}
     1781\end{lrbox}
     1782
     1783\subfloat[\CFA]{\label{f:AtomicCounterCFA}\usebox\myboxA}
     1784\hspace{3pt}
     1785\vrule
     1786\hspace{3pt}
     1787\subfloat[Java]{\label{f:AtomicCounterJava}\usebox\myboxB}
     1788\caption{Atomic counter}
     1789\label{f:AtomicCounter}
     1790\end{figure}
     1791
     1792Like 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.
     1793% \begin{cfa}
     1794% monitor M { ... } m;
     1795% void foo( M & mutex m ) { ... } $\C{// acquire mutual exclusion}$
     1796% void bar( M & mutex m ) { $\C{// acquire mutual exclusion}$
     1797%       ... `bar( m );` ... `foo( m );` ... $\C{// reacquire mutual exclusion}$
     1798% }
     1799% \end{cfa}
     1800\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.
     1801Similar 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.
     1802However, 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;
    16171803RAII is purely a mutual-exclusion mechanism (see Section~\ref{s:Scheduling}).
    16181804
    1619 
    1620 \subsection{Monitor Implementation}
     1805Both 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.
     1806Non-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.
     1807Monitor objects can be passed through multiple helper functions without acquiring mutual exclusion, until a designated function associated with the object is called.
     1808\CFA designated functions are marked by an explicitly parameter-only pointer/reference qualifier @mutex@ (discussed further in Section\ref{s:MutexAcquisition}).
     1809Whereas, Java designated members are marked with \lstinline[language=java]|synchronized| that applies to the implicit reference parameter @this@.
     1810In the example, the increment and setter operations need mutual exclusion while the read-only getter operation can be nonmutex if reading the implementation is atomic.
     1811
     1812
     1813\subsection{Monitor implementation}
    16211814
    16221815For the same design reasons, \CFA provides a custom @monitor@ type and a @trait@ to enforce and restrict the monitor-interface functions.
     
    16381831\end{tabular}
    16391832\end{cquote}
    1640 The @dtype@ property prevents \emph{implicit} copy operations and the @is_monitor@ trait provides no \emph{explicit} copy operations, so monitors must be passed by reference (pointer).
    1641 % Copying a lock is insecure because it is possible to copy an open lock and then use the open copy when the original lock is closed to simultaneously access the shared data.
    1642 % Copying a monitor is secure because both the lock and shared data are copies, but copying the shared data is meaningless because it no longer represents a unique entity.
    1643 Similarly, the function definitions ensures there is a mechanism to get (read) the monitor descriptor from its handle, and a special destructor to prevent deallocation if a thread using the shared data.
     1833The @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.
     1834Similarly, the function definitions ensure 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.
    16441835The custom monitor type also inserts any locks needed to implement the mutual exclusion semantics.
    1645 
    1646 
    1647 \subsection{Mutex Acquisition}
     1836\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.
     1837
     1838
     1839\subsection{Mutex acquisition}
    16481840\label{s:MutexAcquisition}
    16491841
    1650 While the monitor lock provides mutual exclusion for shared data, there are implementation options for when and where the locking/unlocking occurs.
    1651 (Much of this discussion also applies to basic locks.)
    1652 For example, a monitor may be passed through multiple helper functions before it is necessary to acquire the monitor's mutual exclusion.
    1653 
    1654 The benefit of mandatory monitor qualifiers is self-documentation, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameters is redundant.
    1655 Instead, the semantics has one qualifier as the default and the other required.
    1656 For example, make the safe @mutex@ qualifier the default because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors.
    1657 Alternatively, make the unsafe \lstinline[morekeywords=nomutex]@nomutex@ qualifier the default because it is the \emph{normal} parameter semantics while @mutex@ parameters are rare.
    1658 Providing a default qualifier implies knowing whether a parameter is a monitor.
    1659 Since \CFA relies heavily on traits as an abstraction mechanism, types can coincidentally match the monitor trait but not be a monitor, similar to inheritance where a shape and playing card can both be drawable.
    1660 For this reason, \CFA requires programmers to identify the kind of parameter with the @mutex@ keyword and uses no keyword to mean \lstinline[morekeywords=nomutex]@nomutex@.
    1661 
    1662 The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@.
    1663 The following has monitor parameter types that are composed of multiple objects.
    1664 \begin{cfa}
    1665 monitor M { ... }
     1842For object-oriented programming languages, the mutex property applies to one object, the implicit pointer/reference to the monitor type.
     1843Because \CFA uses a pointer qualifier, other possibilities exist, \eg:
     1844\begin{cfa}
     1845monitor M { ... };
    16661846int f1( M & mutex m ); $\C{// single parameter object}$
    16671847int f2( M * mutex m ); $\C{// single or multiple parameter object}$
     
    16691849int f4( stack( M * ) & mutex m ); $\C{// multiple parameters object}$
    16701850\end{cfa}
    1671 Function @f1@ has a single parameter object, while @f2@'s indirection could be a single or multi-element array, where static array size is often unknown in C.
    1672 Function @f3@ has a multiple object matrix, and @f4@ a multiple object data structure.
    1673 While shown shortly, multiple object acquisition is possible, but the number of objects must be statically known.
    1674 Therefore, \CFA only acquires one monitor per parameter with at most one level of indirection, excluding pointers as it is impossible to statically determine the size.
    1675 
    1676 For object-oriented monitors, \eg Java, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
    1677 \CFA has no receiver, and hence, the explicit @mutex@ qualifier is used to specify which objects acquire mutual exclusion.
    1678 A positive consequence of this design decision is the ability to support multi-monitor functions,\footnote{
     1851Function @f1@ has a single object parameter, while functions @f2@ to @f4@ can be a single or multi-element parameter with statically unknown size.
     1852Because of the statically unknown size, \CFA only supports a single reference @mutex@ parameter, @f1@.
     1853
     1854The \CFA @mutex@ qualifier does allow the ability to support multimonitor functions,\footnote{
    16791855While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.}
    1680 called \newterm{bulk acquire}.
    1681 \CFA guarantees acquisition order is consistent across calls to @mutex@ functions using the same monitors as arguments, so acquiring multiple monitors is safe from deadlock.
     1856where the number of acquisitions is statically known, called \newterm{bulk acquire}.
     1857\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.
    16821858Figure~\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.
    16831859A \CFA programmer only has to manage when to acquire mutual exclusion;
     
    16991875void transfer( BankAccount & `mutex` my,
    17001876        BankAccount & `mutex` your, int me2you ) {
    1701 
     1877        // bulk acquire
    17021878        deposit( my, -me2you ); // debit
    17031879        deposit( your, me2you ); // credit
     
    17291905void transfer( BankAccount & my,
    17301906                        BankAccount & your, int me2you ) {
    1731         `scoped_lock lock( my.m, your.m );`
     1907        `scoped_lock lock( my.m, your.m );` // bulk acquire
    17321908        deposit( my, -me2you ); // debit
    17331909        deposit( your, me2you ); // credit
     
    17571933\end{figure}
    17581934
    1759 Users can still force the acquiring order by using @mutex@/\lstinline[morekeywords=nomutex]@nomutex@.
     1935Users can still force the acquiring order by using or not using @mutex@.
    17601936\begin{cfa}
    17611937void foo( M & mutex m1, M & mutex m2 ); $\C{// acquire m1 and m2}$
    1762 void bar( M & mutex m1, M & /* nomutex */ m2 ) { $\C{// acquire m1}$
     1938void bar( M & mutex m1, M & m2 ) { $\C{// only acquire m1}$
    17631939        ... foo( m1, m2 ); ... $\C{// acquire m2}$
    17641940}
    1765 void baz( M & /* nomutex */ m1, M & mutex m2 ) { $\C{// acquire m2}$
     1941void baz( M & m1, M & mutex m2 ) { $\C{// only acquire m2}$
    17661942        ... foo( m1, m2 ); ... $\C{// acquire m1}$
    17671943}
     
    18061982% 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.
    18071983% 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.
    1808 This section discusses monitor scheduling for waiting threads eligible for entry, \ie which thread gets the shared resource next. (See Section~\ref{s:RuntimeStructureCluster} for scheduling threads on virtual processors.)
    1809 While monitor mutual-exclusion provides safe access to shared data, the monitor data may indicate that a thread accessing it cannot proceed, \eg a bounded buffer may be full/empty so produce/consumer threads must block.
    1810 Leaving the monitor and trying again (busy waiting) is impractical for high-level programming.
    1811 Monitors eliminate busy waiting by providing synchronization to schedule threads needing access to the shared data, where threads block versus spinning.
     1984This section discusses scheduling for waiting threads eligible for monitor entry~\cite{Buhr95b}, \ie which user thread gets the shared resource next.
     1985(See Section~\ref{s:RuntimeStructureCluster} for scheduling kernel threads on virtual processors.)
     1986While 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.
     1987Leaving the monitor and retrying (busy waiting) is impractical for high-level programming.
     1988
     1989Monitors 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.
    18121990Synchronization is generally achieved with internal~\cite{Hoare74} or external~\cite[\S~2.9.2]{uC++} scheduling.
    1813 \newterm{Internal scheduling} is characterized by each thread entering the monitor and making an individual decision about proceeding or blocking, while \newterm{external scheduling} is characterized by an entering thread making a decision about proceeding for itself and on behalf of other threads attempting entry.
    1814 Finally, \CFA monitors do not allow calling threads to barge ahead of signalled threads, which simplifies synchronization among threads in the monitor and increases correctness.
    1815 If barging is allowed, synchronization between a signaller and signallee is difficult, often requiring additional flags and multiple unblock/block cycles.
    1816 In fact, signals-as-hints is completely opposite from that proposed by Hoare in the seminal paper on monitors~\cite[p.~550]{Hoare74}.
     1991\newterm{Internal} largely schedules threads located \emph{inside} the monitor and is accomplished using condition variables with signal and wait.
     1992\newterm{External} largely schedules threads located \emph{outside} the monitor and is accomplished with the @waitfor@ statement.
     1993Note, 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.
     1994For complex scheduling, the approaches can be combined, so there are threads waiting inside and outside.
     1995
     1996\CFA monitors do not allow calling threads to barge ahead of signaled threads via barging prevention, which simplifies synchronization among threads in the monitor and increases correctness.
     1997A 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.
     1998Preventing barging comes directly from Hoare's semantics in the seminal paper on monitors~\cite[p.~550]{Hoare74}.
    18171999% \begin{cquote}
    18182000% However, we decree that a signal operation be followed immediately by resumption of a waiting program, without possibility of an intervening procedure call from yet a third program.
    1819 % It is only in this way that a waiting program has an absolute guarantee that it can acquire the resource just released by the signalling program without any danger that a third program will interpose a monitor entry and seize the resource instead.~\cite[p.~550]{Hoare74}
     2001% It is only in this way that a waiting program has an absolute guarantee that it can acquire the resource just released by the signaling program without any danger that a third program will interpose a monitor entry and seize the resource instead.~\cite[p.~550]{Hoare74}
    18202002% \end{cquote}
    1821 Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implicit form of self barging.
    1822 Hence, a \CFA @wait@ statement is not enclosed in a @while@ loop retesting a blocking predicate, which can cause thread starvation due to barging.
    1823 
    1824 Figure~\ref{f:MonitorScheduling} shows general internal/external scheduling (for the bounded-buffer example in Figure~\ref{f:InternalExternalScheduling}).
    1825 External calling threads block on the calling queue, if the monitor is occupied, otherwise they enter in FIFO order.
    1826 Internal threads block on condition queues via @wait@ and reenter from the condition in FIFO order.
    1827 Alternatively, internal threads block on urgent from the @signal_block@ or @waitfor@, and reenter implicitly when the monitor becomes empty, \ie, the thread in the monitor exits or waits.
    1828 
    1829 There are three signalling mechanisms to unblock waiting threads to enter the monitor.
    1830 Note, signalling cannot have the signaller and signalled thread in the monitor simultaneously because of the mutual exclusion, so either the signaller or signallee can proceed.
    1831 For internal scheduling, threads are unblocked from condition queues using @signal@, where the signallee is moved to urgent and the signaller continues (solid line).
    1832 Multiple signals move multiple signallees to urgent until the condition is empty.
    1833 When the signaller exits or waits, a thread blocked on urgent is processed before calling threads to prevent barging.
    1834 (Java conceptually moves the signalled thread to the calling queue, and hence, allows barging.)
    1835 The alternative unblock is in the opposite order using @signal_block@, where the signaller is moved to urgent and the signallee continues (dashed line), and is implicitly unblocked from urgent when the signallee exits or waits.
    1836 
    1837 For external scheduling, the condition queues are not used;
    1838 instead threads are unblocked directly from the calling queue using @waitfor@ based on function names requesting mutual exclusion.
    1839 (The linear search through the calling queue to locate a particular call can be reduced to $O(1)$.)
    1840 The @waitfor@ has the same semantics as @signal_block@, where the signalled thread executes before the signallee, which waits on urgent.
    1841 Executing multiple @waitfor@s from different signalled functions causes the calling threads to move to urgent.
    1842 External scheduling requires urgent to be a stack, because the signaller expects to execute immediately after the specified monitor call has exited or waited.
    1843 Internal scheduling behaves the same for an urgent stack or queue, except for multiple signalling, where the threads unblock from urgent in reverse order from signalling.
    1844 If the restart order is important, multiple signalling by a signal thread can be transformed into daisy-chain signalling among threads, where each thread signals the next thread.
    1845 We tried both a stack for @waitfor@ and queue for signalling, but that resulted in complex semantics about which thread enters next.
    1846 Hence, \CFA uses a single urgent stack to correctly handle @waitfor@ and adequately support both forms of signalling.
     2003Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implicit self barging.
     2004
     2005Monitor mutual-exclusion means signaling cannot have the signaller and signaled 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}.
     2006Figure~\ref{f:MonitorScheduling} shows internal and external scheduling for the bounded-buffer examples in Figure~\ref{f:GenericBoundedBuffer}.
     2007For 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).
     2008Multiple signals move multiple signallees to urgent until the condition queue is empty.
     2009When the signaller exits or waits, a thread is implicitly unblocked from urgent, if available, before unblocking a calling thread to prevent barging.
     2010(Java conceptually moves the signaled thread to the calling queue, and hence, allows barging.)
     2011Signal 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 signaled thread, which can immediately take advantage of the state change.
     2012Specifically, the @wait@ function atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the function's parameter list.
     2013Signalling is unconditional because signaling an empty condition queue does nothing.
     2014It 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.
     2015In \CFA, a condition queue can be created and stored independently.
    18472016
    18482017\begin{figure}
     
    18622031\end{figure}
    18632032
    1864 Figure~\ref{f:BBInt} shows a \CFA generic bounded-buffer with internal scheduling, where producers/consumers enter the monitor, detect the buffer is full/empty, and block on an appropriate condition variable, @full@/@empty@.
    1865 The @wait@ function atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the function's parameter list.
    1866 The appropriate condition variable is signalled to unblock an opposite kind of thread after an element is inserted/removed from the buffer.
    1867 Signalling is unconditional, because signalling an empty condition variable does nothing.
    1868 It is common to declare condition variables as monitor fields to prevent shared access, hence no locking is required for access as the conditions are protected by the monitor lock.
    1869 In \CFA, a condition variable can be created/stored independently.
    1870 % To still prevent expensive locking on access, a condition variable is tied to a \emph{group} of monitors on first use, called \newterm{branding}, resulting in a low-cost boolean test to detect sharing from other monitors.
    1871 
    1872 % Signalling semantics cannot have the signaller and signalled thread in the monitor simultaneously, which means:
    1873 % \begin{enumerate}
    1874 % \item
    1875 % The signalling thread returns immediately and the signalled thread continues.
    1876 % \item
    1877 % The signalling thread continues and the signalled thread is marked for urgent unblocking at the next scheduling point (exit/wait).
    1878 % \item
    1879 % The signalling thread blocks but is marked for urgent unblocking at the next scheduling point and the signalled thread continues.
    1880 % \end{enumerate}
    1881 % The first approach is too restrictive, as it precludes solving a reasonable class of problems, \eg dating service (see Figure~\ref{f:DatingService}).
    1882 % \CFA supports the next two semantics as both are useful.
    1883 
    18842033\begin{figure}
    18852034\centering
     
    18932042                T elements[10];
    18942043        };
    1895         void ?{}( Buffer(T) & buffer ) with(buffer) {
     2044        void ?{}( Buffer(T) & buf ) with(buf) {
    18962045                front = back = count = 0;
    18972046        }
    1898         void insert( Buffer(T) & mutex buffer, T elem )
    1899                                 with(buffer) {
    1900                 if ( count == 10 ) `wait( empty )`;
    1901                 // insert elem into buffer
     2047
     2048        void insert(Buffer(T) & mutex buf, T elm) with(buf){
     2049                if ( count == 10 ) `wait( empty )`; // full ?
     2050                // insert elm into buf
    19022051                `signal( full )`;
    19032052        }
    1904         T remove( Buffer(T) & mutex buffer ) with(buffer) {
    1905                 if ( count == 0 ) `wait( full )`;
    1906                 // remove elem from buffer
     2053        T remove( Buffer(T) & mutex buf ) with(buf) {
     2054                if ( count == 0 ) `wait( full )`; // empty ?
     2055                // remove elm from buf
    19072056                `signal( empty )`;
    1908                 return elem;
     2057                return elm;
    19092058        }
    19102059}
    19112060\end{cfa}
    19122061\end{lrbox}
    1913 
    1914 % \newbox\myboxB
    1915 % \begin{lrbox}{\myboxB}
    1916 % \begin{cfa}[aboveskip=0pt,belowskip=0pt]
    1917 % forall( otype T ) { // distribute forall
    1918 %       monitor Buffer {
    1919 %
    1920 %               int front, back, count;
    1921 %               T elements[10];
    1922 %       };
    1923 %       void ?{}( Buffer(T) & buffer ) with(buffer) {
    1924 %               [front, back, count] = 0;
    1925 %       }
    1926 %       T remove( Buffer(T) & mutex buffer ); // forward
    1927 %       void insert( Buffer(T) & mutex buffer, T elem )
    1928 %                               with(buffer) {
    1929 %               if ( count == 10 ) `waitfor( remove, buffer )`;
    1930 %               // insert elem into buffer
    1931 %
    1932 %       }
    1933 %       T remove( Buffer(T) & mutex buffer ) with(buffer) {
    1934 %               if ( count == 0 ) `waitfor( insert, buffer )`;
    1935 %               // remove elem from buffer
    1936 %
    1937 %               return elem;
    1938 %       }
    1939 % }
    1940 % \end{cfa}
    1941 % \end{lrbox}
    19422062
    19432063\newbox\myboxB
    19442064\begin{lrbox}{\myboxB}
    19452065\begin{cfa}[aboveskip=0pt,belowskip=0pt]
     2066forall( otype T ) { // distribute forall
     2067        monitor Buffer {
     2068
     2069                int front, back, count;
     2070                T elements[10];
     2071        };
     2072        void ?{}( Buffer(T) & buf ) with(buf) {
     2073                front = back = count = 0;
     2074        }
     2075        T remove( Buffer(T) & mutex buf ); // forward
     2076        void insert(Buffer(T) & mutex buf, T elm) with(buf){
     2077                if ( count == 10 ) `waitfor( remove : buf )`;
     2078                // insert elm into buf
     2079
     2080        }
     2081        T remove( Buffer(T) & mutex buf ) with(buf) {
     2082                if ( count == 0 ) `waitfor( insert : buf )`;
     2083                // remove elm from buf
     2084
     2085                return elm;
     2086        }
     2087}
     2088\end{cfa}
     2089\end{lrbox}
     2090
     2091\subfloat[Internal scheduling]{\label{f:BBInt}\usebox\myboxA}
     2092\hspace{1pt}
     2093\vrule
     2094\hspace{3pt}
     2095\subfloat[External scheduling]{\label{f:BBExt}\usebox\myboxB}
     2096
     2097\caption{Generic bounded buffer}
     2098\label{f:GenericBoundedBuffer}
     2099\end{figure}
     2100
     2101The @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}.
     2102Signal 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.
     2103Using @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.
     2104
     2105For 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++}.
     2106While prior languages use external scheduling solely for thread interaction, \CFA generalizes it to both monitors and threads.
     2107External scheduling allows waiting for events from other threads while restricting unrelated events, that would otherwise have to wait on condition queues in the monitor.
     2108Scheduling 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.
     2109Specifically, 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.
     2110(The linear search through the calling queue to locate a particular call can be reduced to $O(1)$.)
     2111Hence, 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.
     2112Now 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.
     2113For 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.
     2114Hence, this mechanism is done in terms of control flow, next call, versus in terms of data, channels, as in Go and Rust @select@.
     2115While both mechanisms have strengths and weaknesses, \CFA uses the control-flow mechanism to be consistent with other language features.
     2116
     2117Figure~\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.
     2118For 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.
     2119To 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@.
     2120An 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.
     2121For 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@.
     2122The writer does a similar action for each reader or writer using the resource.
     2123Note, no new calls to @StartRead@/@StartWrite@ may occur when waiting for the call to @EndRead@/@EndWrite@.
     2124
     2125\begin{figure}
     2126\centering
     2127\newbox\myboxA
     2128\begin{lrbox}{\myboxA}
     2129\begin{cfa}[aboveskip=0pt,belowskip=0pt]
     2130enum RW { READER, WRITER };
    19462131monitor ReadersWriter {
    1947         int rcnt, wcnt; // readers/writer using resource
     2132        int rcnt, wcnt; // readers/writer using resource
     2133        `condition RWers;`
    19482134};
    19492135void ?{}( ReadersWriter & rw ) with(rw) {
     
    19522138void EndRead( ReadersWriter & mutex rw ) with(rw) {
    19532139        rcnt -= 1;
     2140        if ( rcnt == 0 ) `signal( RWers )`;
    19542141}
    19552142void EndWrite( ReadersWriter & mutex rw ) with(rw) {
    19562143        wcnt = 0;
     2144        `signal( RWers );`
    19572145}
    19582146void StartRead( ReadersWriter & mutex rw ) with(rw) {
    1959         if ( wcnt > 0 ) `waitfor( EndWrite, rw );`
     2147        if ( wcnt !=0 || ! empty( RWers ) )
     2148                `wait( RWers, READER )`;
    19602149        rcnt += 1;
     2150        if ( ! empty(RWers) && `front(RWers) == READER` )
     2151                `signal( RWers )`;  // daisy-chain signaling
    19612152}
    19622153void StartWrite( ReadersWriter & mutex rw ) with(rw) {
    1963         if ( wcnt > 0 ) `waitfor( EndWrite, rw );`
    1964         else while ( rcnt > 0 ) `waitfor( EndRead, rw );`
     2154        if ( wcnt != 0 || rcnt != 0 ) `wait( RWers, WRITER )`;
     2155
    19652156        wcnt = 1;
    19662157}
    1967 
    19682158\end{cfa}
    19692159\end{lrbox}
    19702160
    1971 \subfloat[Generic bounded buffer, internal scheduling]{\label{f:BBInt}\usebox\myboxA}
    1972 \hspace{3pt}
     2161\newbox\myboxB
     2162\begin{lrbox}{\myboxB}
     2163\begin{cfa}[aboveskip=0pt,belowskip=0pt]
     2164
     2165monitor ReadersWriter {
     2166        int rcnt, wcnt; // readers/writer using resource
     2167
     2168};
     2169void ?{}( ReadersWriter & rw ) with(rw) {
     2170        rcnt = wcnt = 0;
     2171}
     2172void EndRead( ReadersWriter & mutex rw ) with(rw) {
     2173        rcnt -= 1;
     2174
     2175}
     2176void EndWrite( ReadersWriter & mutex rw ) with(rw) {
     2177        wcnt = 0;
     2178
     2179}
     2180void StartRead( ReadersWriter & mutex rw ) with(rw) {
     2181        if ( wcnt > 0 ) `waitfor( EndWrite : rw );`
     2182
     2183        rcnt += 1;
     2184
     2185
     2186}
     2187void StartWrite( ReadersWriter & mutex rw ) with(rw) {
     2188        if ( wcnt > 0 ) `waitfor( EndWrite : rw );`
     2189        else while ( rcnt > 0 ) `waitfor( EndRead : rw );`
     2190        wcnt = 1;
     2191}
     2192\end{cfa}
     2193\end{lrbox}
     2194
     2195\subfloat[Internal scheduling]{\label{f:RWInt}\usebox\myboxA}
     2196\hspace{1pt}
    19732197\vrule
    19742198\hspace{3pt}
    1975 \subfloat[Readers / writer lock, external scheduling]{\label{f:RWExt}\usebox\myboxB}
    1976 
    1977 \caption{Internal / external scheduling}
    1978 \label{f:InternalExternalScheduling}
     2199\subfloat[External scheduling]{\label{f:RWExt}\usebox\myboxB}
     2200
     2201\caption{Readers / writer lock}
     2202\label{f:ReadersWriterLock}
    19792203\end{figure}
    19802204
    1981 Figure~\ref{f:BBInt} can be transformed into external scheduling by removing the condition variables and signals/waits, and adding the following lines at the locations of the current @wait@s in @insert@/@remove@, respectively.
    1982 \begin{cfa}[aboveskip=2pt,belowskip=1pt]
    1983 if ( count == 10 ) `waitfor( remove, buffer )`;       |      if ( count == 0 ) `waitfor( insert, buffer )`;
    1984 \end{cfa}
    1985 Here, the producers/consumers detects a full/\-empty buffer and prevents more producers/consumers from entering the monitor until there is a free/empty slot in the buffer.
    1986 External scheduling is controlled by the @waitfor@ statement, which atomically blocks the calling thread, releases the monitor lock, and restricts the function calls that can next acquire mutual exclusion.
    1987 If the buffer is full, only calls to @remove@ can acquire the buffer, and if the buffer is empty, only calls to @insert@ can acquire the buffer.
    1988 Threads calling excluded functions block outside of (external to) the monitor on the calling queue, versus blocking on condition queues inside of (internal to) the monitor.
    1989 Figure~\ref{f:RWExt} shows a readers/writer lock written using external scheduling, where a waiting reader detects a writer using the resource and restricts further calls until the writer exits by calling @EndWrite@.
    1990 The writer does a similar action for each reader or writer using the resource.
    1991 Note, no new calls to @StarRead@/@StartWrite@ may occur when waiting for the call to @EndRead@/@EndWrite@.
    1992 External scheduling allows waiting for events from other threads while restricting unrelated events, that would otherwise have to wait on conditions in the monitor.
    1993 The mechnaism can be done in terms of control flow, \eg Ada @accept@ or \uC @_Accept@, or in terms of data, \eg Go @select@ on channels.
    1994 While both mechanisms have strengths and weaknesses, this project uses the control-flow mechanism to be consistent with other language features.
    1995 % Two challenges specific to \CFA for external scheduling are loose object-definitions (see Section~\ref{s:LooseObjectDefinitions}) and multiple-monitor functions (see Section~\ref{s:Multi-MonitorScheduling}).
    1996 
    1997 Figure~\ref{f:DatingService} shows a dating service demonstrating non-blocking and blocking signalling.
    1998 The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers.
    1999 A thread blocks until an appropriate partner arrives.
    2000 The complexity is exchanging phone numbers in the monitor because of the mutual-exclusion property.
    2001 For 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.
    2002 For signal-block scheduling, the implicit urgent-queue replaces the explict @exchange@-condition and @signal_block@ puts the finding thread on the urgent condition and unblocks the matcher.
    2003 The dating service is an example of a monitor that cannot be written using external scheduling because it requires knowledge of calling parameters to make scheduling decisions, and parameters of waiting threads are unavailable;
    2004 as well, an arriving thread may not find a partner and must wait, which requires a condition variable, and condition variables imply internal scheduling.
    2005 Furthermore, 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.
    2006 Putting loops around the @wait@s does not correct the problem;
    2007 the simple solution must be restructured to account for barging.
     2205Finally, external scheduling requires urgent to be a stack, because the signaller expects to execute immediately after the specified monitor call has exited or waited.
     2206Internal scheduling performing multiple signaling results in unblocking from urgent in the reverse order from signaling.
     2207It is rare for the unblocking order to be important as an unblocked thread can be time-sliced immediately after leaving the monitor.
     2208If the unblocking order is important, multiple signaling can be restructured into daisy-chain signaling, where each thread signals the next thread.
     2209Hence, \CFA uses a single urgent stack to correctly handle @waitfor@ and adequately support both forms of signaling.
     2210(Advanced @waitfor@ features are discussed in Section~\ref{s:ExtendedWaitfor}.)
    20082211
    20092212\begin{figure}
     
    20192222};
    20202223int girl( DS & mutex ds, int phNo, int ccode ) {
    2021         if ( is_empty( Boys[ccode] ) ) {
     2224        if ( empty( Boys[ccode] ) ) {
    20222225                wait( Girls[ccode] );
    20232226                GirlPhNo = phNo;
     
    20462249};
    20472250int girl( DS & mutex ds, int phNo, int ccode ) {
    2048         if ( is_empty( Boys[ccode] ) ) { // no compatible
     2251        if ( empty( Boys[ccode] ) ) { // no compatible
    20492252                wait( Girls[ccode] ); // wait for boy
    20502253                GirlPhNo = phNo; // make phone number available
     
    20662269\qquad
    20672270\subfloat[\lstinline@signal_block@]{\label{f:DatingSignalBlock}\usebox\myboxB}
    2068 \caption{Dating service}
    2069 \label{f:DatingService}
     2271\caption{Dating service Monitor}
     2272\label{f:DatingServiceMonitor}
    20702273\end{figure}
    20712274
    2072 In summation, for internal scheduling, non-blocking signalling (as in the producer/consumer example) is used when the signaller is providing the cooperation for a waiting thread;
    2073 the signaller enters the monitor and changes state, detects a waiting threads that can use the state, performs a non-blocking signal on the condition queue for the waiting thread, and exits the monitor to run concurrently.
    2074 The waiter unblocks next from the urgent queue, uses/takes the state, and exits the monitor.
    2075 Blocking signal is the reverse, where the waiter is providing the cooperation for the signalling thread;
    2076 the signaller enters the monitor, detects a waiting thread providing the necessary state, performs a blocking signal to place it on the urgent queue and unblock the waiter.
    2077 The waiter changes state and exits the monitor, and the signaller unblocks next from the urgent queue to use/take the state.
    2078 
    2079 Both internal and external scheduling extend to multiple monitors in a natural way.
     2275Figure~\ref{f:DatingServiceMonitor} shows a dating service demonstrating nonblocking and blocking signaling.
     2276The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers.
     2277A thread blocks until an appropriate partner arrives.
     2278The complexity is exchanging phone numbers in the monitor because of the mutual-exclusion property.
     2279For 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.
     2280For 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.
     2281Note, 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.
     2282This situation shows rechecking the waiting condition and waiting again (signals-as-hints) fails, requiring significant restructured to account for barging.
     2283
     2284Given external and internal scheduling, what guidelines can a programmer use to select between them?
     2285In 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.
     2286Therefore, there are no condition variables, and hence, no wait and signal, which reduces coding complexity and synchronization errors.
     2287If external scheduling is simpler than internal, why not use it all the time?
     2288Unfortunately, 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.
     2289For example, the dating service cannot be written using external scheduling.
     2290First, scheduling requires knowledge of calling parameters to make matching decisions and parameters of calling threads are unavailable within the monitor.
     2291Specifically, a thread within the monitor cannot examine the @ccode@ of threads waiting on the calling queue to determine if there is a matching partner.
     2292(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.)
     2293Second, 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.
     2294Specifically, 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.
     2295For complex synchronization, both external and internal scheduling can be used to take advantage of best of properties of each.
     2296
     2297Finally, both internal and external scheduling extend to multiple monitors in a natural way.
    20802298\begin{cquote}
    2081 \begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
     2299\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
    20822300\begin{cfa}
    20832301monitor M { `condition e`; ... };
     
    20902308&
    20912309\begin{cfa}
    2092 void rtn$\(_1\)$( M & mutex m1, M & mutex m2 );
     2310void rtn$\(_1\)$( M & mutex m1, M & mutex m2 ); // overload rtn
    20932311void rtn$\(_2\)$( M & mutex m1 );
    20942312void bar( M & mutex m1, M & mutex m2 ) {
    2095         ... waitfor( `rtn` ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\), m1, m2 )}$
    2096         ... waitfor( `rtn, m1` ); ... // $\LstCommentStyle{waitfor( rtn\(_2\), m1 )}$
     2313        ... waitfor( `rtn`${\color{red}\(_1\)}$ ); ...       // $\LstCommentStyle{waitfor( rtn\(_1\) : m1, m2 )}$
     2314        ... waitfor( `rtn${\color{red}\(_2\)}$ : m1` ); ...
    20972315}
    20982316\end{cfa}
     
    21002318\end{cquote}
    21012319For @wait( e )@, the default semantics is to atomically block the signaller and release all acquired mutex parameters, \ie @wait( e, m1, m2 )@.
    2102 To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
    2103 Wait cannot statically verifies the released monitors are the acquired mutex-parameters without disallowing separately compiled helper functions calling @wait@.
    2104 While \CC supports bulk locking, @wait@ only accepts a single lock for a condition variable, so bulk locking with condition variables is asymmetric.
     2320To override the implicit multimonitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@.
     2321Wait cannot statically verify the released monitors are the acquired mutex-parameters without disallowing separately compiled helper functions calling @wait@.
     2322While \CC supports bulk locking, @wait@ only accepts a single lock for a condition queue, so bulk locking with condition queues is asymmetric.
    21052323Finally, a signaller,
    21062324\begin{cfa}
     
    21092327}
    21102328\end{cfa}
    2111 must have acquired at least the same locks as the waiting thread signalled from a condition queue to allow the locks to be passed, and hence, prevent barging.
    2112 
    2113 Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex parameters, \ie @waitfor( rtn, m1, m2 )@.
    2114 To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn, m1 )@.
    2115 @waitfor@ does statically verify the monitor types passed are the same as the acquired mutex-parameters of the given function or function pointer, hence the function (pointer) prototype must be accessible.
     2329must have acquired at least the same locks as the waiting thread signaled from a condition queue to allow the locks to be passed, and hence, prevent barging.
     2330
     2331Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex parameters, \ie @waitfor( rtn : m1, m2 )@.
     2332To override the implicit multimonitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn : m1 )@.
     2333@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.
    21162334% When an overloaded function appears in an @waitfor@ statement, calls to any function with that name are accepted.
    2117 % The rationale is that members with the same name should perform a similar function, and therefore, all should be eligible to accept a call.
     2335% The rationale is that functions with the same name should perform a similar actions, and therefore, all should be eligible to accept a call.
    21182336Overloaded functions can be disambiguated using a cast
    21192337\begin{cfa}
    21202338void rtn( M & mutex m );
    21212339`int` rtn( M & mutex m );
    2122 waitfor( (`int` (*)( M & mutex ))rtn, m );
    2123 \end{cfa}
    2124 
    2125 The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock.
     2340waitfor( (`int` (*)( M & mutex ))rtn : m );
     2341\end{cfa}
     2342
     2343The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock (see Section~\ref{s:MutexAcquisition}).
    21262344\begin{cfa}
    21272345void foo( M & mutex m1, M & mutex m2 ) {
    2128         ... wait( `e, m1` ); ...                                $\C{// release m1, keeping m2 acquired )}$
    2129 void bar( M & mutex m1, M & mutex m2 ) {        $\C{// must acquire m1 and m2 )}$
     2346        ... wait( `e, m1` ); ...                                $\C{// release m1, keeping m2 acquired}$
     2347void bar( M & mutex m1, M & mutex m2 ) {        $\C{// must acquire m1 and m2}$
    21302348        ... signal( `e` ); ...
    21312349\end{cfa}
    2132 The @wait@ only releases @m1@ so the signalling thread cannot acquire @m1@ and @m2@ to enter @bar@ and @signal@ the condition.
    2133 While deadlock can occur with multiple/nesting acquisition, this is a consequence of locks, and by extension monitors, not being perfectly composable.
    2134 
     2350The @wait@ only releases @m1@ so the signaling thread cannot acquire @m1@ and @m2@ to enter @bar@ and @signal@ the condition.
     2351While deadlock can occur with multiple/nesting acquisition, this is a consequence of locks, and by extension monitor locking is not perfectly composable.
    21352352
    21362353
    21372354\subsection{\texorpdfstring{Extended \protect\lstinline@waitfor@}{Extended waitfor}}
     2355\label{s:ExtendedWaitfor}
    21382356
    21392357Figure~\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.
    2140 For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding member(s) must exist.
     2358For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding function(s) must exist.
    21412359The \emph{conditional-expression} of a @when@ may call a function, but the function must not block or context switch.
    2142 If there are multiple acceptable mutex calls, selection occurs top-to-bottom (prioritized) among the @waitfor@ clauses, whereas some programming languages with similar mechanisms accept nondeterministically for this case, \eg Go \lstinline[morekeywords=select]@select@.
    2143 If some accept guards are true and there are no outstanding calls to these members, the acceptor is blocked until a call to one of these members is made.
     2360If 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@.
     2361If 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.
    21442362If there is a @timeout@ clause, it provides an upper bound on waiting.
    21452363If 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.
    21462364Hence, the terminating @else@ clause allows a conditional attempt to accept a call without blocking.
    21472365If both @timeout@ and @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered.
    2148 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.
     2366% 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.
     2367Finally, there is a shorthand for specifying multiple functions using the same set of monitors: @waitfor( f, g, h : m1, m2, m3 )@.
    21492368
    21502369\begin{figure}
     
    21522371\begin{cfa}
    21532372`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
    2154         waitfor( $\emph{mutex-member-name}$ ) $\emph{statement}$ $\C{// action after call}$
     2373        waitfor( $\emph{mutex-function-name}$ ) $\emph{statement}$ $\C{// action after call}$
    21552374`or` `when` ( $\emph{conditional-expression}$ ) $\C{// any number of functions}$
    2156         waitfor( $\emph{mutex-member-name}$ ) $\emph{statement}$
     2375        waitfor( $\emph{mutex-function-name}$ ) $\emph{statement}$
    21572376`or`    ...
    21582377`when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
     
    21722391The left example only accepts @mem1@ if @C1@ is true or only @mem2@ if @C2@ is true.
    21732392The right example accepts either @mem1@ or @mem2@ if @C1@ and @C2@ are true.
    2174 
    2175 An interesting use of @waitfor@ is accepting the @mutex@ destructor to know when an object is deallocated, \eg assume the bounded buffer is restructred from a monitor to a thread with the following @main@.
     2393Hence, the @waitfor@ has parallel semantics, accepting any true @when@ clause.
     2394
     2395An 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@.
    21762396\begin{cfa}
    21772397void main( Buffer(T) & buffer ) with(buffer) {
    21782398        for () {
    2179                 `waitfor( ^?{}, buffer )` break;
    2180                 or when ( count != 20 ) waitfor( insert, buffer ) { ... }
    2181                 or when ( count != 0 ) waitfor( remove, buffer ) { ... }
     2399                `waitfor( ^?{} : buffer )` break;
     2400                or when ( count != 20 ) waitfor( insert : buffer ) { ... }
     2401                or when ( count != 0 ) waitfor( remove : buffer ) { ... }
    21822402        }
    21832403        // clean up
     
    21922412
    21932413
    2194 \subsection{Bulk Barging Prevention}
    2195 
    2196 Figure~\ref{f:BulkBargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signalling semantics.
     2414\subsection{Bulk barging prevention}
     2415
     2416Figure~\ref{f:BulkBargingPrevention} shows \CFA code where bulk acquire adds complexity to the internal-signaling semantics.
    21972417The complexity begins at the end of the inner @mutex@ statement, where the semantics of internal scheduling need to be extended for multiple monitors.
    21982418The problem is that bulk acquire is used in the inner @mutex@ statement where one of the monitors is already acquired.
    2199 When 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.
    2200 However, both the signalling and waiting threads W1 and W2 need some subset of monitors @m1@ and @m2@.
     2419When the signaling 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.
     2420However, both the signaling and waiting threads W1 and W2 need some subset of monitors @m1@ and @m2@.
    22012421\begin{cquote}
    22022422condition c: (order 1) W2(@m2@), W1(@m1@,@m2@)\ \ \ or\ \ \ (order 2) W1(@m1@,@m2@), W2(@m2@) \\
     
    22652485\end{figure}
    22662486
    2267 One 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.
    2268 However, 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.
     2487One 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 behavior of single-monitor scheduling.
     2488However, this solution is inefficient if W2 waited first and immediate passed @m2@ when released, while S retains @m1@ until completion of the outer mutex statement.
    22692489If W1 waited first, the signaller must retain @m1@ amd @m2@ until completion of the outer mutex statement and then pass both to W1.
    22702490% Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
    2271 To support this efficient semantics (and prevent barging), the implementation maintains a list of monitors acquired for each blocked thread.
    2272 When a signaller exits or waits in a monitor function/statement, the front waiter on urgent is unblocked if all its monitors are released.
    2273 Implementing a fast subset check for the necessary released monitors is important.
     2491To support these efficient semantics and prevent barging, the implementation maintains a list of monitors acquired for each blocked thread.
     2492When a signaller exits or waits in a mutex function or statement, the front waiter on urgent is unblocked if all its monitors are released.
     2493Implementing a fast subset check for the necessarily released monitors is important and discussed in the following sections.
    22742494% 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.
    22752495
    22762496
    2277 \subsection{Loose Object Definitions}
    2278 \label{s:LooseObjectDefinitions}
    2279 
    2280 In an object-oriented programming language, a class includes an exhaustive list of operations.
    2281 A new class can add members via static inheritance but the subclass still has an exhaustive list of operations.
    2282 (Dynamic member adding, \eg JavaScript~\cite{JavaScript}, is not considered.)
    2283 In the object-oriented scenario, the type and all its operators are always present at compilation (even separate compilation), so it is possible to number the operations in a bit mask and use an $O(1)$ compare with a similar bit mask created for the operations specified in a @waitfor@.
    2284 
    2285 However, in \CFA, monitor functions can be statically added/removed in translation units, making a fast subset check difficult.
    2286 \begin{cfa}
    2287         monitor M { ... }; // common type, included in .h file
    2288 translation unit 1
    2289         void `f`( M & mutex m );
    2290         void g( M & mutex m ) { waitfor( `f`, m ); }
    2291 translation unit 2
    2292         void `f`( M & mutex m ); $\C{// replacing f and g for type M in this translation unit}$
    2293         void `g`( M & mutex m );
    2294         void h( M & mutex m ) { waitfor( `f`, m ) or waitfor( `g`, m ); } $\C{// extending type M in this translation unit}$
    2295 \end{cfa}
    2296 The @waitfor@ statements in each translation unit cannot form a unique bit-mask because the monitor type does not carry that information.
     2497\subsection{\texorpdfstring{\protect\lstinline@waitfor@ Implementation}{waitfor Implementation}}
     2498\label{s:waitforImplementation}
     2499
     2500In 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}).
     2501Knowing 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.
     2502
     2503\begin{figure}
     2504\centering
     2505\begin{lrbox}{\myboxA}
     2506\begin{uC++}[aboveskip=0pt,belowskip=0pt]
     2507$\emph{translation unit 1}$
     2508_Monitor B { // common type in .h file
     2509        _Mutex virtual void `f`( ... );
     2510        _Mutex virtual void `g`( ... );
     2511        _Mutex virtual void w1( ... ) { ... _Accept(`f`, `g`); ... }
     2512};
     2513$\emph{translation unit 2}$
     2514// include B
     2515_Monitor D : public B { // inherit
     2516        _Mutex void `h`( ... ); // add
     2517        _Mutex void w2( ... ) { ... _Accept(`f`, `h`); ... }
     2518};
     2519\end{uC++}
     2520\end{lrbox}
     2521
     2522\begin{lrbox}{\myboxB}
     2523\begin{cfa}[aboveskip=0pt,belowskip=0pt]
     2524$\emph{translation unit 1}$
     2525monitor M { ... }; // common type in .h file
     2526void `f`( M & mutex m, ... );
     2527void `g`( M & mutex m, ... );
     2528void w1( M & mutex m, ... ) { ... waitfor(`f`, `g` : m); ... }
     2529
     2530$\emph{translation unit 2}$
     2531// include M
     2532extern void `f`( M & mutex m, ... ); // import f but not g
     2533void `h`( M & mutex m ); // add
     2534void w2( M & mutex m, ... ) { ... waitfor(`f`, `h` : m); ... }
     2535
     2536\end{cfa}
     2537\end{lrbox}
     2538
     2539\subfloat[\uC]{\label{f:uCinheritance}\usebox\myboxA}
     2540\hspace{3pt}
     2541\vrule
     2542\hspace{3pt}
     2543\subfloat[\CFA]{\label{f:CFinheritance}\usebox\myboxB}
     2544\caption{Member / function visibility}
     2545\label{f:MemberFunctionVisibility}
     2546\end{figure}
     2547
     2548However, 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.
     2549(A possible way to construct a dense mapping is at link or load-time.)
    22972550Hence, function pointers are used to identify the functions listed in the @waitfor@ statement, stored in a variable-sized array.
    2298 Then, the same implementation approach used for the urgent stack is used for the calling queue.
    2299 Each caller has a list of monitors acquired, and the @waitfor@ statement performs a (usually short) linear search matching functions in the @waitfor@ list with called functions, and then verifying the associated mutex locks can be transfers.
    2300 (A possible way to construct a dense mapping is at link or load-time.)
    2301 
    2302 
    2303 \subsection{Multi-Monitor Scheduling}
     2551Then, the same implementation approach used for the urgent stack (see Section~\ref{s:Scheduling}) is used for the calling queue.
     2552Each 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 transferred.
     2553
     2554
     2555\subsection{Multimonitor scheduling}
    23042556\label{s:Multi-MonitorScheduling}
    23052557
    2306 External scheduling, like internal scheduling, becomes significantly more complex for multi-monitor semantics.
     2558External scheduling, like internal scheduling, becomes significantly more complex for multimonitor semantics.
    23072559Even in the simplest case, new semantics need to be established.
    23082560\begin{cfa}
     
    23132565The solution is for the programmer to disambiguate:
    23142566\begin{cfa}
    2315 waitfor( f, `m2` ); $\C{// wait for call to f with argument m2}$
     2567waitfor( f : `m2` ); $\C{// wait for call to f with argument m2}$
    23162568\end{cfa}
    23172569Both 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@.
    2318 This behaviour can be extended to the multi-monitor @waitfor@ statement.
     2570This behavior can be extended to the multimonitor @waitfor@ statement.
    23192571\begin{cfa}
    23202572monitor M { ... };
    23212573void f( M & mutex m1, M & mutex m2 );
    2322 void g( M & mutex m1, M & mutex m2 ) { waitfor( f, `m1, m2` ); $\C{// wait for call to f with arguments m1 and m2}$
     2574void g( M & mutex m1, M & mutex m2 ) { waitfor( f : `m1, m2` ); $\C{// wait for call to f with arguments m1 and m2}$
    23232575\end{cfa}
    23242576Again, the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired by the accepting function.
    2325 Also, the order of the monitors in a @waitfor@ statement is unimportant.
    2326 
    2327 Figure~\ref{f:UnmatchedMutexSets} shows an example where, for internal and external scheduling with multiple monitors, a signalling or accepting thread must match exactly, \ie partial matching results in waiting.
    2328 For both examples, the set of monitors is disjoint so unblocking is impossible.
     2577% Also, the order of the monitors in a @waitfor@ statement must match the order of the mutex parameters.
     2578
     2579Figure~\ref{f:UnmatchedMutexSets} shows internal and external scheduling with multiple monitors that must match exactly with a signaling or accepting thread, \ie partial matching results in waiting.
     2580In both cases, the set of monitors is disjoint so unblocking is impossible.
    23292581
    23302582\begin{figure}
     
    23552607}
    23562608void g( M1 & mutex m1, M2 & mutex m2 ) {
    2357         waitfor( f, m1, m2 );
     2609        waitfor( f : m1, m2 );
    23582610}
    23592611g( `m11`, m2 ); // block on accept
     
    23702622\end{figure}
    23712623
    2372 
    2373 \subsection{\texorpdfstring{\protect\lstinline@mutex@ Threads}{mutex Threads}}
    2374 
    2375 Threads in \CFA can also be monitors to allow \emph{direct communication} among threads, \ie threads can have mutex functions that are called by other threads.
    2376 Hence, all monitor features are available when using threads.
    2377 Figure~\ref{f:DirectCommunication} shows a comparison of direct call communication in \CFA with direct channel communication in Go.
    2378 (Ada provides a similar mechanism to the \CFA direct communication.)
    2379 The program main in both programs communicates directly with the other thread versus indirect communication where two threads interact through a passive monitor.
    2380 Both direct and indirection thread communication are valuable tools in structuring concurrent programs.
    2381 
    23822624\begin{figure}
    23832625\centering
     
    23862628
    23872629struct Msg { int i, j; };
    2388 thread GoRtn { int i;  float f;  Msg m; };
     2630mutex thread GoRtn { int i;  float f;  Msg m; };
    23892631void mem1( GoRtn & mutex gortn, int i ) { gortn.i = i; }
    23902632void mem2( GoRtn & mutex gortn, float f ) { gortn.f = f; }
     
    23922634void ^?{}( GoRtn & mutex ) {}
    23932635
    2394 void main( GoRtn & gortn ) with( gortn ) { // thread starts
     2636void main( GoRtn & mutex gortn ) with(gortn) { // thread starts
    23952637
    23962638        for () {
    23972639
    2398                 `waitfor( mem1, gortn )` sout | i;  // wait for calls
    2399                 or `waitfor( mem2, gortn )` sout | f;
    2400                 or `waitfor( mem3, gortn )` sout | m.i | m.j;
    2401                 or `waitfor( ^?{}, gortn )` break;
     2640                `waitfor( mem1 : gortn )` sout | i;  // wait for calls
     2641                or `waitfor( mem2 : gortn )` sout | f;
     2642                or `waitfor( mem3 : gortn )` sout | m.i | m.j;
     2643                or `waitfor( ^?{} : gortn )` break; // low priority
    24022644
    24032645        }
     
    24532695\hspace{3pt}
    24542696\subfloat[Go]{\label{f:Gochannel}\usebox\myboxB}
    2455 \caption{Direct communication}
    2456 \label{f:DirectCommunication}
     2697\caption{Direct versus indirect communication}
     2698\label{f:DirectCommunicationComparison}
     2699
     2700\medskip
     2701
     2702\begin{cfa}
     2703mutex thread DatingService {
     2704        condition Girls[CompCodes], Boys[CompCodes];
     2705        int girlPhoneNo, boyPhoneNo, ccode;
     2706};
     2707int girl( DatingService & mutex ds, int phoneno, int code ) with( ds ) {
     2708        girlPhoneNo = phoneno;  ccode = code;
     2709        `wait( Girls[ccode] );`                                                         $\C{// wait for boy}$
     2710        girlPhoneNo = phoneno;  return boyPhoneNo;
     2711}
     2712int boy( DatingService & mutex ds, int phoneno, int code ) with( ds ) {
     2713        boyPhoneNo = phoneno;  ccode = code;
     2714        `wait( Boys[ccode] );`                                                          $\C{// wait for girl}$
     2715        boyPhoneNo = phoneno;  return girlPhoneNo;
     2716}
     2717void main( DatingService & ds ) with( ds ) {                    $\C{// thread starts, ds defaults to mutex}$
     2718        for () {
     2719                waitfor( ^?{} ) break;                                                  $\C{// high priority}$
     2720                or waitfor( girl )                                                              $\C{// girl called, compatible boy ? restart boy then girl}$
     2721                        if ( ! is_empty( Boys[ccode] ) ) { `signal_block( Boys[ccode] );  signal_block( Girls[ccode] );` }
     2722                or waitfor( boy ) {                                                             $\C{// boy called, compatible girl ? restart girl then boy}$
     2723                        if ( ! is_empty( Girls[ccode] ) ) { `signal_block( Girls[ccode] );  signal_block( Boys[ccode] );` }
     2724        }
     2725}
     2726\end{cfa}
     2727\caption{Direct communication dating service}
     2728\label{f:DirectCommunicationDatingService}
    24572729\end{figure}
    24582730
     
    24692741void main( Ping & pi ) {
    24702742        for ( 10 ) {
    2471                 `waitfor( ping, pi );`
     2743                `waitfor( ping : pi );`
    24722744                `pong( po );`
    24732745        }
     
    24822754        for ( 10 ) {
    24832755                `ping( pi );`
    2484                 `waitfor( pong, po );`
     2756                `waitfor( pong : po );`
    24852757        }
    24862758}
     
    24932765% \label{f:pingpong}
    24942766% \end{figure}
    2495 Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start (and possibly complete) before the program main starts.
     2767Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start and possibly complete before the program main starts.
    24962768\end{comment}
    24972769
    24982770
    2499 \subsection{Execution Properties}
    2500 
    2501 Table~\ref{t:ObjectPropertyComposition} shows how the \CFA high-level constructs cover 3 fundamental execution properties: thread, stateful function, and mutual exclusion.
    2502 Case 1 is a basic object, with none of the new execution properties.
    2503 Case 2 allows @mutex@ calls to Case 1 to protect shared data.
    2504 Case 3 allows stateful functions to suspend/resume but restricts operations because the state is stackless.
    2505 Case 4 allows @mutex@ calls to Case 3 to protect shared data.
    2506 Cases 5 and 6 are the same as 3 and 4 without restriction because the state is stackful.
    2507 Cases 7 and 8 are rejected because a thread cannot execute without a stackful state in a preemptive environment when context switching from the signal handler.
    2508 Cases 9 and 10 have a stackful thread without and with @mutex@ calls.
    2509 For situations where threads do not require direct communication, case 9 provides faster creation/destruction by eliminating @mutex@ setup.
    2510 
    2511 \begin{table}
    2512 \caption{Object property composition}
    2513 \centering
    2514 \label{t:ObjectPropertyComposition}
    2515 \renewcommand{\arraystretch}{1.25}
    2516 %\setlength{\tabcolsep}{5pt}
    2517 \begin{tabular}{c|c||l|l}
    2518 \multicolumn{2}{c||}{object properties} & \multicolumn{2}{c}{mutual exclusion} \\
    2519 \hline
    2520 thread  & stateful                              & \multicolumn{1}{c|}{No} & \multicolumn{1}{c}{Yes} \\
    2521 \hline
    2522 \hline
    2523 No              & No                                    & \textbf{1}\ \ \ aggregate type                & \textbf{2}\ \ \ @monitor@ aggregate type \\
    2524 \hline
    2525 No              & Yes (stackless)               & \textbf{3}\ \ \ @generator@                   & \textbf{4}\ \ \ @monitor@ @generator@ \\
    2526 \hline
    2527 No              & Yes (stackful)                & \textbf{5}\ \ \ @coroutine@                   & \textbf{6}\ \ \ @monitor@ @coroutine@ \\
    2528 \hline
    2529 Yes             & No / Yes (stackless)  & \textbf{7}\ \ \ {\color{red}rejected} & \textbf{8}\ \ \ {\color{red}rejected} \\
    2530 \hline
    2531 Yes             & Yes (stackful)                & \textbf{9}\ \ \ @thread@                              & \textbf{10}\ \ @monitor@ @thread@ \\
    2532 \end{tabular}
    2533 \end{table}
     2771\subsection{\texorpdfstring{\protect\lstinline@mutex@ Generators / coroutines / threads}{monitor Generators / coroutines / threads}}
     2772
     2773\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.
     2774All monitor features are available within these mutex functions.
     2775For 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:
     2776\begin{cfa}
     2777void fmt( Fmt & mutex fmt, char ch ) { fmt.ch = ch; resume( fmt ) }
     2778\end{cfa}
     2779multiple threads can safely pass characters for formatting.
     2780
     2781Figure~\ref{f:DirectCommunicationComparison} shows a comparison of direct call-communication in \CFA versus indirect channel-communication in Go.
     2782(Ada has a similar mechanism to \CFA direct communication.)
     2783% The thread main function is by default @mutex@, so the @mutex@ qualifier for the thread parameter is optional.
     2784% 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.
     2785The \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.
     2786Communication by multiple threads is safe for the @gortn@ thread via mutex calls in \CFA or channel assignment in Go.
     2787The difference between call and channel send occurs for buffered channels making the send asynchronous.
     2788In \CFA, asynchronous call and multiple buffers are provided using an administrator and worker threads~\cite{Gentleman81} and/or futures (not discussed).
     2789
     2790Figure~\ref{f:DirectCommunicationDatingService} shows the dating-service problem in Figure~\ref{f:DatingServiceMonitor} extended from indirect monitor communication to direct thread communication.
     2791When 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 as much work as possible.
     2792Notice, the dating server is postponing requests for an unspecified time while continuing to accept new requests.
     2793For 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.
    25342794
    25352795
     
    25372797
    25382798For 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.
    2539 Some of these low-level mechanism are used in the \CFA runtime, but we strongly advocate using high-level mechanisms whenever possible.
     2799Some of these low-level mechanisms are used to build the \CFA runtime, but we always advocate using high-level mechanisms whenever possible.
    25402800
    25412801
     
    25512811%
    25522812%
    2553 % \subsection{User Threads}
     2813% \subsection{User threads}
    25542814%
    25552815% A direct improvement on kernel threads is user threads, \eg Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
     
    25662826
    25672827\begin{comment}
    2568 \subsection{Thread Pools}
     2828\subsection{Thread pools}
    25692829
    25702830In 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.
    2571 If the jobs are dependent, \ie interact, there is an implicit/explicit dependency graph that ties them together.
     2831If the jobs are dependent, \ie interact, there is an implicit dependency graph that ties them together.
    25722832While removing direct concurrency, and hence the amount of context switching, thread pools significantly limit the interaction that can occur among jobs.
    25732833Indeed, jobs should not block because that also blocks the underlying thread, which effectively means the CPU utilization, and therefore throughput, suffers.
     
    25802840\begin{cfa}
    25812841struct Adder {
    2582     int * row, cols;
     2842        int * row, cols;
    25832843};
    25842844int operator()() {
     
    26392899\label{s:RuntimeStructureCluster}
    26402900
    2641 A \newterm{cluster} is a collection of threads and virtual processors (abstract kernel-thread) that execute the (user) threads from its own ready queue (like an OS executing kernel threads).
     2901A \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~\cite{Buhr90a}.
     2902The term \newterm{virtual processor} is introduced as a synonym for kernel thread to disambiguate between user and kernel thread.
     2903From the language perspective, a virtual processor is an actual processor (core).
     2904
    26422905The purpose of a cluster is to control the amount of parallelism that is possible among threads, plus scheduling and other execution defaults.
    26432906The default cluster-scheduler is single-queue multi-server, which provides automatic load-balancing of threads on processors.
    2644 However, the design allows changing the scheduler, \eg multi-queue multi-server with work-stealing/sharing across the virtual processors.
     2907However, the design allows changing the scheduler, \eg multi-queue multiserver with work-stealing/sharing across the virtual processors.
    26452908If several clusters exist, both threads and virtual processors, can be explicitly migrated from one cluster to another.
    26462909No automatic load balancing among clusters is performed by \CFA.
     
    26522915
    26532916
    2654 \subsection{Virtual Processor}
     2917\subsection{Virtual processor}
    26552918\label{s:RuntimeStructureProcessor}
    26562919
    2657 A 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.
     2920A 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.
    26582921Programs may use more virtual processors than hardware processors.
    26592922On a multiprocessor, kernel threads are distributed across the hardware processors resulting in virtual processors executing in parallel.
    2660 (It is possible to use affinity to lock a virtual processor onto a particular hardware processor~\cite{affinityLinux, affinityWindows, affinityFreebsd, affinityNetbsd, affinityMacosx}, which is used when caching issues occur or for heterogeneous hardware processors.)
     2923(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
    26612924The \CFA runtime attempts to block unused processors and unblock processors as the system load increases;
    2662 balancing the workload with processors is difficult because it requires future knowledge, \ie what will the applicaton workload do next.
     2925balancing the workload with processors is difficult because it requires future knowledge, \ie what will the application workload do next.
    26632926Preemption occurs on virtual processors rather than user threads, via operating-system interrupts.
    26642927Thus virtual processors execute user threads, where preemption frequency applies to a virtual processor, so preemption occurs randomly across the executed user threads.
     
    26702933\label{s:Implementation}
    26712934
    2672 A primary implementation challenge is avoiding contention from dynamically allocating memory because of bulk acquire, \eg the internal-scheduling design is (almost) free of allocations.
     2935A primary implementation challenge is avoiding contention from dynamically allocating memory because of bulk acquire, \eg the internal-scheduling design is almost free of allocations.
    26732936All 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.
    26742937Furthermore, several bulk-acquire operations need a variable amount of memory.
    26752938This 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.
    26762939
    2677 In \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.
     2940In \CFA, ordering of monitor acquisition relies on memory ordering to prevent deadlock~\cite{Havender68}, because all objects have distinct nonoverlapping memory layouts, and mutual-exclusion for a monitor is only defined for its lifetime.
    26782941When a mutex call is made, pointers to the concerned monitors are aggregated into a variable-length array and sorted.
    26792942This array persists for the entire duration of the mutual exclusion and is used extensively for synchronization operations.
     
    26942957
    26952958Nondeterministic 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.
    2696 This atomic reliance can fail on multi-core machines, because execution across cores is nondeterministic.
    2697 A different reason for not supporting preemption is that it significantly complicates the runtime system, \eg Microsoft runtime does not support interrupts and on Linux systems, interrupts are complex (see below).
     2959This atomic reliance can fail on multicore machines, because execution across cores is nondeterministic.
     2960A 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).
    26982961Preemption is normally handled by setting a countdown timer on each virtual processor.
    2699 When the timer expires, an interrupt is delivered, and the interrupt handler resets the countdown timer, and if the virtual processor is executing in user code, the signal handler performs a user-level context-switch, or if executing in the language runtime kernel, the preemption is ignored or rolled forward to the point where the runtime kernel context switches back to user code.
     2962When 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.
    27002963Multiple signal handlers may be pending.
    27012964When 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.
    27022965The 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;
    27032966therefore, the same signal mask is required for all virtual processors in a cluster.
    2704 Because preemption frequency is usually long (1 millisecond) performance cost is negligible.
    2705 
    2706 Linux switched a decade ago from specific to arbitrary process signal-delivery for applications with multiple kernel threads.
    2707 \begin{cquote}
    2708 A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked.
    2709 If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which it will deliver the signal.
    2710 SIGNAL(7) - Linux Programmer's Manual
    2711 \end{cquote}
     2967Because preemption interval is usually long (1 ms) performance cost is negligible.
     2968
     2969Linux switched a decade ago from specific to arbitrary virtual-processor signal-delivery for applications with multiple kernel threads.
     2970In 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.
    27122971Hence, 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).
    27132972To 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.
     
    27172976
    27182977
    2719 \subsection{Debug Kernel}
    2720 
    2721 There are two versions of the \CFA runtime kernel: debug and non-debug.
    2722 The 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.
    2723 After a program is debugged, the non-debugging version can be used to significantly decrease space and increase performance.
     2978\subsection{Debug kernel}
     2979
     2980There are two versions of the \CFA runtime kernel: debug and nondebug.
     2981The debugging version has many runtime checks and internal assertions, \eg stack nonwritable guard page, and checks for stack overflow whenever context switches occur among coroutines and threads, which catches most stack overflows.
     2982After a program is debugged, the nondebugging version can be used to significantly decrease space and increase performance.
    27242983
    27252984
     
    27272986\label{s:Performance}
    27282987
    2729 To verify the implementation of the \CFA runtime, a series of microbenchmarks are performed comparing \CFA with pthreads, Java OpenJDK-9, Go 1.12.6 and \uC 7.0.0.
    2730 For comparison, the package must be multi-processor (M:N), which excludes libdill/libmil~\cite{libdill} (M:1)), and use a shared-memory programming model, \eg not message passing.
    2731 The benchmark computer is an AMD Opteron\texttrademark\ 6380 NUMA 64-core, 8 socket, 2.5 GHz processor, running Ubuntu 16.04.6 LTS, and \CFA/\uC are compiled with gcc 6.5.
    2732 
    2733 All benchmarks are run using the following harness. (The Java harness is augmented to circumvent JIT issues.)
    2734 \begin{cfa}
    2735 unsigned int N = 10_000_000;
    2736 #define BENCH( `run` ) Time before = getTimeNsec();  `run;`  Duration result = (getTimeNsec() - before) / N;
    2737 \end{cfa}
    2738 The method used to get time is @clock_gettime( CLOCK_REALTIME )@.
    2739 Each benchmark is performed @N@ times, where @N@ varies depending on the benchmark;
    2740 the total time is divided by @N@ to obtain the average time for a benchmark.
    2741 Each benchmark experiment is run 31 times.
    2742 All omitted tests for other languages are functionally identical to the \CFA tests and available online~\cite{CforallBenchMarks}.
    2743 % tar --exclude=.deps --exclude=Makefile --exclude=Makefile.in --exclude=c.c --exclude=cxx.cpp --exclude=fetch_add.c -cvhf benchmark.tar benchmark
    2744 
    2745 \paragraph{Object Creation}
    2746 
    2747 Object creation is measured by creating/deleting the specific kind of concurrent object.
    2748 Figure~\ref{f:creation} shows the code for \CFA, with results in Table~\ref{tab:creation}.
    2749 The only note here is that the call stacks of \CFA coroutines are lazily created, therefore without priming the coroutine to force stack creation, the creation cost is artificially low.
     2988To 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.
     2989For comparison, the package must be multiprocessor (M:N), which excludes libdil and libmil~\cite{libdill} (M:1)), and use a shared-memory programming model, \eg not message passing.
     2990The 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.
     2991
     2992All benchmarks are run using the following harness.
     2993(The Java harness is augmented to circumvent JIT issues.)
     2994\begin{cfa}
     2995#define BENCH( `run` ) uint64_t start = cputime_ns();  `run;`  double result = (double)(cputime_ns() - start) / N;
     2996\end{cfa}
     2997where CPU time in nanoseconds is from the appropriate language clock.
     2998Each benchmark is performed @N@ times, where @N@ is selected so the benchmark runs in the range of 2--20 s for the specific programming language;
     2999each @N@ appears after the experiment name in the following tables.
     3000The total time is divided by @N@ to obtain the average time for a benchmark.
     3001Each benchmark experiment is run 13 times and the average appears in the table.
     3002For languages with a runtime JIT (Java, Node.js, Python), a single half-hour long experiment is run to check stability;
     3003all long-experiment results are statistically equivalent, \ie median/average/SD correlate with the short-experiment results, indicating the short experiments reached a steady state.
     3004All omitted tests for other languages are functionally identical to the \CFA tests and available online~\cite{CforallConcurrentBenchmarks}.
     3005
     3006\subsection{Creation}
     3007
     3008Creation is measured by creating and deleting a specific kind of control-flow object.
     3009Figure~\ref{f:creation} shows the code for \CFA with results in Table~\ref{t:creation}.
     3010Note, 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.
    27503011
    27513012\begin{multicols}{2}
    2752 \lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
    2753 \begin{cfa}
    2754 @thread@ MyThread {};
    2755 void @main@( MyThread & ) {}
     3013\begin{cfa}[xleftmargin=0pt]
     3014`coroutine` MyCoroutine {};
     3015void ?{}( MyCoroutine & this ) {
     3016#ifdef EAGER
     3017        resume( this );
     3018#endif
     3019}
     3020void main( MyCoroutine & ) {}
    27563021int main() {
    2757         BENCH( for ( N ) { @MyThread m;@ } )
    2758         sout | result`ns;
    2759 }
    2760 \end{cfa}
    2761 \captionof{figure}{\CFA object-creation benchmark}
     3022        BENCH( for ( N ) { `MyCoroutine c;` } )
     3023        sout | result;
     3024}
     3025\end{cfa}
     3026\captionof{figure}{\CFA creation benchmark}
    27623027\label{f:creation}
    27633028
     
    27653030
    27663031\vspace*{-16pt}
    2767 \captionof{table}{Object creation comparison (nanoseconds)}
    2768 \label{tab:creation}
     3032\captionof{table}{Creation comparison (nanoseconds)}
     3033\label{t:creation}
    27693034
    27703035\begin{tabular}[t]{@{}r*{3}{D{.}{.}{5.2}}@{}}
    2771 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
    2772 \CFA Coroutine Lazy             & 13.2          & 13.1          & 0.44          \\
    2773 \CFA Coroutine Eager    & 531.3         & 536.0         & 26.54         \\
    2774 \CFA Thread                             & 2074.9        & 2066.5        & 170.76        \\
    2775 \uC Coroutine                   & 89.6          & 90.5          & 1.83          \\
    2776 \uC Thread                              & 528.2         & 528.5         & 4.94          \\
    2777 Goroutine                               & 4068.0        & 4113.1        & 414.55        \\
    2778 Java Thread                             & 103848.5      & 104295.4      & 2637.57       \\
    2779 Pthreads                                & 33112.6       & 33127.1       & 165.90
     3036\multicolumn{1}{@{}r}{Object(N)\hspace*{10pt}} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
     3037\CFA generator (1B)                     & 0.6           & 0.6           & 0.0           \\
     3038\CFA coroutine lazy     (100M)  & 13.4          & 13.1          & 0.5           \\
     3039\CFA coroutine eager (10M)      & 144.7         & 143.9         & 1.5           \\
     3040\CFA thread (10M)                       & 466.4         & 468.0         & 11.3          \\
     3041\uC coroutine (10M)                     & 155.6         & 155.7         & 1.7           \\
     3042\uC thread (10M)                        & 523.4         & 523.9         & 7.7           \\
     3043Python generator (10M)          & 123.2         & 124.3         & 4.1           \\
     3044Node.js generator (10M)         & 33.4          & 33.5          & 0.3           \\
     3045Goroutine thread (10M)          & 751.0         & 750.5         & 3.1           \\
     3046Rust tokio thread (10M)         & 1860.0        & 1881.1        & 37.6          \\
     3047Rust thread     (250K)                  & 53801.0       & 53896.8       & 274.9         \\
     3048Java thread (250K)                      & 119256.0      & 119679.2      & 2244.0        \\
     3049% Java thread (1 000 000)               & 123100.0      & 123052.5      & 751.6         \\
     3050Pthreads thread (250K)          & 31465.5       & 31419.5       & 140.4
    27803051\end{tabular}
    27813052\end{multicols}
    27823053
    2783 
    2784 \paragraph{Context-Switching}
     3054\vspace*{-10pt}
     3055\subsection{Internal scheduling}
     3056
     3057Internal scheduling is measured using a cycle of two threads signaling and waiting.
     3058Figure~\ref{f:schedint} shows the code for \CFA, with results in Table~\ref{t:schedint}.
     3059Note, the \CFA incremental cost for bulk acquire is a fixed cost for small numbers of mutex objects.
     3060User-level threading has one kernel thread, eliminating contention between the threads (direct handoff of the kernel thread).
     3061Kernel-level threading has two kernel threads allowing some contention.
     3062
     3063\begin{multicols}{2}
     3064\setlength{\tabcolsep}{3pt}
     3065\begin{cfa}[xleftmargin=0pt]
     3066volatile int go = 0;
     3067`condition c;`
     3068`monitor` M {} m1/*, m2, m3, m4*/;
     3069void call( M & `mutex p1/*, p2, p3, p4*/` ) {
     3070        `signal( c );`
     3071}
     3072void wait( M & `mutex p1/*, p2, p3, p4*/` ) {
     3073        go = 1; // continue other thread
     3074        for ( N ) { `wait( c );` } );
     3075}
     3076thread T {};
     3077void main( T & ) {
     3078        while ( go == 0 ) { yield(); } // waiter must start first
     3079        BENCH( for ( N ) { call( m1/*, m2, m3, m4*/ ); } )
     3080        sout | result;
     3081}
     3082int main() {
     3083        T t;
     3084        wait( m1/*, m2, m3, m4*/ );
     3085}
     3086\end{cfa}
     3087\vspace*{-8pt}
     3088\captionof{figure}{\CFA Internal-scheduling benchmark}
     3089\label{f:schedint}
     3090
     3091\columnbreak
     3092
     3093\vspace*{-16pt}
     3094\captionof{table}{Internal-scheduling comparison (nanoseconds)}
     3095\label{t:schedint}
     3096\bigskip
     3097
     3098\begin{tabular}{@{}r*{3}{D{.}{.}{5.2}}@{}}
     3099\multicolumn{1}{@{}r}{Object(N)\hspace*{10pt}} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
     3100\CFA @signal@, 1 monitor (10M)  & 364.4         & 364.2         & 4.4           \\
     3101\CFA @signal@, 2 monitor (10M)  & 484.4         & 483.9         & 8.8           \\
     3102\CFA @signal@, 4 monitor (10M)  & 709.1         & 707.7         & 15.0          \\
     3103\uC @signal@ monitor (10M)              & 328.3         & 327.4         & 2.4           \\
     3104Rust cond. variable     (1M)            & 7514.0        & 7437.4        & 397.2         \\
     3105Java @notify@ monitor (1M)              & 8717.0        & 8774.1        & 471.8         \\
     3106% Java @notify@ monitor (100 000 000)           & 8634.0        & 8683.5        & 330.5         \\
     3107Pthreads cond. variable (1M)    & 5553.7        & 5576.1        & 345.6
     3108\end{tabular}
     3109\end{multicols}
     3110
     3111
     3112\subsection{External scheduling}
     3113
     3114External scheduling is measured using a cycle of two threads calling and accepting the call using the @waitfor@ statement.
     3115Figure~\ref{f:schedext} shows the code for \CFA with results in Table~\ref{t:schedext}.
     3116Note, the \CFA incremental cost for bulk acquire is a fixed cost for small numbers of mutex objects.
     3117
     3118\begin{multicols}{2}
     3119\setlength{\tabcolsep}{5pt}
     3120\vspace*{-16pt}
     3121\begin{cfa}[xleftmargin=0pt]
     3122`monitor` M {} m1/*, m2, m3, m4*/;
     3123void call( M & `mutex p1/*, p2, p3, p4*/` ) {}
     3124void wait( M & `mutex p1/*, p2, p3, p4*/` ) {
     3125        for ( N ) { `waitfor( call : p1/*, p2, p3, p4*/ );` }
     3126}
     3127thread T {};
     3128void main( T & ) {
     3129        BENCH( for ( N ) { call( m1/*, m2, m3, m4*/ ); } )
     3130        sout | result;
     3131}
     3132int main() {
     3133        T t;
     3134        wait( m1/*, m2, m3, m4*/ );
     3135}
     3136\end{cfa}
     3137\captionof{figure}{\CFA external-scheduling benchmark}
     3138\label{f:schedext}
     3139
     3140\columnbreak
     3141
     3142\vspace*{-18pt}
     3143\captionof{table}{External-scheduling comparison (nanoseconds)}
     3144\label{t:schedext}
     3145\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
     3146\multicolumn{1}{@{}r}{Object(N)\hspace*{10pt}} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
     3147\CFA @waitfor@, 1 monitor (10M) & 367.1 & 365.3 & 5.0   \\
     3148\CFA @waitfor@, 2 monitor (10M) & 463.0 & 464.6 & 7.1   \\
     3149\CFA @waitfor@, 4 monitor (10M) & 689.6 & 696.2 & 21.5  \\
     3150\uC \lstinline[language=uC++]|_Accept| monitor (10M)    & 328.2 & 329.1 & 3.4   \\
     3151Go \lstinline[language=Golang]|select| channel (10M)    & 365.0 & 365.5 & 1.2
     3152\end{tabular}
     3153\end{multicols}
     3154
     3155\subsection{Mutual-Exclusion}
     3156
     3157Uncontented mutual exclusion, which frequently occurs, is measured by entering and leaving a critical section.
     3158For monitors, entering and leaving a mutex function are measured, otherwise the language-appropriate mutex-lock is measured.
     3159For comparison, a spinning (vs.\ blocking) test-and-test-set lock is presented.
     3160Figure~\ref{f:mutex} shows the code for \CFA with results in Table~\ref{t:mutex}.
     3161Note the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
     3162
     3163\begin{multicols}{2}
     3164\setlength{\tabcolsep}{3pt}
     3165\begin{cfa}[xleftmargin=0pt]
     3166`monitor` M {} m1/*, m2, m3, m4*/;
     3167call( M & `mutex p1/*, p2, p3, p4*/` ) {}
     3168int main() {
     3169        BENCH( for( N ) call( m1/*, m2, m3, m4*/ ); )
     3170        sout | result;
     3171}
     3172\end{cfa}
     3173\captionof{figure}{\CFA acquire/release mutex benchmark}
     3174\label{f:mutex}
     3175
     3176\columnbreak
     3177
     3178\vspace*{-16pt}
     3179\captionof{table}{Mutex comparison (nanoseconds)}
     3180\label{t:mutex}
     3181\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
     3182\multicolumn{1}{@{}r}{Object(N)\hspace*{10pt}} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
     3183test-and-test-set lock (50M)            & 19.1  & 18.9  & 0.4   \\
     3184\CFA @mutex@ function, 1 arg. (50M)     & 48.3  & 47.8  & 0.9   \\
     3185\CFA @mutex@ function, 2 arg. (50M)     & 86.7  & 87.6  & 1.9   \\
     3186\CFA @mutex@ function, 4 arg. (50M)     & 173.4 & 169.4 & 5.9   \\
     3187\uC @monitor@ member rtn. (50M)         & 54.8  & 54.8  & 0.1   \\
     3188Goroutine mutex lock (50M)                      & 34.0  & 34.0  & 0.0   \\
     3189Rust mutex lock (50M)                           & 33.0  & 33.2  & 0.8   \\
     3190Java synchronized method (50M)          & 31.0  & 30.9  & 0.5   \\
     3191% Java synchronized method (10 000 000 000)             & 31.0 & 30.2 & 0.9 \\
     3192Pthreads mutex Lock (50M)                       & 31.0  & 31.1  & 0.4
     3193\end{tabular}
     3194\end{multicols}
     3195
     3196\subsection{Context switching}
    27853197
    27863198In procedural programming, the cost of a function call is important as modularization (refactoring) increases.
    2787 (In many cases, a compiler inlines function calls to eliminate this cost.)
    2788 Similarly, when modularization extends to coroutines/tasks, the time for a context switch becomes a relevant factor.
     3199(In many cases, a compiler inlines function calls to increase the size and number of basic blocks for optimizing.)
     3200Similarly, when modularization extends to coroutines and threads, the time for a context switch becomes a relevant factor.
    27893201The coroutine test is from resumer to suspender and from suspender to resumer, which is two context switches.
     3202%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.
     3203For 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@).
    27903204The thread test is using yield to enter and return from the runtime kernel, which is two context switches.
    27913205The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling.
    2792 Figure~\ref{f:ctx-switch} only shows the \CFA code for coroutines/threads (other systems are similar) with all results in Table~\ref{tab:ctx-switch}.
     3206Figure~\ref{f:ctx-switch} shows the \CFA code for a coroutine and thread with results in Table~\ref{t:ctx-switch}.
     3207
     3208% From: Gregor Richards <gregor.richards@uwaterloo.ca>
     3209% To: "Peter A. Buhr" <pabuhr@plg2.cs.uwaterloo.ca>
     3210% Date: Fri, 24 Jan 2020 13:49:18 -0500
     3211%
     3212% I can also verify that the previous version, which just tied a bunch of promises together, *does not* go back to the
     3213% event loop at all in the current version of Node. Presumably they're taking advantage of the fact that the ordering of
     3214% events is intentionally undefined to just jump right to the next 'then' in the chain, bypassing event queueing
     3215% entirely. That's perfectly correct behavior insofar as its difference from the specified behavior isn't observable, but
     3216% it isn't typical or representative of much anything useful, because most programs wouldn't have whole chains of eager
     3217% promises. Also, it's not representative of *anything* you can do with async/await, as there's no way to encode such an
     3218% eager chain that way.
    27933219
    27943220\begin{multicols}{2}
    2795 \lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
    2796 \begin{cfa}[aboveskip=0pt,belowskip=0pt]
    2797 @coroutine@ C {} c;
    2798 void main( C & ) { for ( ;; ) { @suspend;@ } }
     3221\begin{cfa}[xleftmargin=0pt]
     3222`coroutine` C {};
     3223void main( C & ) { for () { `suspend;` } }
    27993224int main() { // coroutine test
    2800         BENCH( for ( N ) { @resume( c );@ } )
    2801         sout | result`ns;
    2802 }
    2803 int main() { // task test
    2804         BENCH( for ( N ) { @yield();@ } )
    2805         sout | result`ns;
     3225        C c;
     3226        BENCH( for ( N ) { `resume( c );` } )
     3227        sout | result;
     3228}
     3229int main() { // thread test
     3230        BENCH( for ( N ) { `yield();` } )
     3231        sout | result;
    28063232}
    28073233\end{cfa}
     
    28133239\vspace*{-16pt}
    28143240\captionof{table}{Context switch comparison (nanoseconds)}
    2815 \label{tab:ctx-switch}
     3241\label{t:ctx-switch}
    28163242\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
    2817 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
    2818 C function              & 1.8   & 1.8   & 0.01  \\
    2819 \CFA generator  & 2.4   & 2.2   & 0.25  \\
    2820 \CFA Coroutine  & 36.2  & 36.2  & 0.25  \\
    2821 \CFA Thread             & 93.2  & 93.5  & 2.09  \\
    2822 \uC Coroutine   & 52.0  & 52.1  & 0.51  \\
    2823 \uC Thread              & 96.2  & 96.3  & 0.58  \\
    2824 Goroutine               & 141.0 & 141.3 & 3.39  \\
    2825 Java Thread             & 374.0 & 375.8 & 10.38 \\
    2826 Pthreads Thread & 361.0 & 365.3 & 13.19
     3243\multicolumn{1}{@{}r}{Object(N)\hspace*{10pt}} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
     3244C function (10B)                        & 1.8           & 1.8           & 0.0   \\
     3245\CFA generator (5B)                     & 1.8           & 2.0           & 0.3   \\
     3246\CFA coroutine (100M)           & 32.5          & 32.9          & 0.8   \\
     3247\CFA thread (100M)                      & 93.8          & 93.6          & 2.2   \\
     3248\uC coroutine (100M)            & 50.3          & 50.3          & 0.2   \\
     3249\uC thread (100M)                       & 97.3          & 97.4          & 1.0   \\
     3250Python generator (100M)         & 40.9          & 41.3          & 1.5   \\
     3251Node.js await (5M)                      & 1852.2        & 1854.7        & 16.4  \\
     3252Node.js generator (100M)        & 33.3          & 33.4          & 0.3   \\
     3253Goroutine thread (100M)         & 143.0         & 143.3         & 1.1   \\
     3254Rust async await (100M)         & 32.0          & 32.0          & 0.0   \\
     3255Rust tokio thread (100M)        & 143.0         & 143.0         & 1.7   \\
     3256Rust thread (25M)                       & 332.0         & 331.4         & 2.4   \\
     3257Java thread (100M)                      & 405.0         & 415.0         & 17.6  \\
     3258% Java thread (  100 000 000)                   & 413.0 & 414.2 & 6.2 \\
     3259% Java thread (5 000 000 000)                   & 415.0 & 415.2 & 6.1 \\
     3260Pthreads thread (25M)           & 334.3         & 335.2         & 3.9
    28273261\end{tabular}
    28283262\end{multicols}
    28293263
    28303264
    2831 \paragraph{Mutual-Exclusion}
    2832 
    2833 Uncontented mutual exclusion, which frequently occurs, is measured by entering/leaving a critical section.
    2834 For monitors, entering and leaving a monitor function is measured.
    2835 To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a @pthread_mutex@ lock is also measured.
    2836 Figure~\ref{f:mutex} shows the code for \CFA with all results in Table~\ref{tab:mutex}.
    2837 Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
    2838 
    2839 \begin{multicols}{2}
    2840 \lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
    2841 \begin{cfa}
    2842 @monitor@ M {} m1/*, m2, m3, m4*/;
    2843 void __attribute__((noinline))
    2844 do_call( M & @mutex m/*, m2, m3, m4*/@ ) {}
    2845 int main() {
    2846         BENCH(
    2847                 for( N ) do_call( m1/*, m2, m3, m4*/ );
    2848         )
    2849         sout | result`ns;
    2850 }
    2851 \end{cfa}
    2852 \captionof{figure}{\CFA acquire/release mutex benchmark}
    2853 \label{f:mutex}
    2854 
    2855 \columnbreak
    2856 
    2857 \vspace*{-16pt}
    2858 \captionof{table}{Mutex comparison (nanoseconds)}
    2859 \label{tab:mutex}
    2860 \begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
    2861 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
    2862 test and test-and-test lock             & 19.1  & 18.9  & 0.40  \\
    2863 \CFA @mutex@ function, 1 arg.   & 45.9  & 46.6  & 1.45  \\
    2864 \CFA @mutex@ function, 2 arg.   & 105.0 & 104.7 & 3.08  \\
    2865 \CFA @mutex@ function, 4 arg.   & 165.0 & 167.6 & 5.65  \\
    2866 \uC @monitor@ member rtn.               & 54.0  & 53.7  & 0.82  \\
    2867 Java synchronized method                & 31.0  & 31.1  & 0.50  \\
    2868 Pthreads Mutex Lock                             & 33.6  & 32.6  & 1.14
    2869 \end{tabular}
    2870 \end{multicols}
    2871 
    2872 
    2873 \paragraph{External Scheduling}
    2874 
    2875 External scheduling is measured using a cycle of two threads calling and accepting the call using the @waitfor@ statement.
    2876 Figure~\ref{f:ext-sched} shows the code for \CFA, with results in Table~\ref{tab:ext-sched}.
    2877 Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
    2878 
    2879 \begin{multicols}{2}
    2880 \lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
    2881 \vspace*{-16pt}
    2882 \begin{cfa}
    2883 volatile int go = 0;
    2884 @monitor@ M {} m;
    2885 thread T {};
    2886 void __attribute__((noinline))
    2887 do_call( M & @mutex@ ) {}
    2888 void main( T & ) {
    2889         while ( go == 0 ) { yield(); }
    2890         while ( go == 1 ) { do_call( m ); }
    2891 }
    2892 int __attribute__((noinline))
    2893 do_wait( M & @mutex@ m ) {
    2894         go = 1; // continue other thread
    2895         BENCH( for ( N ) { @waitfor( do_call, m );@ } )
    2896         go = 0; // stop other thread
    2897         sout | result`ns;
    2898 }
    2899 int main() {
    2900         T t;
    2901         do_wait( m );
    2902 }
    2903 \end{cfa}
    2904 \captionof{figure}{\CFA external-scheduling benchmark}
    2905 \label{f:ext-sched}
    2906 
    2907 \columnbreak
    2908 
    2909 \vspace*{-16pt}
    2910 \captionof{table}{External-scheduling comparison (nanoseconds)}
    2911 \label{tab:ext-sched}
    2912 \begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
    2913 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
    2914 \CFA @waitfor@, 1 @monitor@     & 376.4 & 376.8 & 7.63  \\
    2915 \CFA @waitfor@, 2 @monitor@     & 491.4 & 492.0 & 13.31 \\
    2916 \CFA @waitfor@, 4 @monitor@     & 681.0 & 681.7 & 19.10 \\
    2917 \uC @_Accept@                           & 331.1 & 331.4 & 2.66
    2918 \end{tabular}
    2919 \end{multicols}
    2920 
    2921 
    2922 \paragraph{Internal Scheduling}
    2923 
    2924 Internal scheduling is measured using a cycle of two threads signalling and waiting.
    2925 Figure~\ref{f:int-sched} shows the code for \CFA, with results in Table~\ref{tab:int-sched}.
    2926 Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.
    2927 Java scheduling is significantly greater because the benchmark explicitly creates multiple thread in order to prevent the JIT from making the program sequential, \ie removing all locking.
    2928 
    2929 \begin{multicols}{2}
    2930 \lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
    2931 \begin{cfa}
    2932 volatile int go = 0;
    2933 @monitor@ M { @condition c;@ } m;
    2934 void __attribute__((noinline))
    2935 do_call( M & @mutex@ a1 ) { @signal( c );@ }
    2936 thread T {};
    2937 void main( T & this ) {
    2938         while ( go == 0 ) { yield(); }
    2939         while ( go == 1 ) { do_call( m ); }
    2940 }
    2941 int  __attribute__((noinline))
    2942 do_wait( M & mutex m ) with(m) {
    2943         go = 1; // continue other thread
    2944         BENCH( for ( N ) { @wait( c );@ } );
    2945         go = 0; // stop other thread
    2946         sout | result`ns;
    2947 }
    2948 int main() {
    2949         T t;
    2950         do_wait( m );
    2951 }
    2952 \end{cfa}
    2953 \captionof{figure}{\CFA Internal-scheduling benchmark}
    2954 \label{f:int-sched}
    2955 
    2956 \columnbreak
    2957 
    2958 \vspace*{-16pt}
    2959 \captionof{table}{Internal-scheduling comparison (nanoseconds)}
    2960 \label{tab:int-sched}
    2961 \bigskip
    2962 
    2963 \begin{tabular}{@{}r*{3}{D{.}{.}{5.2}}@{}}
    2964 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
    2965 \CFA @signal@, 1 @monitor@      & 372.6         & 374.3         & 14.17         \\
    2966 \CFA @signal@, 2 @monitor@      & 492.7         & 494.1         & 12.99         \\
    2967 \CFA @signal@, 4 @monitor@      & 749.4         & 750.4         & 24.74         \\
    2968 \uC @signal@                            & 320.5         & 321.0         & 3.36          \\
    2969 Java @notify@                           & 10160.5       & 10169.4       & 267.71        \\
    2970 Pthreads Cond. Variable         & 4949.6        & 5065.2        & 363
    2971 \end{tabular}
    2972 \end{multicols}
    2973 
    2974 
    2975 \section{Conclusion}
     3265\subsection{Discussion}
     3266
     3267Languages using 1:1 threading based on pthreads can at best meet or exceed, due to language overhead, the pthread results.
     3268Note, pthreads has a fast zero-contention mutex lock checked in user space.
     3269Languages with M:N threading have better performance than 1:1 because there is no operating-system interactions (context-switching or locking).
     3270As well, for locking experiments, M:N threading has less contention if only one kernel thread is used.
     3271Languages with stackful coroutines have higher cost than stackless coroutines because of stack allocation and context switching;
     3272however, stackful \uC and \CFA coroutines have approximately the same performance as stackless Python and Node.js generators.
     3273The \CFA stackless generator is approximately 25 times faster for suspend/resume and 200 times faster for creation than stackless Python and Node.js generators.
     3274The Node.js context-switch is costly when asynchronous await must enter the event engine because a promise is not fulfilled.
     3275Finally, the benchmark results correlate across programming languages with and without JIT, indicating the JIT has completed any runtime optimizations.
     3276
     3277
     3278\section{Conclusions and Future Work}
    29763279
    29773280Advanced control-flow will always be difficult, especially when there is temporal ordering and nondeterminism.
    29783281However, many systems exacerbate the difficulty through their presentation mechanisms.
    2979 This paper shows it is possible to present a hierarchy of control-flow features, generator, coroutine, thread, and monitor, providing an integrated set of high-level, efficient, and maintainable control-flow features.
    2980 Eliminated from \CFA are spurious wakeup and barging, which are nonintuitive and lead to errors, and having to work with a bewildering set of low-level locks and acquisition techniques.
    2981 \CFA high-level race-free monitors and tasks provide the core mechanisms for mutual exclusion and synchronization, without having to resort to magic qualifiers like @volatile@/@atomic@.
     3282This paper shows it is possible to understand high-level control-flow using three properties: statefulness, thread, mutual-exclusion/synchronization.
     3283Combining these properties creates a number of high-level, efficient, and maintainable control-flow types: generator, coroutine, thread, each of which can be a monitor.
     3284Eliminated 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.
     3285\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@.
    29823286Extending these mechanisms to handle high-level deadlock-free bulk acquire across both mutual exclusion and synchronization is a unique contribution.
    29833287The \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.
    29843288The M:N model is judged to be efficient and provide greater flexibility than a 1:1 threading model.
    29853289These 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.
    2986 Performance comparisons with other concurrent systems/languages show the \CFA approach is competitive across all low-level operations, which translates directly into good performance in well-written concurrent applications.
    2987 C programmers should feel comfortable using these mechanisms for developing complex control-flow in applications, with the ability to obtain maximum available performance by selecting mechanisms at the appropriate level of need.
    2988 
    2989 
    2990 \section{Future Work}
     3290Performance 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.
     3291C 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.
    29913292
    29923293While control flow in \CFA has a strong start, development is still underway to complete a number of missing features.
    29933294
    2994 \paragraph{Flexible Scheduling}
    2995 \label{futur:sched}
    2996 
     3295\medskip
     3296\textbf{Flexible scheduling:}
    29973297An important part of concurrency is scheduling.
    2998 Different scheduling algorithms can affect performance (both in terms of average and variation).
     3298Different scheduling algorithms can affect performance, both in terms of average and variation.
    29993299However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
    30003300One solution is to offer various tuning options, allowing the scheduler to be adjusted to the requirements of the workload.
    30013301However, to be truly flexible, a pluggable scheduler is necessary.
    3002 Currently, the \CFA pluggable scheduler is too simple to handle complex scheduling, \eg quality of service and real-time, where the scheduler must interact with mutex objects to deal with issues like priority inversion~\cite{Buhr00b}.
    3003 
    3004 \paragraph{Non-Blocking I/O}
    3005 \label{futur:nbio}
    3006 
    3007 Many modern workloads are not bound by computation but IO operations, a common case being web servers and XaaS~\cite{XaaS} (anything as a service).
     3302Currently, 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}.
     3303
     3304\smallskip
     3305\textbf{Non-Blocking I/O:}
     3306Many modern workloads are not bound by computation but IO operations, common cases being web servers and XaaS~\cite{XaaS} (anything as a service).
    30083307These types of workloads require significant engineering to amortizing costs of blocking IO-operations.
    3009 At 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.
     3308At its core, nonblocking 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.
    30103309Current 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.
    3011 However, these solutions lead to code that is hard to create, read and maintain.
    3012 A 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.
    3013 A non-blocking I/O library is currently under development for \CFA.
    3014 
    3015 \paragraph{Other Concurrency Tools}
    3016 \label{futur:tools}
    3017 
     3310However, these solutions lead to code that is hard to create, read, and maintain.
     3311A better approach is to tie nonblocking I/O into the concurrency system to provide ease of use with low overhead, \eg thread-per-connection web-services.
     3312A nonblocking I/O library is currently under development for \CFA.
     3313
     3314\smallskip
     3315\textbf{Other concurrency tools:}
    30183316While monitors offer flexible and powerful concurrency for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
    30193317Examples of such tools can include futures and promises~\cite{promises}, executors and actors.
     
    30213319As well, new \CFA extensions should make it possible to create a uniform interface for virtually all mutual exclusion, including monitors and low-level locks.
    30223320
    3023 \paragraph{Implicit Threading}
    3024 \label{futur:implcit}
    3025 
    3026 Basic concurrent (embarrassingly parallel) applications can benefit greatly from implicit concurrency, where sequential programs are converted to concurrent, possibly with some help from pragmas to guide the conversion.
     3321\smallskip
     3322\textbf{Implicit threading:}
     3323Basic \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.
    30273324This type of concurrency can be achieved both at the language level and at the library level.
    30283325The canonical example of implicit concurrency is concurrent nested @for@ loops, which are amenable to divide and conquer algorithms~\cite{uC++book}.
    3029 The \CFA language features should make it possible to develop a reasonable number of implicit concurrency mechanism to solve basic HPC data-concurrency problems.
     3326The \CFA language features should make it possible to develop a reasonable number of implicit concurrency mechanisms to solve basic HPC data-concurrency problems.
    30303327However, implicit concurrency is a restrictive solution with significant limitations, so it can never replace explicit concurrent programming.
    30313328
     
    30333330\section{Acknowledgements}
    30343331
    3035 The authors would like to recognize the design assistance of Aaron Moss, Rob Schluntz, Andrew Beach and Michael Brooks on the features described in this paper.
    3036 Funding for this project has been provided by Huawei Ltd.\ (\url{http://www.huawei.com}). %, and Peter Buhr is partially funded by the Natural Sciences and Engineering Research Council of Canada.
     3332The 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.
     3333This research is funded by the NSERC/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.
    30373334
    30383335{%
    3039 \fontsize{9bp}{12bp}\selectfont%
     3336\fontsize{9bp}{11.5bp}\selectfont%
    30403337\bibliography{pl,local}
    30413338}%
Note: See TracChangeset for help on using the changeset viewer.