Changes in / [97392b69:a5873bd]


Ignore:
Files:
1 added
13 deleted
27 edited

Legend:

Unmodified
Added
Removed
  • benchmark/creation/node_cor.js

    r97392b69 ra5873bd  
    55
    66function * coroutine() { yield }
    7 
    8 for ( var i = 0; i < times; i += 1 ) { // warm jit
    9         cor = coroutine()
    10 }
    11 
    127var hrstart = process.hrtime()
    138for ( var i = 0; i < times; i += 1 ) {
  • benchmark/ctxswitch/node_cor.js

    r97392b69 ra5873bd  
    1010}
    1111cor = coroutine()
    12 
    13 for ( var i = 0; i < times; i += 1 ) { // warm git
    14         cor.next();
    15 }
    1612
    1713var hrstart = process.hrtime()
  • benchmark/exclude

    r97392b69 ra5873bd  
    1010interrupt_linux.c
    1111exclude
    12 io
    1312Monitor.c
  • doc/bibliography/pl.bib

    r97392b69 ra5873bd  
    10011001}
    10021002
    1003 @misc{CforallConcurrentBenchmarks,
     1003@misc{CforallBenchMarks,
    10041004    contributer = {pabuhr@plg},
    10051005    key         = {Cforall Benchmarks},
    10061006    author      = {{\textsf{C}{$\mathbf{\forall}$} Benchmarks}},
    1007     howpublished= {\href{https://plg.uwaterloo.ca/~cforall/doc/CforallConcurrentBenchmarks.tar}{https://\-plg.uwaterloo.ca/\-$\sim$cforall/\-doc/\-CforallConcurrentBenchmarks.tar}},
     1007    howpublished= {\href{https://plg.uwaterloo.ca/~cforall/benchmark.tar}{https://\-plg.uwaterloo.ca/\-$\sim$cforall/\-benchmark.tar}},
    10081008}
    10091009
     
    19821982    author      = {Adya, Atul and Howell, Jon and Theimer, Marvin and Bolosky, William J. and Douceur, John R.},
    19831983    title       = {Cooperative Task Management Without Manual Stack Management},
    1984     booktitle   = {Proc. of the General Track USENIX Tech. Conf.},
     1984    booktitle   = {Proceedings of the General Track of the Annual Conference on USENIX Annual Technical Conference},
    19851985    series      = {ATEC '02},
    19861986    year        = {2002},
  • doc/papers/AMA/AMA-stix/ama/WileyNJD-v2.cls

    r97392b69 ra5873bd  
    24442444     \@afterheading}
    24452445
    2446 \renewcommand\section{\@startsection{section}{1}{\z@}{-20pt \@plus -2pt \@minus -2pt}{7\p@}{\sectionfont}}%
    2447 \renewcommand\subsection{\@startsection{subsection}{2}{\z@}{-18pt \@plus -2pt \@minus -2pt}{5\p@}{\subsectionfont}}%
    2448 \renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}{-16pt \@plus -2pt \@minus -2pt}{2\p@}{\subsubsectionfont}}%
     2446\renewcommand\section{\@startsection{section}{1}{\z@}{-25pt \@plus -2pt \@minus -2pt}{12\p@}{\sectionfont}}%
     2447\renewcommand\subsection{\@startsection{subsection}{2}{\z@}{-22pt \@plus -2pt \@minus -2pt}{5\p@}{\subsectionfont}}%
     2448\renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}{-20pt \@plus -2pt \@minus -2pt}{2\p@}{\subsubsectionfont}}%
    24492449%
    24502450\newskip\secruleskip\secruleskip8.5\p@%
  • doc/papers/concurrency/Paper.tex

    r97392b69 ra5873bd  
    9999\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
    100100
    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}
     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}
    103103% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
    104104\newcommand{\newtermFontInline}{\emph}
     
    235235{\lstset{language=python,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
    236236{}
    237 \lstnewenvironment{java}[1][]
    238 {\lstset{language=java,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
    239 {}
    240237
    241238% inline code @...@
     
    269266
    270267\abstract[Summary]{
    271 \CFA is a polymorphic, non-object-oriented, concurrent, backwards compatible extension of the C programming language.
     268\CFA is a polymorphic, non-object-oriented, concurrent, backwards-compatible extension of the C programming language.
    272269This paper discusses the design philosophy and implementation of its advanced control-flow and concurrent/parallel features, along with the supporting runtime written in \CFA.
    273270These 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.
     
    275272% Library extension for executors, futures, and actors are built on these basic mechanisms.
    276273The runtime provides significant programmer simplification and safety by eliminating spurious wakeup and monitor barging.
    277 The 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.
     274The runtime also ensures multiple monitors can be safely acquired \emph{simultaneously} (deadlock free), and this feature is fully integrated with all monitor synchronization mechanisms.
    278275All control-flow features integrate with the \CFA polymorphic type-system and exception handling, while respecting the expectations and style of C programmers.
    279276Experimental results show comparable performance of the new features with similar mechanisms in other concurrent programming languages.
     
    296293% "Trait inheritance" works for me. "Interface inheritance" might also be a good choice, and distinguish clearly from implementation inheritance.
    297294% You'll want to be a little bit careful with terms like "structural" and "nominal" inheritance as well. CFA has structural inheritance (I think Go as well) -- it's inferred based on the structure of the code. Java, Rust, and Haskell (not sure about Swift) have nominal inheritance, where there needs to be a specific statement that "this type inherits from this type".
    298 However, functions \emph{cannot} be nested in structures, so there is no lexical binding between a structure and set of functions implemented by an implicit \lstinline@this@ (receiver) parameter.},
     295However, functions \emph{cannot} be nested in structures, so there is no lexical binding between a structure and set of functions (member/method) implemented by an implicit \lstinline@this@ (receiver) parameter.},
    299296backwards-compatible extension of the C programming language.
    300 In 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{
    301 The 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.}
     297In many ways, \CFA is to C as Scala~\cite{Scala} is to Java, providing a \emph{research vehicle} for new typing and control-flow capabilities on top of a highly popular programming language\footnote{
     298The TIOBE index~\cite{TIOBE} for December 2019 ranks the top five \emph{popular} programming languages as Java 17\%, C 16\%, Python 10\%, and \CC 6\%, \Csharp 5\% = 54\%, and over the past 30 years, C has always ranked either first or second in popularity.}
    302299allowing immediate dissemination.
    303 This 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.
     300This paper discusses the design philosophy and implementation of advanced language-level control-flow and concurrent/parallel features in \CFA and its runtime, which is written entirely in \CFA.
     301The \CFA control-flow framework extends ISO \Celeven~\cite{C11} with new call/return and concurrent/parallel control-flow.
    304302
    305303% The call/return extensions retain state between callee and caller versus losing the callee's state on return;
    306304% the concurrency extensions allow high-level management of threads.
    307305
    308 The \CFA control-flow framework extends ISO \Celeven~\cite{C11} with new call/return and concurrent/parallel control-flow.
    309 Call/return control-flow with argument and parameter passing appeared in the first programming languages.
    310 Over the past 50 years, call/return has been augmented with features like static and dynamic call, exceptions (multi-level return) and generators/coroutines (see Section~\ref{s:StatefulFunction}).
    311 While \CFA has mechanisms for dynamic call (algebraic effects~\cite{Zhang19}) and exceptions\footnote{
     306Call/return control-flow with argument/parameter passing appeared in the first programming languages.
     307Over the past 50 years, call/return has been augmented with features like static/dynamic call, exceptions (multi-level return) and generators/coroutines (retain state between calls).
     308While \CFA has mechanisms for dynamic call (algebraic effects) and exceptions\footnote{
    312309\CFA exception handling will be presented in a separate paper.
    313 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++}}, this work only discusses retaining state between calls via generators and coroutines.
     310The key feature that dovetails with this paper is nonlocal exceptions allowing exceptions to be raised across stacks, with synchronous exceptions raised among coroutines and asynchronous exceptions raised among threads, similar to that in \uC~\cite[\S~5]{uC++}}, this work only discusses retaining state between calls via generators/coroutines.
    314311\newterm{Coroutining} was introduced by Conway~\cite{Conway63} (1963), discussed by Knuth~\cite[\S~1.4.2]{Knuth73V1}, implemented in Simula67~\cite{Simula67}, formalized by Marlin~\cite{Marlin80}, and is now popular and appears in old and new programming languages: CLU~\cite{CLU}, \Csharp~\cite{Csharp}, Ruby~\cite{Ruby}, Python~\cite{Python}, JavaScript~\cite{JavaScript}, Lua~\cite{Lua}, \CCtwenty~\cite{C++20Coroutine19}.
    315312Coroutining is sequential execution requiring direct handoff among coroutines, \ie only the programmer is controlling execution order.
    316 If 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}.
     313If coroutines transfer to an internal event-engine for scheduling the next coroutines, the program transitions into the realm of concurrency~\cite[\S~3]{Buhr05a}.
    317314Coroutines are only a stepping stone towards concurrency where the commonality is that coroutines and threads retain state between calls.
    318315
    319 \Celeven/\CCeleven define concurrency~\cite[\S~7.26]{C11}, but it is largely wrappers for a subset of the pthreads library~\cite{Pthreads}.\footnote{Pthreads concurrency is based on simple thread fork and join in a function and mutex or condition locks, which is low-level and error-prone}
    320 Interestingly, 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).
     316\Celeven/\CCeleven define concurrency~\cite[\S~7.26]{C11}, but it is largely wrappers for a subset of the pthreads library~\cite{Pthreads}.\footnote{Pthreads concurrency is based on simple thread fork/join in a function and mutex/condition locks, which is low-level and error-prone}
     317Interestingly, almost a decade after the \Celeven standard, neither gcc-9, clang-9 nor msvc-19 (most recent versions) support the \Celeven include @threads.h@, indicating no interest in the C11 concurrency approach (possibly because of the recent effort to add concurrency to \CC).
    321318While 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.
    322319In contrast, there has been a renewed interest during the past decade in user-level (M:N, green) threading in old and new programming languages.
     
    324321Kernel 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}.
    325322Libraries like pthreads were developed for C, and the Solaris operating-system switched from user (JDK 1.1~\cite{JDK1.1}) to kernel threads.
    326 As 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.
     323As a result, many current languages implementations adopt the 1:1 kernel-threading model, like Java (Scala), Objective-C~\cite{obj-c-book}, \CCeleven~\cite{C11}, C\#~\cite{Csharp} and Rust~\cite{Rust}, with a variety of presentation mechanisms.
    327324From 2000 onwards, several language implementations have championed the M:N user-threading model, like Go~\cite{Go}, Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, D~\cite{D}, and \uC~\cite{uC++,uC++book}, including putting green threads back into Java~\cite{Quasar}, and many user-threading libraries have appeared~\cite{Qthreads,MPC,Marcel}.
    328 The 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}.
     325The main argument for user-level threading is that it is lighter weight than kernel threading (locking and context switching do not cross the kernel boundary), so there is less restriction on programming styles that encourages large numbers of threads performing medium-sized work to facilitate load balancing by the runtime~\cite{Verch12}.
    329326As well, user-threading facilitates a simpler concurrency approach using thread objects that leverage sequential patterns versus events with call-backs~\cite{Adya02,vonBehren03}.
    330 Finally, 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.
     327Finally, performant user-threading implementations (both time and space) meet or exceed direct kernel-threading implementations, while achieving the programming advantages of high concurrency levels and safety.
    331328
    332329A 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}.
    333 The 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.
    334 One solution is low-level qualifiers and functions, \eg @volatile@ and atomics, allowing \emph{programmers} to explicitly write safe, race-free~\cite{Boehm12} programs.
    335 A 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.
     330The consequence is that a language must provide sufficient tools to program around safety issues, as inline and library code is all sequential to the compiler.
     331One solution is low-level qualifiers and functions (\eg @volatile@ and atomics) allowing \emph{programmers} to explicitly write safe (race-free~\cite{Boehm12}) programs.
     332A safer solution is high-level language constructs so the \emph{compiler} knows the concurrency boundaries (where mutual exclusion and synchronization are acquired/released) and provide implicit safety at and across these boundaries.
    336333While the optimization problem is best known with respect to concurrency, it applies to other complex control-flow, like exceptions and coroutines.
    337334As 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.
    338335
    339 Finally, it is important for a language to provide safety over performance \emph{as the default}, allowing careful reduction of safety for performance when necessary.
    340 Two concurrency violations of this philosophy are \emph{spurious} or \emph{random wakeup}~\cite[\S~9]{Buhr05a}, and \emph{barging}\footnote{
     336Finally, it is important for a language to provide safety over performance \emph{as the default}, allowing careful reduction of safety (unsafe code) for performance when necessary.
     337Two concurrency violations of this philosophy are \emph{spurious wakeup} (random wakeup~\cite[\S~9]{Buhr05a}) and \emph{barging}\footnote{
    341338Barging is competitive succession instead of direct handoff, \ie after a lock is released both arriving and preexisting waiter threads compete to acquire the lock.
    342339Hence, an arriving thread can temporally \emph{barge} ahead of threads already waiting for an event, which can repeat indefinitely leading to starvation of waiter threads.
    343 } or signals-as-hints~\cite[\S~8]{Buhr05a}, where one is a consequence of the other, \ie once there is spurious wakeup, barging follows.
     340} (signals-as-hints~\cite[\S~8]{Buhr05a}), where one is a consequence of the other, \ie once there is spurious wakeup, signals-as-hints follow.
    344341(Author experience teaching concurrency is that students are confused by these semantics.)
    345342However, spurious wakeup is \emph{not} a foundational concurrency property~\cite[\S~9]{Buhr05a};
     
    359356
    360357\item
    361 monitor 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,
     358monitor synchronization without barging, and the ability to safely acquiring multiple monitors \emph{simultaneously} (deadlock free), while seamlessly integrating these capabilities with all monitor synchronization mechanisms,
    362359
    363360\item
     
    371368
    372369\item
    373 a 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.
     370a dynamic partitioning mechanism to segregate groups of executing user and kernel threads performing specialized work (\eg web-server or compute engine) or requiring different scheduling (\eg NUMA or real-time).
    374371
    375372% \item
     
    383380Section~\ref{s:StatefulFunction} begins advanced control by introducing sequential functions that retain data and execution state between calls producing constructs @generator@ and @coroutine@.
    384381Section~\ref{s:Concurrency} begins concurrency, or how to create (fork) and destroy (join) a thread producing the @thread@ construct.
    385 Section~\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.
     382Section~\ref{s:MutualExclusionSynchronization} discusses the two mechanisms to restricted nondeterminism when controlling shared access to resources (mutual exclusion) and timing relationships among threads (synchronization).
    386383Section~\ref{s:Monitor} shows how both mutual exclusion and synchronization are safely embedded in the @monitor@ and @thread@ constructs.
    387 Section~\ref{s:CFARuntimeStructure} describes the large-scale mechanism to structure threads and virtual processors (kernel threads).
    388 Section~\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.
     384Section~\ref{s:CFARuntimeStructure} describes the large-scale mechanism to structure (cluster) threads and virtual processors (kernel threads).
     385Section~\ref{s:Performance} uses a series of microbenchmarks to compare \CFA threading with pthreads, Java 11.0.6, Go 1.12.6, Rust 1.37.0, Python 3.7.6, Node.js 12.14.1, and \uC 7.0.0.
    389386
    390387
     
    395392To 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++}).
    396393The fundamental properties are execution state, thread, and mutual-exclusion/synchronization (MES).
    397 These 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.
    398 While 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.
    399 As 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.
    400 If a compositional feature is missing, a programmer has too few fundamental properties resulting in a complex and/or is inefficient solution.
     394These independent properties can be used alone, in pairs, or in triplets to compose different language features, forming a compositional hierarchy where the most advanced feature has all the properties (state/thread/MES).
     395While it is possible for a language to only support the most advanced feature~\cite{Hermes90}, this unnecessarily complicates and makes inefficient solutions to certain classes of problems.
     396As is shown, each of the (non-rejected) composed features solves a particular set of problems, and hence, has a defensible position in a programming language.
     397If a compositional feature is missing, a programmer has too few/many fundamental properties resulting in a complex and/or is inefficient solution.
    401398
    402399In detail, the fundamental properties are:
    403400\begin{description}[leftmargin=\parindent,topsep=3pt,parsep=0pt]
    404401\item[\newterm{execution state}:]
    405 is the state information needed by a control-flow feature to initialize, manage compute data and execution location(s), and de-initialize, \eg calling a function initializes a stack frame including contained objects with constructors, manages local data in blocks and return locations during calls, and de-initializes the frame by running any object destructors and management operations.
    406 State is retained in fixed-sized aggregate structures (objects) and dynamic-sized stack(s), often allocated in the heap(s) managed by the runtime system.
    407 The 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.
    408 Control-flow transfers among execution states in multiple ways, such as function call, context switch, asynchronous await, etc.
     402is the state information needed by a control-flow feature to initialize, manage compute data and execution location(s), and de-initialize.
     403State is retained in fixed-sized aggregate structures and dynamic-sized stack(s), often allocated in the heap(s) managed by the runtime system.
     404The lifetime of the state varies with the control-flow feature, where longer life-time and dynamic size provide greater power but also increase usage complexity and cost.
     405Control-flow transfers among execution states occurs in multiple ways, such as function call, context switch, asynchronous await, etc.
    409406Because 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.
    410407% An execution-state is related to the notion of a process continuation \cite{Hieb90}.
    411408
    412409\item[\newterm{threading}:]
    413 is execution of code that occurs independently of other execution, where an individual thread's execution is sequential.
     410is execution of code that occurs independently of other execution, \ie the execution resulting from a thread is sequential.
    414411Multiple threads provide \emph{concurrent execution};
    415 concurrent execution becomes parallel when run on multiple processing units, \eg hyper-threading, cores, or sockets.
    416 There must be language mechanisms to create, block and unblock, and join with a thread, even if the mechanism is indirect.
     412concurrent execution becomes parallel when run on multiple processing units (hyper-threading, cores, sockets).
     413There must be language mechanisms to create, block/unblock, and join with a thread.
    417414
    418415\item[\newterm{MES}:]
    419416is the concurrency mechanisms to perform an action without interruption and establish timing relationships among multiple threads.
    420 We contented these two properties are independent, \ie mutual exclusion cannot provide synchronization and vice versa without introducing additional threads~\cite[\S~4]{Buhr05a}.
     417These two properties are independent, \ie mutual exclusion cannot provide synchronization and vice versa without introducing additional threads~\cite[\S~4]{Buhr05a}.
    421418Limiting MES, \eg no access to shared data, results in contrived solutions and inefficiency on multi-core von Neumann computers where shared memory is a foundational aspect of its design.
    422419\end{description}
    423 These properties are fundamental because they cannot be built from existing language features, \eg a basic programming language like C99~\cite{C99} cannot create new control-flow features, concurrency, or provide MES without atomic hardware mechanisms.
    424 
    425 
    426 \subsection{Structuring Execution Properties}
    427 
    428 Programming languages seldom present the fundamental execution properties directly to programmers.
    429 Instead, the properties are packaged into higher-level constructs that encapsulate details and provide safety to these low-level mechanisms.
    430 Interestingly, language designers often pick and choose among these execution properties proving a varying subset of constructs.
    431 
    432 Table~\ref{t:ExecutionPropertyComposition} shows all combinations of the three fundamental execution properties available to language designers.
    433 (When doing combination case-analysis, not all combinations are meaningful.)
    434 The 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.
    435 To 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.
     420These properties are fundamental because they cannot be built from existing language features, \eg a basic programming language like C99~\cite{C99} cannot create new control-flow features, concurrency, or provide MES using atomic hardware mechanisms.
     421
     422
     423\subsection{Execution Properties}
     424
     425Table~\ref{t:ExecutionPropertyComposition} shows how the three fundamental execution properties: state, thread, and mutual exclusion compose a hierarchy of control-flow features needed in a programming language.
     426(When doing case analysis, not all combinations are meaningful.)
     427Note, basic von Neumann execution requires at least one thread and an execution state providing some form of call stack.
    436428For table entries missing these minimal components, the property is borrowed from the invoker (caller).
    437 Each 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.
     429
     430Case 1 is a function that borrows storage for its state (stack frame/activation) and a thread from its invoker and retains this state across \emph{callees}, \ie function local-variables are retained on the stack across calls.
     431Case 2 is case 1 with access to shared state so callers are restricted during update (mutual exclusion) and scheduling for other threads (synchronization).
     432Case 3 is a stateful function supporting resume/suspend along with call/return to retain state across \emph{callers}, but has some restrictions because the function's state is stackless.
     433Note, stackless functions still borrow the caller's stack and thread, where the stack is used to preserve state across its callees.
     434Case 4 is cases 2 and 3 with protection to shared state for stackless functions.
     435Cases 5 and 6 are the same as 3 and 4 but only the thread is borrowed as the function state is stackful, so resume/suspend is a context switch from the caller's to the function's stack.
     436Cases 7 and 8 are rejected because a function that is given a new thread must have its own stack where the thread begins and stack frames are stored for calls, \ie there is no stack to borrow.
     437Cases 9 and 10 are rejected because a thread with a fixed state (no stack) cannot accept calls, make calls, block, or be preempted, all of which require an unknown amount of additional dynamic state.
     438Hence, once started, this kind of thread must execute to completion, \ie computation only, which severely restricts runtime management.
     439Cases 11 and 12 have a stackful thread with and without safe access to shared state.
     440Execution properties increase the cost of creation and execution along with complexity of usage.
    438441
    439442\begin{table}
     
    449452\hline   
    450453\hline   
    451 No                                      & No            & \textbf{1}\ \ \ @struct@                              & \textbf{2}\ \ \ @mutex@ @struct@              \\
     454No                                      & No            & \textbf{1}\ \ \ function                              & \textbf{2}\ \ \ @monitor@ function    \\
    452455\hline   
    453 Yes (stackless)         & No            & \textbf{3}\ \ \ @generator@                   & \textbf{4}\ \ \ @mutex@ @generator@   \\
     456Yes (stackless)         & No            & \textbf{3}\ \ \ @generator@                   & \textbf{4}\ \ \ @monitor@ @generator@ \\
    454457\hline   
    455 Yes (stackful)          & No            & \textbf{5}\ \ \ @coroutine@                   & \textbf{6}\ \ \ @mutex@ @coroutine@   \\
     458Yes (stackful)          & No            & \textbf{5}\ \ \ @coroutine@                   & \textbf{6}\ \ \ @monitor@ @coroutine@ \\
    456459\hline   
    457460No                                      & Yes           & \textbf{7}\ \ \ {\color{red}rejected} & \textbf{8}\ \ \ {\color{red}rejected} \\
     
    459462Yes (stackless)         & Yes           & \textbf{9}\ \ \ {\color{red}rejected} & \textbf{10}\ \ \ {\color{red}rejected} \\
    460463\hline   
    461 Yes (stackful)          & Yes           & \textbf{11}\ \ \ @thread@                             & \textbf{12}\ \ @mutex@ @thread@               \\
     464Yes (stackful)          & Yes           & \textbf{11}\ \ \ @thread@                             & \textbf{12}\ \ @monitor@ @thread@             \\
    462465\end{tabular}
    463466\end{table}
    464467
    465 Case 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.
    466 Structures are a foundational mechanism for data organization, and access functions provide interface abstraction and code sharing in all programming languages.
    467 Case 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).
    468 A @mutex@ structure, often called a \newterm{monitor}, provides a high-level interface for race-free access of shared data in concurrent programming-languages.
    469 Case 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.
    470 A stackless structure, often called a \newterm{generator} or \emph{iterator}, is \newterm{stackless} because it still borrow the caller's stack and thread, but the stack is used only to preserve state across its callees not callers.
    471 Generators provide the first step toward directly solving problems like finite-state machines that retain data and execution state between calls, whereas normal functions restart on each call.
    472 Case 4 is cases 2 and 3 with thread safety during execution of the generator's access functions.
    473 A @mutex@ generator extends generators into the concurrent domain.
    474 Cases 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.
    475 A 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.
    476 A coroutine extends the state retained between calls beyond the generator's structure to arbitrary call depth in the access functions.
    477 Cases 7 and 8 are rejected because a new thread must have its own stack, where the thread begins and stack frames are stored for calls, \ie it is unrealistic for a thread to borrow a stack.
    478 Cases 9 and 10 are rejected because a thread needs a growable stack to accept calls, make calls, block, or be preempted, all of which compound to require an unknown amount of execution state.
    479 If this kind of thread exists, it must execute to completion, \ie computation only, which severely restricts runtime management.
    480 Cases 11 and 12 are a stackful thread with and without safe access to shared state.
    481 A thread is the language mechanism to start another thread of control in a program with growable execution state for call/return execution.
    482 In general, language constructs with more execution properties increase the cost of creation and execution along with complexity of usage.
    483 
    484 Given 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.
    485 Table~\ref{t:ExecutionPropertyComposition} then suggests the optimal language feature needed for implementing a programming problem.
    486 The following sections describe how \CFA fills in \emph{all} the non-rejected table entries with language features, while other programming languages may only provide a subset of the table.
     468Given the execution-properties taxonomy, programmers can now answer three basic questions: is state necessary across calls and how much, is a separate thread necessary, is access to shared state necessary.
     469The answers define the optimal language feature need for implementing a programming problem.
     470The next sections discusses how \CFA fills in the table with language features, while other programming languages may only provide a subset of the table.
    487471
    488472
     
    497481\item
    498482Direct interaction among language features must be possible allowing any feature to be selected without restricting comm\-unication.
    499 For example, many concurrent languages do not provide direct communication calls among threads, \ie threads only communicate indirectly through monitors, channels, messages, and/or futures.
    500 Indirect communication increases the number of objects, consuming more resources, and requires additional synchronization and possibly data transfer.
     483For example, many concurrent languages do not provide direct communication (calls) among threads, \ie threads only communicate indirectly through monitors, channels, messages, and/or futures.
     484Indirect communication increases the number of objects, consuming more resources, and require additional synchronization and possibly data transfer.
    501485
    502486\item
     
    509493
    510494\item
    511 MES 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.
     495MES must be available implicitly in language constructs as well as explicitly for specialized requirements, because requiring programmers to build MES using low-level locks often leads to incorrect programs.
    512496Furthermore, reducing synchronization scope by encapsulating it within language constructs further reduces errors in concurrent programs.
    513497
     
    518502\item
    519503Synchronization 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.
    520 Otherwise, certain concurrency problems are difficult, \eg web server, disk scheduling, and the amount of concurrency is inhibited~\cite{Gentleman81}.
     504Otherwise, certain concurrency problems are difficult, e.g.\ web server, disk scheduling, and the amount of concurrency is inhibited~\cite{Gentleman81}.
    521505\end{itemize}
    522506We have satisfied these requirements in \CFA while maintaining backwards compatibility with the huge body of legacy C programs.
     
    527511
    528512Asynchronous 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).
    529 The caller detects the action's completion through a \newterm{future} or \newterm{promise}.
     513The caller detects the action's completion through a \newterm{future}/\newterm{promise}.
    530514The benefit is asynchronous caller execution with respect to the callee until future resolution.
    531515For 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.
     
    533517A promise-completion call-back can be part of the callee action or the caller is rescheduled;
    534518in either case, the call back is executed after the promise is fulfilled.
    535 While 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.
     519While asynchronous calls generate new callee (server) events, we content this mechanism is insufficient for advanced control-flow mechanisms like generators or coroutines (which are discussed next).
    536520Specifically, 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.
    537521Note, @async-await@ is just syntactic-sugar over the event engine so it does not solve these deficiencies.
    538522For multi-threaded languages like Java, the asynchronous call queues a callee action with an executor (server), which subsequently executes the work by a thread in the executor thread-pool.
    539 The problem is when concurrent work-units need to interact and/or block as this effects the executor by stopping threads.
     523The problem is when concurrent work-units need to interact and/or block as this effects the executor, \eg stops threads.
    540524While 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.
    541525
     
    556540There are two styles of activating a stateful function, \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles).
    557541These 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.
    558 Selecting 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.
    559 Additionally, storage management for the closure/stack must be factored into design and performance, especially in unmanaged languages without garbage collection.
     542Selecting between stackless/stackful semantics and asymmetric/symmetric style is a tradeoff between programming requirements, performance, and design, where stackless is faster and smaller (modified call/return between closures), stackful is more general but slower and larger (context switching between distinct stacks), and asymmetric is simpler control-flow than symmetric.
     543Additionally, storage management for the closure/stack (especially in unmanaged languages, \ie no garbage collection) must be factored into design and performance.
    560544Note, creation cost (closure/stack) is amortized across usage, so activation cost (resume/suspend) is usually the dominant factor.
    561545
     
    594578&
    595579\begin{cfa}
    596 void * `rtn`( void * arg ) { ... }
     580void * rtn( void * arg ) { ... }
    597581int i = 3, rc;
    598582pthread_t t; $\C{// thread id}$
     
    706690\hspace{3pt}
    707691\subfloat[C generated code for \CFA version]{\label{f:CFibonacciSim}\usebox\myboxC}
    708 \caption{Fibonacci output asymmetric generator}
     692\caption{Fibonacci (output) asymmetric generator}
    709693\label{f:FibonacciAsymmetricGenerator}
    710694
     
    781765\subfloat[C generated code for \CFA version]{\label{f:CFormatGenImpl}\usebox\myboxB}
    782766\hspace{3pt}
    783 \caption{Formatter input asymmetric generator}
     767\caption{Formatter (input) asymmetric generator}
    784768\label{f:FormatterAsymmetricGenerator}
    785769\end{figure}
    786770
    787 Figure~\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.
     771Figure~\ref{f:FibonacciAsymmetricGenerator} shows an unbounded asymmetric generator for an infinite sequence of Fibonacci numbers written (left to right) in C, \CFA, and showing the underlying C implementation for the \CFA version.
    788772This generator is an \emph{output generator}, producing a new result on each resumption.
    789773To 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.
    790 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;
     774An additional requirement is the ability to create an arbitrary number of generators (of any kind), \ie retaining one state in global variables is insufficient;
    791775hence, state is retained in a closure between calls.
    792776Figure~\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.
     
    810794Figure~\ref{f:CFibonacciSim} shows the C implementation of the \CFA asymmetric generator.
    811795Only one execution-state field, @restart@, is needed to subscript the suspension points in the generator.
    812 At 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}.
     796At the start of the generator main, the @static@ declaration, @states@, is initialized to the N suspend points in the generator (where operator @&&@ dereferences/references a label~\cite{gccValueLabels}).
    813797Next, the computed @goto@ selects the last suspend point and branches to it.
    814 The  cost of setting @restart@ and branching via the computed @goto@ adds very little cost to the suspend and resume calls.
     798The  cost of setting @restart@ and branching via the computed @goto@ adds very little cost to the suspend/resume calls.
    815799
    816800An advantage of the \CFA explicit generator type is the ability to allow multiple type-safe interface functions taking and returning arbitrary types.
     
    893877With 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.
    894878Our 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.
    895 As well, C programmers are not afraid of this kind of semantic programming requirement, if it results in very small and fast generators.
     879As well, C programmers are not afraid of this kind of semantic programming requirement, if it results in very small, fast generators.
    896880
    897881Figure~\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.
     
    915899The destructor provides a newline, if formatted text ends with a full line.
    916900Figure~\ref{f:CFormatGenImpl} shows the C implementation of the \CFA input generator with one additional field and the computed @goto@.
    917 For contrast, Figure~\ref{f:PythonFormatter} shows the equivalent Python format generator with the same properties as the \CFA format generator.
     901For contrast, Figure~\ref{f:PythonFormatter} shows the equivalent Python format generator with the same properties as the format generator.
    918902
    919903% https://dl-acm-org.proxy.lib.uwaterloo.ca/
    920904
    921 An 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}
     905Figure~\ref{f:DeviceDriverGen} shows an important application for an asymmetric generator, a device-driver, because device drivers are a significant source of operating-system errors: 85\% in Windows XP~\cite[p.~78]{Swift05} and 51.6\% in Linux~\cite[p.~1358,]{Xiao19}. %\cite{Palix11}
    922906Swift \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;
    923907however, the calls do not retain execution state, and hence always start from the top.
     
    925909However, 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.
    926910
    927 Figure~\ref{f:DeviceDriverGen} shows the generator advantages in implementing a simple network device-driver with the following protocol:
     911As an example, the following protocol:
    928912\begin{center}
    929913\ldots\, STX \ldots\, message \ldots\, ESC ETX \ldots\, message \ldots\, ETX 2-byte crc \ldots
    930914\end{center}
    931 where the network message begins with the control character STX, ends with an ETX, and is followed by a 2-byte cyclic-redundancy check.
     915is for a simple network message beginning with the control character STX, ending with an ETX, and followed by a 2-byte cyclic-redundancy check.
    932916Control characters may appear in a message if preceded by an ESC.
    933917When 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.
    934 The 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.
    935 Hence, 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.
     918The device driver returns a status code of its current state, and when a complete message is obtained, the operating system read the message accumulated in the supplied buffer.
     919Hence, the device driver is an input/output generator, where the cost of resuming the device-driver generator is the same as call/return, so performance in an operating-system kernel is excellent.
    936920The key benefits of using a generator are correctness, safety, and maintenance because the execution states are transcribed directly into the programming language rather than table lookup or stack ripping.
    937 % The conclusion is that FSMs are complex and occur in important domains, so direct generator support is important in a system programming language.
     921The conclusion is that FSMs are complex and occur in important domains, so direct generator support is important in a system programming language.
    938922
    939923\begin{figure}
     
    992976\end{figure}
    993977
    994 Generators can also have symmetric activation using resume/resume to create control-flow cycles among generators.
     978Figure~\ref{f:CFAPingPongGen} shows a symmetric generator, where the generator resumes another generator, forming a resume/resume cycle.
    995979(The trivial cycle is a generator resuming itself.)
    996980This control flow is similar to recursion for functions but without stack growth.
    997 Figure~\ref{f:PingPongFullCoroutineSteps} shows the steps for symmetric control-flow using for the ping/pong program in Figure~\ref{f:CFAPingPongGen}.
    998 The program starts by creating the generators, @ping@ and @pong@, and then assigns the partners that form the cycle.
     981Figure~\ref{f:PingPongFullCoroutineSteps} shows the steps for symmetric control-flow are creating, executing, and terminating the cycle.
    999982Constructing 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.
    1000983(This issue occurs for any cyclic data structure.)
     984The example creates the generators, @ping@/@pong@, and then assigns the partners that form the cycle.
    1001985% (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.)
    1002 Once 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).
     986Once the cycle is formed, the program main resumes one of the generators, @ping@, and the generators can then traverse an arbitrary cycle using @resume@ to activate partner generator(s).
    1003987Terminating 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).
    1004988Note, the creator and starter may be different, \eg if the creator calls another function that starts the cycle.
     
    1006990Also, 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.
    1007991Destructor cost occurs when the generator instance is deallocated by the creator.
    1008 
    1009 \begin{figure}
    1010 \centering
    1011 \input{FullCoroutinePhases.pstex_t}
    1012 \vspace*{-10pt}
    1013 \caption{Symmetric coroutine steps: Ping / Pong}
    1014 \label{f:PingPongFullCoroutineSteps}
    1015 \end{figure}
    1016992
    1017993\begin{figure}
     
    10771053\end{figure}
    10781054
     1055\begin{figure}
     1056\centering
     1057\input{FullCoroutinePhases.pstex_t}
     1058\vspace*{-10pt}
     1059\caption{Symmetric coroutine steps: Ping / Pong}
     1060\label{f:PingPongFullCoroutineSteps}
     1061\end{figure}
     1062
    10791063Figure~\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.
    10801064Before 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.
     
    10821066While the semantics of call forward is a tail-call optimization, which compilers perform, the generator state is different on each call rather a common state for a tail-recursive function (i.e., the parameter to the function never changes during the forward calls.
    10831067However, this assembler code depends on what entry code is generated, specifically if there are local variables and the level of optimization.
    1084 Hence, 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@.
    1085 For 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.
     1068Hence, internal compiler support is necessary for any forward call (or backwards return), \eg LLVM has various coroutine support~\cite{CoroutineTS}, and \CFA can leverage this support should it eventually fork @clang@.
     1069For this reason, \CFA does not support general symmetric generators at this time, but, it is possible to hand generate any symmetric generators (as in Figure~\ref{f:CPingPongSim}) for proof of concept and performance testing.
    10861070
    10871071Finally, 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.
     
    11001084\label{s:Coroutine}
    11011085
    1102 Stackful 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.
    1103 Note, simulating coroutines with stacks of generators, \eg Python with @yield from@ cannot handle symmetric control-flow.
    1104 Furthermore, all stack components must be of generators, so it is impossible to call a library function passing a generator that yields.
    1105 Creating a generator copy of the library function maybe impossible because the library function is opaque.
    1106 
    1107 A \CFA coroutine is specified by replacing @generator@ with @coroutine@ for the type.
     1086Stackful coroutines (Table~\ref{t:ExecutionPropertyComposition} case 5) extend generator semantics, \ie there is an implicit closure and @suspend@ may appear in a helper function called from the coroutine main.
     1087A coroutine is specified by replacing @generator@ with @coroutine@ for the type.
    11081088Coroutine 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.
    11091089A series of different kinds of coroutines and their implementations demonstrate how coroutines extend generators.
    11101090
    11111091First, 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.
    1112 Now the coroutine type only contains communication variables between interface functions and the coroutine main.
    11131092\begin{center}
    11141093\begin{tabular}{@{}l|l|l|l@{}}
     
    11471126\begin{cfa}
    11481127int Crc() {
    1149         `suspend;`  short int crc = byte << 8;
    1150         `suspend;`  status = (crc | byte) == sum ? MSG : ECRC;
     1128        `suspend;`
     1129        short int crc = byte << 8;
     1130        `suspend;`
     1131        status = (crc | byte) == sum ? MSG : ECRC;
    11511132        return crc;
    11521133}
    11531134\end{cfa}
    1154 A call to this function is placed at the end of the device driver's coroutine-main.
     1135A call to this function is placed at the end of the driver's coroutine-main.
    11551136For complex finite-state machines, refactoring is part of normal program abstraction, especially when code is used in multiple places.
    11561137Again, this complexity is usually associated with execution state rather than data state.
     
    11581139\begin{comment}
    11591140Figure~\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@.
    1160 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.
     1141Like the structure in Figure~\ref{f:ExternalState}, the coroutine type allows multiple instances, where instances of this type are passed to the (overloaded) coroutine main.
    11611142The 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@.
    11621143The interface function @restart@, takes a Fibonacci instance and context switches to it using @resume@;
     
    13921373
    13931374Figure~\ref{f:ProdCons} shows the ping-pong example in Figure~\ref{f:CFAPingPongGen} extended into a producer/consumer symmetric-coroutine performing bidirectional communication.
    1394 This example is illustrative because both producer and consumer have two interface functions with @resume@s that suspend execution in these interface functions.
     1375This example is illustrative because both producer/consumer have two interface functions with @resume@s that suspend execution in these interface (helper) functions.
    13951376The 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.
    13961377The 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.
     
    14201401The question now is where does control continue?
    14211402
    1422 The 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.
     1403The na\"{i}ve semantics for coroutine-cycle termination is to context switch to the last resumer, like executing a @suspend@/@return@ in a generator.
    14231404However, for coroutines, the last resumer is \emph{not} implicitly below the current stack frame, as for generators, because each coroutine's stack is independent.
    14241405Unfortunately, it is impossible to determine statically if a coroutine is in a cycle and unrealistic to check dynamically (graph-cycle problem).
     
    14291410For asymmetric coroutines, it is common for the first resumer (starter) coroutine to be the only resumer;
    14301411for symmetric coroutines, it is common for the cycle creator to persist for the lifetime of the cycle.
    1431 For 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.
     1412For other scenarios, it is always possible to devise a solution with additional programming effort, such as forcing the cycle forward (backward) to a safe point before starting termination.
    14321413
    14331414Note, the producer/consumer example does not illustrate the full power of the starter semantics because @cons@ always ends first.
    14341415Assume generator @PingPong@ in Figure~\ref{f:PingPongSymmetricGenerator} is converted to a coroutine.
    14351416Unlike generators, coroutines have a starter structure with multiple levels, where the program main starts @ping@ and @ping@ starts @pong@.
    1436 By adjusting $N$ for either @ping@ or @pong@, it is possible to have either finish first.
     1417By adjusting $N$ for either @ping@/@pong@, it is possible to have either finish first.
    14371418If @pong@ ends first, it resumes its starter @ping@ in its coroutine main, then @ping@ ends and resumes its starter the program main on return;
    14381419if @ping@ ends first, it resumes its starter the program main on return.
     
    14441425\subsection{Generator / Coroutine Implementation}
    14451426
    1446 A 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.
     1427A significant implementation challenge for generators/coroutines (and threads in Section~\ref{s:threads}) is adding extra fields to the custom types and related functions, \eg inserting code after/before the coroutine constructor/destructor and @main@ to create/initialize/de-initialize/destroy any extra fields, \eg stack.
    14471428There are several solutions to these problem, which follow from the object-oriented flavour of adopting custom types.
    14481429
     
    14521433\end{cfa}
    14531434% 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.
    1454 The 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.
     1435The problem is that some special properties are not handled by existing language semantics, \eg the execution of constructors/destructors is in the wrong order to implicitly start threads because the thread must start \emph{after} all constructors as it relies on a completely initialized object, but the inherited constructor runs \emph{before} the derived.
    14551436Alternatives, such as explicitly starting threads as in Java, are repetitive and forgetting to call start is a common source of errors.
    14561437An alternative is composition:
     
    14801461forall( `dtype` T | is_coroutine(T) ) void $suspend$( T & ), resume( T & );
    14811462\end{cfa}
    1482 Note, copying generators, coroutines, and threads is undefined because muliple objects cannot execute on a shared stack and stack copying does not work in unmanaged languages (no garbage collection), like C, because the stack may contain pointers to objects within it that require updating for the copy.
    1483 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 or pointer.
    1484 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 read the coroutine descriptor from its handle.
    1485 The @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.
     1463Note, copying generators/coroutines/threads is undefined because muliple objects cannot execute on a shared stack and stack copying does not work in unmanaged languages (no garbage collection), like C, because the stack may contain pointers to objects within it that require updating for the copy.
     1464The \CFA @dtype@ property provides no \emph{implicit} copying operations and the @is_coroutine@ trait provides no \emph{explicit} copying operations, so all coroutines must be passed by reference (pointer).
     1465The function definitions ensure there is a statically typed @main@ function that is the starting point (first stack frame) of a coroutine, and a mechanism to get (read) the coroutine descriptor from its handle.
     1466The @main@ function has no return value or additional parameters because the coroutine type allows an arbitrary number of interface functions with corresponding arbitrary typed input/output values versus fixed ones.
    14861467The 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@.
    14871468
     
    15251506
    15261507Figure~\ref{f:CoroutineMemoryLayout} shows different memory-layout options for a coroutine (where a thread is similar).
    1527 The coroutine handle is the @coroutine@ instance containing programmer specified type global and communication variables across interface functions.
     1508The coroutine handle is the @coroutine@ instance containing programmer specified type global/communication variables across interface functions.
    15281509The coroutine descriptor contains all implicit declarations needed by the runtime, \eg @suspend@/@resume@, and can be part of the coroutine handle or separate.
    15291510The coroutine stack can appear in a number of locations and be fixed or variable sized.
    1530 Hence, the coroutine's stack could be a variable-length structure (VLS)
    1531 % \footnote{
    1532 % We are examining VLSs, where fields can be variable-sized structures or arrays.
    1533 % Once allocated, a VLS is fixed sized.}
     1511Hence, the coroutine's stack could be a variable-length structure (VLS)\footnote{
     1512We are examining VLSs, where fields can be variable-sized structures or arrays.
     1513Once allocated, a VLS is fixed sized.}
    15341514on the allocating stack, provided the allocating stack is large enough.
    1535 For a VLS stack allocation and deallocation is an inexpensive adjustment of the stack pointer, modulo any stack constructor costs to initial frame setup.
    1536 For 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.
    1537 It 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.
    1538 Currently, \CFA supports stack and heap allocated descriptors but only fixed-sized heap allocated stacks.
     1515For a VLS stack allocation/deallocation is an inexpensive adjustment of the stack pointer, modulo any stack constructor costs (\eg initial frame setup).
     1516For stack allocation in the heap, allocation/deallocation is an expensive allocation, where the heap can be a shared resource, modulo any stack constructor costs.
     1517It is also possible to use a split (segmented) stack calling convention, available with gcc and clang, allowing a variable-sized stack via a set of connected blocks in the heap.
     1518Currently, \CFA supports stack/heap allocated descriptors but only fixed-sized heap allocated stacks.
    15391519In \CFA debug-mode, the fixed-sized stack is terminated with a write-only page, which catches most stack overflows.
    15401520Experience teaching concurrency with \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue for students.
     
    15591539The 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}.
    15601540Therefore, a minimal concurrency system requires coroutines \emph{in conjunction with a nondeterministic scheduler}.
    1561 The 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.
     1541The resulting execution system now follows a cooperative threading-model~\cite{Adya02,libdill} because context-switching points to the scheduler (blocking) are known, but the next unblocking point is unknown due to the scheduler.
    15621542Adding \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.
    15631543Uncertainty gives the illusion of parallelism on a single processor and provides a mechanism to access and increase performance on multiple processors.
    1564 The reason is that the scheduler and runtime have complete knowledge about resources and how to best utilized them.
     1544The reason is that the scheduler/runtime have complete knowledge about resources and how to best utilized them.
    15651545However, 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;
    15661546otherwise, it is impossible to write meaningful concurrent programs.
     
    15761556\label{s:threads}
    15771557
    1578 Threading (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@.
     1558Threading (Table~\ref{t:ExecutionPropertyComposition} case 11) needs the ability to start a thread and wait for its completion.
     1559A common API for this ability is @fork@ and @join@.
    15791560\vspace{4pt}
    15801561\par\noindent
     
    16081589\vspace{1pt}
    16091590\par\noindent
    1610 \CFA has a simpler approach using a custom @thread@ type and leveraging declaration semantics, allocation and deallocation, where threads implicitly @fork@ after construction and @join@ before destruction.
     1591\CFA has a simpler approach using a custom @thread@ type and leveraging declaration semantics (allocation/deallocation), where threads implicitly @fork@ after construction and @join@ before destruction.
    16111592\begin{cfa}
    16121593thread MyThread {};
     
    16171598} $\C{// deallocate stack-based threads, implicit joins before destruction}$
    16181599\end{cfa}
    1619 This semantic ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic termination synchronization.
    1620 For block allocation to arbitrary depth, including recursion, threads are created and destroyed in a lattice structure (tree with top and bottom).
     1600This semantic ensures a thread is started and stopped exactly once, eliminating some programming error, and scales to multiple threads for basic (termination) synchronization.
     1601For block allocation to arbitrary depth, including recursion, threads are created/destroyed in a lattice structure (tree with top and bottom).
    16211602Arbitrary topologies are possible using dynamic allocation, allowing threads to outlive their declaration scope, identical to normal dynamic allocation.
    16221603\begin{cfa}
     
    16891670\end{tabular}
    16901671\end{cquote}
    1691 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 or pointer.
    1692 Similarly, 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.
     1672Like coroutines, the @dtype@ property prevents \emph{implicit} copy operations and the @is_thread@ trait provides no \emph{explicit} copy operations, so threads must be passed by reference (pointer).
     1673Similarly, the function definitions ensure there is a statically typed @main@ function that is the thread starting point (first stack frame), a mechanism to get (read) the thread descriptor from its handle, and a special destructor to prevent deallocation while the thread is executing.
    16931674(The qualifier @mutex@ for the destructor parameter is discussed in Section~\ref{s:Monitor}.)
    16941675The 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;
    16951676whereas, a thread is scheduling for execution in @main@ immediately after its constructor is run.
    1696 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 and output values.
     1677No return value or additional parameters are necessary for this function because the @thread@ type allows an arbitrary number of interface functions with corresponding arbitrary typed input/output values.
    16971678
    16981679
     
    17021683Unrestricted nondeterminism is meaningless as there is no way to know when a result is completed and safe to access.
    17031684To 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}.
    1704 The shared data protected by mutual exlusion is called a \newterm{critical section}~\cite{Dijkstra65}, and the protection can be simple, only 1 thread, or complex, only N kinds of threads, \eg group~\cite{Joung00} or readers/writer~\cite{Courtois71} problems.
    1705 Without 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.
     1685The shared data protected by mutual exlusion is called a \newterm{critical section}~\cite{Dijkstra65}, and the protection can be simple (only 1 thread) or complex (only N kinds of threads, \eg group~\cite{Joung00} or readers/writer~\cite{Courtois71}).
     1686Without synchronization control in a critical section, an arriving thread can barge ahead of preexisting waiter threads resulting in short/long-term starvation, staleness/freshness problems, and/or incorrect transfer of data.
    17061687Preventing or detecting barging is a challenge with low-level locks, but made easier through higher-level constructs.
    17071688This challenge is often split into two different approaches: barging \emph{avoidance} and \emph{prevention}.
     
    17151696Some 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).
    17161697However, these approaches introduce a new communication mechanism for concurrency different from the standard communication using function call/return.
    1717 Hence, a programmer must learn and manipulate two sets of design and programming patterns.
     1698Hence, a programmer must learn and manipulate two sets of design/programming patterns.
    17181699While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account.
    1719 In contrast, approaches based on shared-state models more closely resemble the standard call and return programming model, resulting in a single programming paradigm.
     1700In contrast, approaches based on shared-state models more closely resemble the standard call/return programming model, resulting in a single programming paradigm.
    17201701Finally, a newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}.
    17211702While 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.
     
    17301711For these reasons, \CFA selected monitors as the core high-level concurrency construct, upon which higher-level approaches can be easily constructed.
    17311712
    1732 Figure~\ref{f:AtomicCounter} compares a \CFA and Java monitor implementing an atomic counter.
    1733 (Like other concurrent programming languages, \CFA and Java have performant specializations for the basic types using atomic instructions.)
    1734 A \newterm{monitor} is a set of functions that ensure mutual exclusion when accessing shared state.
    1735 (Note, in \CFA, @monitor@ is short-hand for @mutex struct@.)
    1736 More 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).
    1737 Restricting acquire and release points eases programming, comprehension, and maintenance, at a slight cost in flexibility and efficiency.
    1738 As for other special types, \CFA has a custom @monitor@ type.
    1739 
    1740 \begin{figure}
    1741 \centering
    1742 
    1743 \begin{lrbox}{\myboxA}
    1744 \begin{cfa}[aboveskip=0pt,belowskip=0pt]
    1745 `monitor` Aint { // atomic integer counter
    1746         int cnt;
    1747 };
    1748 int ++?( Aint & `mutex` this ) with(this) { return ++cnt; }
    1749 int ?=?( Aint & `mutex` lhs, int rhs ) with(lhs) { cnt = rhs; }
    1750 int ?=?(int & lhs, Aint & rhs) with(rhs) { lhs = cnt; }
    1751 
     1713Specifically, a \textbf{monitor} is a set of functions that ensure mutual exclusion when accessing shared state.
     1714More precisely, a monitor is a programming technique that implicitly binds mutual exclusion to static function scope by call/return, as opposed to locks, where mutual-exclusion is defined by acquire/release calls, independent of lexical context (analogous to block and heap storage allocation).
     1715Restricting acquire/release points eases programming, comprehension, and maintenance, at a slight cost in flexibility and efficiency.
     1716\CFA uses a custom @monitor@ type and leverages declaration semantics (deallocation) to protect active or waiting threads in a monitor.
     1717
     1718The following is a \CFA monitor implementation of an atomic counter.
     1719\begin{cfa}
     1720`monitor` Aint { int cnt; }; $\C[4.25in]{// atomic integer counter}$
     1721int ++?( Aint & `mutex` this ) with( this ) { return ++cnt; } $\C{// increment}$
     1722int ?=?( Aint & `mutex` lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions with int, mutex optional}\CRT$
     1723int ?=?( int & lhs, Aint & `mutex` rhs ) with( rhs ) { lhs = cnt; }
     1724\end{cfa}
     1725The operators use the parameter-only declaration type-qualifier @mutex@ to mark which parameters require locking during function execution to protect from race conditions.
     1726The assignment operators provide bidirectional conversion between an atomic and normal integer without accessing field @cnt@.
     1727(These operations only need @mutex@, if reading/writing the implementation type is not atomic.)
     1728The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics.
     1729\begin{cfa}
    17521730int i = 0, j = 0, k = 5;
    1753 Aint x = { 0 }, y = { 0 }, z = { 5 }; // no mutex
    1754 ++x; ++y; ++z;     // mutex
    1755 x = 2; y = i; z = k;  // mutex
    1756 i = x; j = y; k = z;  // no mutex
    1757 \end{cfa}
    1758 \end{lrbox}
    1759 
    1760 \begin{lrbox}{\myboxB}
    1761 \begin{java}[aboveskip=0pt,belowskip=0pt]
    1762 class Aint {
    1763     private int cnt;
    1764     public Aint( int init ) { cnt = init; }
    1765     `synchronized` public int inc() { return ++cnt; }
    1766     `synchronized` public void set( int rhs ) {cnt=rhs;}
    1767     public int get() { return cnt; }
    1768 }
    1769 int i = 0, j = 0, k = 5;
    1770 Aint x=new Aint(0), y=new Aint(0), z=new Aint(5);
    1771 x.inc(); y.inc(); z.inc();
    1772 x.set( 2 ); y.set( i ); z.set( k );
    1773 i = x.get(); j = y.get(); k = z.get();
    1774 \end{java}
    1775 \end{lrbox}
    1776 
    1777 \subfloat[\CFA]{\label{f:AtomicCounterCFA}\usebox\myboxA}
    1778 \hspace{3pt}
    1779 \vrule
    1780 \hspace{3pt}
    1781 \subfloat[Java]{\label{f:AtomicCounterJava}\usebox\myboxB}
    1782 \caption{Atomic counter}
    1783 \label{f:AtomicCounter}
    1784 \end{figure}
    1785 
    1786 Like Java, \CFA monitors have \newterm{multi-acquire} semantics so the thread in the monitor may acquire it multiple times without deadlock, allowing recursion and calling other interface functions.
    1787 % \begin{cfa}
    1788 % monitor M { ... } m;
    1789 % void foo( M & mutex m ) { ... } $\C{// acquire mutual exclusion}$
    1790 % void bar( M & mutex m ) { $\C{// acquire mutual exclusion}$
    1791 %       ... `bar( m );` ... `foo( m );` ... $\C{// reacquire mutual exclusion}$
    1792 % }
    1793 % \end{cfa}
    1794 \CFA monitors also ensure the monitor lock is released regardless of how an acquiring function ends, normal or exceptional, and returning a shared variable is safe via copying before the lock is released.
     1731Aint x = { 0 }, y = { 0 }, z = { 5 }; $\C{// no mutex required}$
     1732++x; ++y; ++z; $\C{// safe increment by multiple threads}$
     1733x = 2; y = i; z = k; $\C{// conversions}$
     1734i = x; j = y; k = z;
     1735\end{cfa}
     1736Note, like other concurrent programming languages, \CFA has specializations for the basic types using atomic instructions for performance and a general trait similar to the \CC template @std::atomic@.
     1737
     1738\CFA monitors have \newterm{multi-acquire} semantics so the thread in the monitor may acquire it multiple times without deadlock, allowing recursion and calling other interface functions.
     1739\newpage
     1740\begin{cfa}
     1741monitor M { ... } m;
     1742void foo( M & mutex m ) { ... } $\C{// acquire mutual exclusion}$
     1743void bar( M & mutex m ) { $\C{// acquire mutual exclusion}$
     1744        ... `bar( m );` ... `foo( m );` ... $\C{// reacquire mutual exclusion}$
     1745}
     1746\end{cfa}
     1747\CFA monitors also ensure the monitor lock is released regardless of how an acquiring function ends (normal or exceptional), and returning a shared variable is safe via copying before the lock is released.
    17951748Similar 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.
    1796 However, 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;
     1749Furthermore, RAII mechanisms cannot handle complex synchronization within a monitor, where the monitor lock may not be released on function exit because it is passed to an unblocking thread;
    17971750RAII is purely a mutual-exclusion mechanism (see Section~\ref{s:Scheduling}).
    1798 
    1799 Both 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.
    1800 Non-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.
    1801 Monitor objects can be passed through multiple helper functions without acquiring mutual exclusion, until a designated function associated with the object is called.
    1802 \CFA designated functions are marked by an explicitly parameter-only pointer/reference qualifier @mutex@ (discussed further in Section\ref{s:MutexAcquisition}).
    1803 Whereas, Java designated members are marked with \lstinline[language=java]|synchronized| that applies to the implicit reference parameter @this@.
    1804 In the example, the increment and setter operations need mutual exclusion while the read-only getter operation can be non-mutex if reading the implementation is atomic.
    18051751
    18061752
     
    18251771\end{tabular}
    18261772\end{cquote}
    1827 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 or pointer.
    1828 Similarly, the function definitions ensures there is a mechanism to read the monitor descriptor from its handle, and a special destructor to prevent deallocation if a thread is using the shared data.
     1773The @dtype@ property prevents \emph{implicit} copy operations and the @is_monitor@ trait provides no \emph{explicit} copy operations, so monitors must be passed by reference (pointer).
     1774Similarly, the function definitions ensures there is a mechanism to get (read) the monitor descriptor from its handle, and a special destructor to prevent deallocation if a thread using the shared data.
    18291775The custom monitor type also inserts any locks needed to implement the mutual exclusion semantics.
    1830 \CFA relies heavily on traits as an abstraction mechanism, so the @mutex@ qualifier prevents coincidentally matching of a monitor trait with a type that is not a monitor, similar to coincidental inheritance where a shape and playing card can both be drawable.
    18311776
    18321777
     
    18341779\label{s:MutexAcquisition}
    18351780
    1836 For object-oriented programming languages, the mutex property applies to one object, the implicit pointer/reference to the monitor type.
    1837 Because \CFA uses a pointer qualifier, other possibilities exist, \eg:
    1838 \begin{cfa}
    1839 monitor M { ... };
     1781While the monitor lock provides mutual exclusion for shared data, there are implementation options for when and where the locking/unlocking occurs.
     1782(Much of this discussion also applies to basic locks.)
     1783For example, a monitor may be passed through multiple helper functions before it is necessary to acquire the monitor's mutual exclusion.
     1784
     1785\CFA requires programmers to identify the kind of parameter with the @mutex@ keyword and uses no keyword to mean \lstinline[morekeywords=nomutex]@nomutex@, because @mutex@ parameters are rare and no keyword is the \emph{normal} parameter semantics.
     1786Hence, @mutex@ parameters are documentation, at the function and its prototype, to both programmer and compiler, without other redundant keywords.
     1787Furthermore, \CFA relies heavily on traits as an abstraction mechanism, so the @mutex@ qualifier prevents coincidentally matching of a monitor trait with a type that is not a monitor, similar to coincidental inheritance where a shape and playing card can both be drawable.
     1788
     1789The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@.
     1790The following has monitor parameter types that are composed of multiple objects.
     1791\begin{cfa}
     1792monitor M { ... }
    18401793int f1( M & mutex m ); $\C{// single parameter object}$
    18411794int f2( M * mutex m ); $\C{// single or multiple parameter object}$
     
    18431796int f4( stack( M * ) & mutex m ); $\C{// multiple parameters object}$
    18441797\end{cfa}
    1845 Function @f1@ has a single object parameter, while functions @f2@ to @f4@ can be a single or multi-element parameter with statically unknown size.
    1846 Because of the statically unknown size, \CFA only supports a single reference @mutex@ parameter, @f1@.
    1847 
    1848 The \CFA @mutex@ qualifier does allow the ability to support multi-monitor functions,\footnote{
     1798Function @f1@ has a single parameter object, while @f2@'s indirection could be a single or multi-element array, where static array size is often unknown in C.
     1799Function @f3@ has a multiple object matrix, and @f4@ a multiple object data structure.
     1800While shown shortly, multiple object acquisition is possible, but the number of objects must be statically known.
     1801Therefore, \CFA only acquires one monitor per parameter with exactly one level of indirection, and exclude pointer types to unknown sized arrays.
     1802
     1803For object-oriented monitors, \eg Java, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@.
     1804\CFA has no receiver, and hence, the explicit @mutex@ qualifier is used to specify which objects acquire mutual exclusion.
     1805A positive consequence of this design decision is the ability to support multi-monitor functions,\footnote{
    18491806While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.}
    1850 where the number of acquisitions is statically known, called \newterm{bulk acquire}.
     1807called \newterm{bulk acquire}.
    18511808\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.
    18521809Figure~\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.
     
    19761933% 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.
    19771934% 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.
    1978 This section discusses scheduling for waiting threads eligible for monitor entry~\cite{Buhr95b}, \ie which user thread gets the shared resource next. (See Section~\ref{s:RuntimeStructureCluster} for scheduling kernel threads on virtual processors.)
     1935This section discusses scheduling for waiting threads eligible for monitor entry, \ie which user thread gets the shared resource next. (See Section~\ref{s:RuntimeStructureCluster} for scheduling kernel threads on virtual processors.)
    19791936While 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.
    19801937Leaving the monitor and retrying (busy waiting) is impractical for high-level programming.
     
    19821939Monitors 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.
    19831940Synchronization is generally achieved with internal~\cite{Hoare74} or external~\cite[\S~2.9.2]{uC++} scheduling.
    1984 \newterm{Internal} largely schedules threads located \emph{inside} the monitor and is accomplished using condition variables with signal and wait.
    1985 \newterm{External} largely schedules threads located \emph{outside} the monitor and is accomplished with the @waitfor@ statement.
    1986 Note, 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.
    1987 For complex scheduling, the approaches can be combined, so there are threads waiting inside and outside.
    1988 
    1989 \CFA monitors do not allow calling threads to barge ahead of signalled threads via barging prevention, which simplifies synchronization among threads in the monitor and increases correctness.
     1941\newterm{Internal} (largely) schedules threads located \emph{inside} the monitor and is accomplished using condition variables with signal and wait.
     1942\newterm{External} (largely) schedules threads located \emph{outside} the monitor and is accomplished with the @waitfor@ statement.
     1943Note, internal scheduling has a small amount of external scheduling and vice versus, so the naming denotes where the majority of the block threads reside (inside or outside) for scheduling.
     1944For complex scheduling, the approaches can be combined, so there can be an equal number of threads waiting inside and outside.
     1945
     1946\CFA monitors do not allow calling threads to barge ahead of signalled threads (via barging prevention), which simplifies synchronization among threads in the monitor and increases correctness.
    19901947A 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.
    19911948Preventing barging comes directly from Hoare's semantics in the seminal paper on monitors~\cite[p.~550]{Hoare74}.
     
    19961953Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implicit self barging.
    19971954
    1998 Monitor mutual-exclusion means signalling cannot have the signaller and signalled thread in the monitor simultaneously, so only the signaller or signallee can proceed and the other waits on an implicit urgent list~\cite[p.~551]{Hoare74}.
    1999 Figure~\ref{f:MonitorScheduling} shows internal and external scheduling for the bounded-buffer examples in Figure~\ref{f:GenericBoundedBuffer}.
    2000 For 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).
     1955Monitor mutual-exclusion means signalling cannot have the signaller and signalled thread in the monitor simultaneously, so only the signaller or signallee can proceed.
     1956Figure~\ref{f:MonitorScheduling} shows internal/external scheduling for the bounded-buffer examples in Figure~\ref{f:GenericBoundedBuffer}.
     1957For internal scheduling in Figure~\ref{f:BBInt}, the @signal@ moves the signallee (front thread of the specified condition queue) to urgent and the signaller continues (solid line).
    20011958Multiple signals move multiple signallees to urgent until the condition queue is empty.
    2002 When the signaller exits or waits, a thread is implicitly unblocked from urgent, if available, before unblocking a calling thread to prevent barging.
     1959When the signaller exits or waits, a thread is implicitly unblocked from urgent (if available) before unblocking a calling thread to prevent barging.
    20031960(Java conceptually moves the signalled thread to the calling queue, and hence, allows barging.)
    2004 Signal is used when the signaller is providing the cooperation needed by the signallee, \eg creating an empty slot in a buffer for a producer, and the signaller immediately exits the monitor to run concurrently consuming the buffer element, and passes control of the monitor to the signalled thread, which can immediately take advantage of the state change.
     1961Signal is used when the signaller is providing the cooperation needed by the signallee (\eg creating an empty slot in a buffer for a producer) and the signaller immediately exits the monitor to run concurrently (consume the buffer element) and passes control of the monitor to the signalled thread, which can immediately take advantage of the state change.
    20051962Specifically, the @wait@ function atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the function's parameter list.
    20061963Signalling is unconditional because signalling an empty condition queue does nothing.
    20071964It 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.
    2008 In \CFA, a condition queue can be created and stored independently.
     1965In \CFA, a condition queue can be created/stored independently.
    20091966
    20101967\begin{figure}
     
    20922049\end{figure}
    20932050
    2094 The @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}.
    2095 Signal 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.
     2051The @signal_block@ provides the opposite unblocking order, where the signaller is moved to urgent and the signallee continues and a thread is implicitly unblocked from urgent when the signallee exits or waits (dashed line).
     2052Signal block is used when the signallee is providing the cooperation needed by the signaller (\eg if the buffer is removed and a producer hands off an item to a consumer, as in Figure~\ref{f:DatingSignalBlock}) so the signaller must wait until the signallee unblocks, provides the cooperation, exits the monitor to run concurrently, and passes control of the monitor to the signaller, which can immediately take advantage of the state change.
    20962053Using @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.
    20972054
    2098 For 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++}.
     2055External scheduling in Figure~\ref{f:BBExt} simplifies internal scheduling by eliminating condition queues and @signal@/@wait@ (cases where it cannot are discussed shortly), and has existed in the programming language Ada for almost 40 years with variants in other languages~\cite{SR,ConcurrentC++,uC++}.
    20992056While prior languages use external scheduling solely for thread interaction, \CFA generalizes it to both monitors and threads.
    21002057External scheduling allows waiting for events from other threads while restricting unrelated events, that would otherwise have to wait on condition queues in the monitor.
     
    21052062Now 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.
    21062063For 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.
    2107 Hence, this mechanism is done in terms of control flow, next call, versus in terms of data, channels, as in Go and Rust @select@.
     2064Hence, this mechanism is done in terms of control flow, next call, versus in terms of data, channels, as in Go/Rust @select@.
    21082065While both mechanisms have strengths and weaknesses, \CFA uses the control-flow mechanism to be consistent with other language features.
    21092066
    2110 Figure~\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.
     2067Figure~\ref{f:ReadersWriterLock} shows internal/external scheduling for a readers/writer lock with no barging and threads are serviced in FIFO order to eliminate staleness/freshness among the reader/writer threads.
    21112068For 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.
    21122069To 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@.
     
    22722229For 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.
    22732230For 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.
    2274 Note, 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.
     2231
     2232The dating service is an important example of a monitor that cannot be written using external scheduling.
     2233First, because scheduling requires knowledge of calling parameters to make matching decisions, and parameters of calling threads are unavailable within the monitor.
     2234For example, a girl thread within the monitor cannot examine the @ccode@ of boy threads waiting on the calling queue to determine if there is a matching partner.
     2235Second, because a scheduling decision may be delayed when there is no immediate match, which requires a condition queue for waiting, and condition queues imply internal scheduling.
     2236For example, if a girl thread could determine there is no calling boy with the same @ccode@, it must wait until a matching boy arrives.
     2237Finally, barging corrupts the dating service during an exchange because a barger may also match and change the phone numbers, invalidating the previous exchange phone number.
    22752238This situation shows rechecking the waiting condition and waiting again (signals-as-hints) fails, requiring significant restructured to account for barging.
    22762239
    2277 Given external and internal scheduling, what guidelines can a programmer use to select between them?
    2278 In 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.
    2279 Therefore, there are no condition variables, and hence, no wait and signal, which reduces coding complexity and synchronization errors.
    2280 If external scheduling is simpler than internal, why not use it all the time?
    2281 Unfortunately, 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.
    2282 For example, the dating service cannot be written using external scheduling.
    2283 First, scheduling requires knowledge of calling parameters to make matching decisions and parameters of calling threads are unavailable within the monitor.
    2284 Specifically, a thread within the monitor cannot examine the @ccode@ of threads waiting on the calling queue to determine if there is a matching partner.
    2285 (Similarly, if the bounded buffer or readers/writer are restructured with a single interface function with a parameter denoting producer/consumer or reader/write, they cannot be solved with external scheduling.)
    2286 Second, 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.
    2287 Specifically, 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.
    2288 For complex synchronization, both external and internal scheduling can be used to take advantage of best of properties of each.
    2289 
    2290 Finally, both internal and external scheduling extend to multiple monitors in a natural way.
     2240Both internal and external scheduling extend to multiple monitors in a natural way.
    22912241\begin{cquote}
    22922242\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
     
    23242274Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex parameters, \ie @waitfor( rtn : m1, m2 )@.
    23252275To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn : m1 )@.
    2326 @waitfor@ does statically verify the monitor types passed are the same as the acquired mutex-parameters of the given function or function pointer, hence the prototype must be accessible.
     2276@waitfor@ does statically verify the monitor types passed are the same as the acquired mutex-parameters of the given function or function pointer, hence the function (pointer) prototype must be accessible.
    23272277% When an overloaded function appears in an @waitfor@ statement, calls to any function with that name are accepted.
    2328 % The rationale is that functions with the same name should perform a similar actions, and therefore, all should be eligible to accept a call.
     2278% The rationale is that members with the same name should perform a similar function, and therefore, all should be eligible to accept a call.
    23292279Overloaded functions can be disambiguated using a cast
    23302280\begin{cfa}
     
    23352285
    23362286The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock (see Section~\ref{s:MutexAcquisition}).
     2287\newpage
    23372288\begin{cfa}
    23382289void foo( M & mutex m1, M & mutex m2 ) {
     
    23492300
    23502301Figure~\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.
    2351 For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding function(s) must exist.
     2302For a @waitfor@ clause to be executed, its @when@ must be true and an outstanding call to its corresponding member(s) must exist.
    23522303The \emph{conditional-expression} of a @when@ may call a function, but the function must not block or context switch.
    2353 If 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@.
    2354 If 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.
     2304If there are multiple acceptable mutex calls, selection occurs top-to-bottom (prioritized) among the @waitfor@ clauses, whereas some programming languages with similar mechanisms accept nondeterministically for this case, \eg Go \lstinline[morekeywords=select]@select@.
     2305If some accept guards are true and there are no outstanding calls to these members, the acceptor is blocked until a call to one of these members is made.
    23552306If there is a @timeout@ clause, it provides an upper bound on waiting.
    23562307If 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.
    23572308Hence, the terminating @else@ clause allows a conditional attempt to accept a call without blocking.
    23582309If both @timeout@ and @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered.
    2359 % There is also a traditional future wait queue (not shown) (\eg Microsoft @WaitForMultipleObjects@), to wait for a specified number of future elements in the queue.
     2310There is also a traditional future wait queue (not shown) (\eg Microsoft @WaitForMultipleObjects@), to wait for a specified number of future elements in the queue.
    23602311Finally, there is a shorthand for specifying multiple functions using the same set of monitors: @waitfor( f, g, h : m1, m2, m3 )@.
    23612312
     
    23642315\begin{cfa}
    23652316`when` ( $\emph{conditional-expression}$ )      $\C{// optional guard}$
    2366         waitfor( $\emph{mutex-function-name}$ ) $\emph{statement}$ $\C{// action after call}$
     2317        waitfor( $\emph{mutex-member-name}$ ) $\emph{statement}$ $\C{// action after call}$
    23672318`or` `when` ( $\emph{conditional-expression}$ ) $\C{// any number of functions}$
    2368         waitfor( $\emph{mutex-function-name}$ ) $\emph{statement}$
     2319        waitfor( $\emph{mutex-member-name}$ ) $\emph{statement}$
    23692320`or`    ...
    23702321`when` ( $\emph{conditional-expression}$ ) $\C{// optional guard}$
     
    23842335The left example only accepts @mem1@ if @C1@ is true or only @mem2@ if @C2@ is true.
    23852336The right example accepts either @mem1@ or @mem2@ if @C1@ and @C2@ are true.
    2386 Hence, the @waitfor@ has parallel semantics, accepting any true @when@ clause.
    23872337
    23882338An 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@.
     
    24822432If W1 waited first, the signaller must retain @m1@ amd @m2@ until completion of the outer mutex statement and then pass both to W1.
    24832433% Furthermore, there is an execution sequence where the signaller always finds waiter W2, and hence, waiter W1 starves.
    2484 To support this efficient semantics and prevent barging, the implementation maintains a list of monitors acquired for each blocked thread.
    2485 When a signaller exits or waits in a mutex function or statement, the front waiter on urgent is unblocked if all its monitors are released.
     2434To support this efficient semantics (and prevent barging), the implementation maintains a list of monitors acquired for each blocked thread.
     2435When a signaller exits or waits in a monitor function/statement, the front waiter on urgent is unblocked if all its monitors are released.
    24862436Implementing a fast subset check for the necessary released monitors is important and discussed in the following sections.
    24872437% 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.
     
    24922442
    24932443In 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}).
    2494 Knowing 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.
     2444Knowing all members at compilation (even separate compilation) allows uniquely numbered them so the accept-statement implementation can use a fast/compact bit mask with $O(1)$ compare.
    24952445
    24962446\begin{figure}
     
    25432493Hence, function pointers are used to identify the functions listed in the @waitfor@ statement, stored in a variable-sized array.
    25442494Then, the same implementation approach used for the urgent stack (see Section~\ref{s:Scheduling}) is used for the calling queue.
    2545 Each caller has a list of monitors acquired, and the @waitfor@ statement performs a short linear search matching functions in the @waitfor@ list with called functions, and then verifying the associated mutex locks can be transfers.
     2495Each caller has a list of monitors acquired, and the @waitfor@ statement performs a (short) linear search matching functions in the @waitfor@ list with called functions, and then verifying the associated mutex locks can be transfers.
    25462496
    25472497
     
    26212571
    26222572struct Msg { int i, j; };
    2623 mutex thread GoRtn { int i;  float f;  Msg m; };
     2573monitor thread GoRtn { int i;  float f;  Msg m; };
    26242574void mem1( GoRtn & mutex gortn, int i ) { gortn.i = i; }
    26252575void mem2( GoRtn & mutex gortn, float f ) { gortn.f = f; }
     
    26272577void ^?{}( GoRtn & mutex ) {}
    26282578
    2629 void main( GoRtn & mutex gortn ) with(gortn) { // thread starts
     2579void main( GoRtn & gortn ) with( gortn ) { // thread starts
    26302580
    26312581        for () {
     
    26942644
    26952645\begin{cfa}
    2696 mutex thread DatingService {
     2646monitor thread DatingService {
    26972647        condition Girls[CompCodes], Boys[CompCodes];
    26982648        int girlPhoneNo, boyPhoneNo, ccode;
     
    27582708% \label{f:pingpong}
    27592709% \end{figure}
    2760 Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start and possibly complete before the program main starts.
     2710Note, the ping/pong threads are globally declared, @pi@/@po@, and hence, start (and possibly complete) before the program main starts.
    27612711\end{comment}
    27622712
    27632713
    2764 \subsection{\texorpdfstring{\protect\lstinline@mutex@ Generators / Coroutines / Threads}{monitor Generators / Coroutines / Threads}}
    2765 
    2766 \CFA generators, coroutines, and threads can also be @mutex@ (Table~\ref{t:ExecutionPropertyComposition} cases 4, 6, 12) allowing safe \emph{direct communication} with threads, \ie the custom types can have mutex functions that are called by other threads.
     2714\subsection{\texorpdfstring{\protect\lstinline@monitor@ Generators / Coroutines / Threads}{monitor Generators / Coroutines / Threads}}
     2715
     2716\CFA generators, coroutines, and threads can also be monitors (Table~\ref{t:ExecutionPropertyComposition} cases 4, 6, 12) allowing safe \emph{direct communication} with threads, \ie the custom types can have mutex functions that are called by other threads.
    27672717All monitor features are available within these mutex functions.
    2768 For 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:
     2718For example, if the formatter generator (or coroutine equivalent) in Figure~\ref{f:CFAFormatGen} is extended with the monitor property and this interface function is used to communicate with the formatter:
    27692719\begin{cfa}
    27702720void fmt( Fmt & mutex fmt, char ch ) { fmt.ch = ch; resume( fmt ) }
     
    27742724Figure~\ref{f:DirectCommunicationComparison} shows a comparison of direct call-communication in \CFA versus indirect channel-communication in Go.
    27752725(Ada has a similar mechanism to \CFA direct communication.)
    2776 % The thread main function is by default @mutex@, so the @mutex@ qualifier for the thread parameter is optional.
    2777 % The reason is that the thread logically starts instantaneously in the thread main acquiring its mutual exclusion, so it starts before any calls to prepare for synchronizing these calls.
    2778 The \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.
     2726The program thread in \CFA @main@ uses the call/return paradigm to directly communicate with the @GoRtn main@, whereas Go switches to the channel paradigm to indirectly communicate with the goroutine.
    27792727Communication by multiple threads is safe for the @gortn@ thread via mutex calls in \CFA or channel assignment in Go.
    2780 The different between call and channel send occurs for buffered channels making the send asynchronous.
    2781 In \CFA, asynchronous call and multiple buffers is provided using an administrator and worker threads~\cite{Gentleman81} and/or futures (not discussed).
    27822728
    27832729Figure~\ref{f:DirectCommunicationDatingService} shows the dating-service problem in Figure~\ref{f:DatingServiceMonitor} extended from indirect monitor communication to direct thread communication.
    2784 When converting a monitor to a thread (server), the coding pattern is to move as much code as possible from the accepted functions into the thread main so it does an much work as possible.
     2730When converting a monitor to a thread (server), the coding pattern is to move as much code as possible from the accepted members into the thread main so it does an much work as possible.
    27852731Notice, the dating server is postponing requests for an unspecified time while continuing to accept new requests.
    2786 For 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.
     2732For complex servers (web-servers), there can be hundreds of lines of code in the thread main and safe interaction with clients can be complex.
    27872733
    27882734
     
    28222768
    28232769In 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.
    2824 If the jobs are dependent, \ie interact, there is an implicit dependency graph that ties them together.
     2770If the jobs are dependent, \ie interact, there is an implicit/explicit dependency graph that ties them together.
    28252771While removing direct concurrency, and hence the amount of context switching, thread pools significantly limit the interaction that can occur among jobs.
    28262772Indeed, jobs should not block because that also blocks the underlying thread, which effectively means the CPU utilization, and therefore throughput, suffers.
     
    29112857\label{s:RuntimeStructureProcessor}
    29122858
    2913 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.
     2859A virtual processor is implemented by a kernel thread (\eg UNIX process), which are scheduled for execution on a hardware processor by the underlying operating system.
    29142860Programs may use more virtual processors than hardware processors.
    29152861On a multiprocessor, kernel threads are distributed across the hardware processors resulting in virtual processors executing in parallel.
     
    29262872\label{s:Implementation}
    29272873
    2928 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.
     2874A primary implementation challenge is avoiding contention from dynamically allocating memory because of bulk acquire, \eg the internal-scheduling design is (almost) free of allocations.
    29292875All 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.
    29302876Furthermore, several bulk-acquire operations need a variable amount of memory.
     
    29722918
    29732919There are two versions of the \CFA runtime kernel: debug and non-debug.
    2974 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.
     2920The debugging version has many runtime checks and internal assertions, \eg stack (non-writable) guard page, and checks for stack overflow whenever context switches occur among coroutines and threads, which catches most stack overflows.
    29752921After a program is debugged, the non-debugging version can be used to significantly decrease space and increase performance.
    29762922
     
    29802926
    29812927To 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.
    2982 For comparison, the package must be multi-processor (M:N), which excludes libdil and /libmil~\cite{libdill} (M:1)), and use a shared-memory programming model, \eg not message passing.
     2928For comparison, the package must be multi-processor (M:N), which excludes libdill/libmil~\cite{libdill} (M:1)), and use a shared-memory programming model, \eg not message passing.
    29832929The 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.
    29842930
     
    29912937The total time is divided by @N@ to obtain the average time for a benchmark.
    29922938Each benchmark experiment is run 13 times and the average appears in the table.
    2993 All omitted tests for other languages are functionally identical to the \CFA tests and available online~\cite{CforallConcurrentBenchmarks}.
     2939All omitted tests for other languages are functionally identical to the \CFA tests and available online~\cite{CforallBenchMarks}.
    29942940% tar --exclude-ignore=exclude -cvhf benchmark.tar benchmark
    2995 % cp -p benchmark.tar /u/cforall/public_html/doc/concurrent_benchmark.tar
    2996 
    2997 \paragraph{Creation}
    2998 
    2999 Creation is measured by creating and deleting a specific kind of control-flow object.
    3000 Figure~\ref{f:creation} shows the code for \CFA with results in Table~\ref{t:creation}.
    3001 Note, 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.
     2941
     2942\paragraph{Context Switching}
     2943
     2944In procedural programming, the cost of a function call is important as modularization (refactoring) increases.
     2945(In many cases, a compiler inlines function calls to increase the size and number of basic blocks for optimizing.)
     2946Similarly, when modularization extends to coroutines/threads, the time for a context switch becomes a relevant factor.
     2947The coroutine test is from resumer to suspender and from suspender to resumer, which is two context switches.
     2948%For async-await systems, the test is scheduling and fulfilling @N@ empty promises, where all promises are allocated before versus interleaved with fulfillment to avoid garbage collection.
     2949For async-await systems, the test measures the cost of the @await@ expression entering the event engine by awaiting @N@ promises, where each created promise is resolved by an immediate event in the engine (using Node.js @setImmediate@).
     2950The thread test is using yield to enter and return from the runtime kernel, which is two context switches.
     2951The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling.
     2952Figure~\ref{f:ctx-switch} shows the \CFA code for a coroutine/thread with results in Table~\ref{t:ctx-switch}.
     2953
     2954% From: Gregor Richards <gregor.richards@uwaterloo.ca>
     2955% To: "Peter A. Buhr" <pabuhr@plg2.cs.uwaterloo.ca>
     2956% Date: Fri, 24 Jan 2020 13:49:18 -0500
     2957%
     2958% I can also verify that the previous version, which just tied a bunch of promises together, *does not* go back to the
     2959% event loop at all in the current version of Node. Presumably they're taking advantage of the fact that the ordering of
     2960% events is intentionally undefined to just jump right to the next 'then' in the chain, bypassing event queueing
     2961% entirely. That's perfectly correct behavior insofar as its difference from the specified behavior isn't observable, but
     2962% it isn't typical or representative of much anything useful, because most programs wouldn't have whole chains of eager
     2963% promises. Also, it's not representative of *anything* you can do with async/await, as there's no way to encode such an
     2964% eager chain that way.
    30022965
    30032966\begin{multicols}{2}
    30042967\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
    3005 \begin{cfa}
    3006 @coroutine@ MyCoroutine {};
    3007 void ?{}( MyCoroutine & this ) {
    3008 #ifdef EAGER
    3009         resume( this );
    3010 #endif
    3011 }
    3012 void main( MyCoroutine & ) {}
    3013 int main() {
    3014         BENCH( for ( N ) { @MyCoroutine c;@ } )
     2968\begin{cfa}[aboveskip=0pt,belowskip=0pt]
     2969@coroutine@ C {};
     2970void main( C & ) { for () { @suspend;@ } }
     2971int main() { // coroutine test
     2972        C c;
     2973        BENCH( for ( N ) { @resume( c );@ } )
    30152974        sout | result;
    30162975}
    3017 \end{cfa}
    3018 \captionof{figure}{\CFA creation benchmark}
    3019 \label{f:creation}
     2976int main() { // thread test
     2977        BENCH( for ( N ) { @yield();@ } )
     2978        sout | result;
     2979}
     2980\end{cfa}
     2981\captionof{figure}{\CFA context-switch benchmark}
     2982\label{f:ctx-switch}
    30202983
    30212984\columnbreak
    30222985
    30232986\vspace*{-16pt}
    3024 \captionof{table}{Creation comparison (nanoseconds)}
    3025 \label{t:creation}
    3026 
    3027 \begin{tabular}[t]{@{}r*{3}{D{.}{.}{5.2}}@{}}
    3028 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
    3029 \CFA generator                  & 0.6           & 0.6           & 0.0           \\
    3030 \CFA coroutine lazy             & 13.4          & 13.1          & 0.5           \\
    3031 \CFA coroutine eager    & 144.7         & 143.9         & 1.5           \\
    3032 \CFA thread                             & 466.4         & 468.0         & 11.3          \\
    3033 \uC coroutine                   & 155.6         & 155.7         & 1.7           \\
    3034 \uC thread                              & 523.4         & 523.9         & 7.7           \\
    3035 Python generator                & 123.2         & 124.3         & 4.1           \\
    3036 Node.js generator               & 33.4          & 33.5          & 0.3           \\
    3037 Goroutine thread                & 751.0         & 750.5         & 3.1           \\
    3038 Rust tokio thread               & 1860.0        & 1881.1        & 37.6          \\
    3039 Rust thread                             & 53801.0       & 53896.8       & 274.9         \\
    3040 Java thread                             & 120274.0      & 120722.9      & 2356.7        \\
    3041 Pthreads thread                 & 31465.5       & 31419.5       & 140.4
     2987\captionof{table}{Context switch comparison (nanoseconds)}
     2988\label{t:ctx-switch}
     2989\begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
     2990\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
     2991C function                      & 1.8           & 1.8           & 0.0   \\
     2992\CFA generator          & 1.8           & 2.0           & 0.3   \\
     2993\CFA coroutine          & 32.5          & 32.9          & 0.8   \\
     2994\CFA thread                     & 93.8          & 93.6          & 2.2   \\
     2995\uC coroutine           & 50.3          & 50.3          & 0.2   \\
     2996\uC thread                      & 97.3          & 97.4          & 1.0   \\
     2997Python generator        & 40.9          & 41.3          & 1.5   \\
     2998Node.js generator       & 32.6          & 32.2          & 1.0   \\
     2999Node.js await           & 1852.2        & 1854.7        & 16.4  \\
     3000Goroutine thread        & 143.0         & 143.3         & 1.1   \\
     3001Rust thread                     & 332.0         & 331.4         & 2.4   \\
     3002Java thread                     & 405.0         & 415.0         & 17.6  \\
     3003Pthreads thread         & 334.3         & 335.2         & 3.9
    30423004\end{tabular}
    30433005\end{multicols}
    30443006
    3045 \vspace*{-10pt}
    30463007\paragraph{Internal Scheduling}
    30473008
     
    30753036}
    30763037\end{cfa}
    3077 \vspace*{-8pt}
    30783038\captionof{figure}{\CFA Internal-scheduling benchmark}
    30793039\label{f:schedint}
     
    31443104\paragraph{Mutual-Exclusion}
    31453105
    3146 Uncontented mutual exclusion, which frequently occurs, is measured by entering and leaving a critical section.
    3147 For monitors, entering and leaving a mutex function is measured, otherwise the language-appropriate mutex-lock is measured.
     3106Uncontented mutual exclusion, which frequently occurs, is measured by entering/leaving a critical section.
     3107For monitors, entering and leaving a monitor function is measured, otherwise the language-appropriate mutex-lock is measured.
    31483108For comparison, a spinning (versus blocking) test-and-test-set lock is presented.
    31493109Figure~\ref{f:mutex} shows the code for \CFA with results in Table~\ref{t:mutex}.
     
    31823142\end{multicols}
    31833143
    3184 \paragraph{Context Switching}
    3185 
    3186 In procedural programming, the cost of a function call is important as modularization (refactoring) increases.
    3187 (In many cases, a compiler inlines function calls to increase the size and number of basic blocks for optimizing.)
    3188 Similarly, when modularization extends to coroutines and threads, the time for a context switch becomes a relevant factor.
    3189 The coroutine test is from resumer to suspender and from suspender to resumer, which is two context switches.
    3190 %For async-await systems, the test is scheduling and fulfilling @N@ empty promises, where all promises are allocated before versus interleaved with fulfillment to avoid garbage collection.
    3191 For 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@).
    3192 The thread test is using yield to enter and return from the runtime kernel, which is two context switches.
    3193 The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling.
    3194 Figure~\ref{f:ctx-switch} shows the \CFA code for a coroutine and thread with results in Table~\ref{t:ctx-switch}.
    3195 
    3196 % From: Gregor Richards <gregor.richards@uwaterloo.ca>
    3197 % To: "Peter A. Buhr" <pabuhr@plg2.cs.uwaterloo.ca>
    3198 % Date: Fri, 24 Jan 2020 13:49:18 -0500
    3199 %
    3200 % I can also verify that the previous version, which just tied a bunch of promises together, *does not* go back to the
    3201 % event loop at all in the current version of Node. Presumably they're taking advantage of the fact that the ordering of
    3202 % events is intentionally undefined to just jump right to the next 'then' in the chain, bypassing event queueing
    3203 % entirely. That's perfectly correct behavior insofar as its difference from the specified behavior isn't observable, but
    3204 % it isn't typical or representative of much anything useful, because most programs wouldn't have whole chains of eager
    3205 % promises. Also, it's not representative of *anything* you can do with async/await, as there's no way to encode such an
    3206 % eager chain that way.
     3144\paragraph{Creation}
     3145
     3146Creation is measured by creating/deleting a specific kind of control-flow object.
     3147Figure~\ref{f:creation} shows the code for \CFA with results in Table~\ref{t:creation}.
     3148Note, the call stacks of \CFA coroutines are lazily created on the first resume, therefore the cost of creation with and without a stack are presented.
    32073149
    32083150\begin{multicols}{2}
    32093151\lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}}
    3210 \begin{cfa}[aboveskip=0pt,belowskip=0pt]
    3211 @coroutine@ C {};
    3212 void main( C & ) { for () { @suspend;@ } }
    3213 int main() { // coroutine test
    3214         C c;
    3215         BENCH( for ( N ) { @resume( c );@ } )
     3152\begin{cfa}
     3153@coroutine@ MyCoroutine {};
     3154void ?{}( MyCoroutine & this ) {
     3155#ifdef EAGER
     3156        resume( this );
     3157#endif
     3158}
     3159void main( MyCoroutine & ) {}
     3160int main() {
     3161        BENCH( for ( N ) { @MyCoroutine c;@ } )
    32163162        sout | result;
    32173163}
    3218 int main() { // thread test
    3219         BENCH( for ( N ) { @yield();@ } )
    3220         sout | result;
    3221 }
    3222 \end{cfa}
    3223 \captionof{figure}{\CFA context-switch benchmark}
    3224 \label{f:ctx-switch}
     3164\end{cfa}
     3165\captionof{figure}{\CFA creation benchmark}
     3166\label{f:creation}
    32253167
    32263168\columnbreak
    32273169
    32283170\vspace*{-16pt}
    3229 \captionof{table}{Context switch comparison (nanoseconds)}
    3230 \label{t:ctx-switch}
    3231 \begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}}
    3232 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
    3233 C function                      & 1.8           & 1.8           & 0.0   \\
    3234 \CFA generator          & 1.8           & 2.0           & 0.3   \\
    3235 \CFA coroutine          & 32.5          & 32.9          & 0.8   \\
    3236 \CFA thread                     & 93.8          & 93.6          & 2.2   \\
    3237 \uC coroutine           & 50.3          & 50.3          & 0.2   \\
    3238 \uC thread                      & 97.3          & 97.4          & 1.0   \\
    3239 Python generator        & 40.9          & 41.3          & 1.5   \\
    3240 Node.js await           & 1852.2        & 1854.7        & 16.4  \\
    3241 Node.js generator       & 33.3          & 33.4          & 0.3   \\
    3242 Goroutine thread        & 143.0         & 143.3         & 1.1   \\
    3243 Rust async await        & 32.0          & 32.0          & 0.0   \\
    3244 Rust tokio thread       & 143.0         & 143.0         & 1.7   \\
    3245 Rust thread                     & 332.0         & 331.4         & 2.4   \\
    3246 Java thread                     & 405.0         & 415.0         & 17.6  \\
    3247 Pthreads thread         & 334.3         & 335.2         & 3.9
     3171\captionof{table}{Creation comparison (nanoseconds)}
     3172\label{t:creation}
     3173
     3174\begin{tabular}[t]{@{}r*{3}{D{.}{.}{5.2}}@{}}
     3175\multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\
     3176\CFA generator                  & 0.6           & 0.6           & 0.0           \\
     3177\CFA coroutine lazy             & 13.4          & 13.1          & 0.5           \\
     3178\CFA coroutine eager    & 144.7         & 143.9         & 1.5           \\
     3179\CFA thread                             & 466.4         & 468.0         & 11.3          \\
     3180\uC coroutine                   & 155.6         & 155.7         & 1.7           \\
     3181\uC thread                              & 523.4         & 523.9         & 7.7           \\
     3182Python generator                & 123.2         & 124.3         & 4.1           \\
     3183Node.js generator               & 32.3          & 32.2          & 0.3           \\
     3184Goroutine thread                & 751.0         & 750.5         & 3.1           \\
     3185Rust thread                             & 53801.0       & 53896.8       & 274.9         \\
     3186Java thread                             & 120274.0      & 120722.9      & 2356.7        \\
     3187Pthreads thread                 & 31465.5       & 31419.5       & 140.4
    32483188\end{tabular}
    32493189\end{multicols}
     
    32523192\subsection{Discussion}
    32533193
    3254 Languages using 1:1 threading based on pthreads can at best meet or exceed, due to language overhead, the pthread results.
     3194Languages using 1:1 threading based on pthreads can at best meet or exceed (due to language overhead) the pthread results.
    32553195Note, pthreads has a fast zero-contention mutex lock checked in user space.
    32563196Languages with M:N threading have better performance than 1:1 because there is no operating-system interactions.
     
    32603200
    32613201
    3262 \section{Conclusions and Future Work}
     3202\section{Conclusion}
    32633203
    32643204Advanced control-flow will always be difficult, especially when there is temporal ordering and nondeterminism.
     
    32673207Combining these properties creates a number of high-level, efficient, and maintainable control-flow types: generator, coroutine, thread, each of which can be a monitor.
    32683208Eliminated from \CFA are barging and spurious wakeup, which are nonintuitive and lead to errors, and having to work with a bewildering set of low-level locks and acquisition techniques.
    3269 \CFA high-level race-free monitors and threads, when used with mutex access function, provide the core mechanisms for mutual exclusion and synchronization, without having to resort to magic qualifiers like @volatile@ or @atomic@.
     3209\CFA high-level race-free monitors and threads provide the core mechanisms for mutual exclusion and synchronization, without having to resort to magic qualifiers like @volatile@/@atomic@.
    32703210Extending these mechanisms to handle high-level deadlock-free bulk acquire across both mutual exclusion and synchronization is a unique contribution.
    32713211The \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.
    32723212The M:N model is judged to be efficient and provide greater flexibility than a 1:1 threading model.
    32733213These 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.
    3274 Performance 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.
     3214Performance comparisons with other concurrent systems/languages show the \CFA approach is competitive across all basic operations, which translates directly into good performance in well-written applications with advanced control-flow.
    32753215C 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.
    32763216
     3217
     3218\section{Future Work}
     3219
    32773220While control flow in \CFA has a strong start, development is still underway to complete a number of missing features.
    32783221
    3279 \medskip
    3280 \textbf{Flexible Scheduling:}
     3222\paragraph{Flexible Scheduling}
     3223\label{futur:sched}
     3224
    32813225An important part of concurrency is scheduling.
    3282 Different scheduling algorithms can affect performance, both in terms of average and variation.
     3226Different scheduling algorithms can affect performance (both in terms of average and variation).
    32833227However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs.
    32843228One solution is to offer various tuning options, allowing the scheduler to be adjusted to the requirements of the workload.
     
    32863230Currently, 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}.
    32873231
    3288 \smallskip
    3289 \textbf{Non-Blocking I/O:}
     3232\paragraph{Non-Blocking I/O}
     3233\label{futur:nbio}
     3234
    32903235Many modern workloads are not bound by computation but IO operations, common cases being web servers and XaaS~\cite{XaaS} (anything as a service).
    32913236These types of workloads require significant engineering to amortizing costs of blocking IO-operations.
     
    32963241A non-blocking I/O library is currently under development for \CFA.
    32973242
    3298 \smallskip
    3299 \textbf{Other Concurrency Tools:}
     3243\paragraph{Other Concurrency Tools}
     3244\label{futur:tools}
     3245
    33003246While monitors offer flexible and powerful concurrency for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package.
    33013247Examples of such tools can include futures and promises~\cite{promises}, executors and actors.
     
    33033249As well, new \CFA extensions should make it possible to create a uniform interface for virtually all mutual exclusion, including monitors and low-level locks.
    33043250
    3305 \smallskip
    3306 \textbf{Implicit Threading:}
    3307 Basic \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.
     3251\paragraph{Implicit Threading}
     3252\label{futur:implcit}
     3253
     3254Basic concurrent (embarrassingly parallel) applications can benefit greatly from implicit concurrency, where sequential programs are converted to concurrent, possibly with some help from pragmas to guide the conversion.
    33083255This type of concurrency can be achieved both at the language level and at the library level.
    33093256The canonical example of implicit concurrency is concurrent nested @for@ loops, which are amenable to divide and conquer algorithms~\cite{uC++book}.
  • doc/papers/concurrency/mail2

    r97392b69 ra5873bd  
    512512Software: Practice and Experience Editorial Office
    513513
    514 
    515 
    516 Date: Sat, 18 Apr 2020 10:42:13 +0000
    517 From: Richard Jones <onbehalfof@manuscriptcentral.com>
    518 Reply-To: R.E.Jones@kent.ac.uk
    519 To: tdelisle@uwaterloo.ca, pabuhr@uwaterloo.ca
    520 Subject: Software: Practice and Experience - Decision on Manuscript ID
    521  SPE-19-0219.R1
    522 
    523 18-Apr-2020
    524 
    525 Dear Dr Buhr,
    526 
    527 Many thanks for submitting SPE-19-0219.R1 entitled "Advanced Control-flow and Concurrency in Cforall" to Software: Practice and Experience. The paper has now been reviewed and the comments of the referees are included at the bottom of this letter.
    528 
    529 I believe that we are making progress here towards a paper that can be published in Software: Practice and Experience.  However the referees still have significant concerns about the paper. The journal's focus is on practice and experience, and one of the the reviewers' concerns remains that your submission should focus the narrative more on the perspective of the programmer than the language designer. I agree that this would strengthen your submission, and I ask you to address this as well as the referees' other comments.
    530 
    531 A revised version of your manuscript that takes into account the comments of the referee(s) will be reconsidered for publication.
    532 
    533 Please note that submitting a revision of your manuscript does not guarantee eventual acceptance, and that your revision may be subject to re-review by the referees before a decision is rendered.
    534 
    535 You have 90 days from the date of this email to submit your revision. If you are unable to complete the revision within this time, please contact me to request a short extension.
    536 
    537 You can upload your revised manuscript and submit it through your Author Center. Log into https://mc.manuscriptcentral.com/spe  and enter your Author Center, where you will find your manuscript title listed under "Manuscripts with Decisions".
    538 
    539 When submitting your revised manuscript, you will be able to respond to the comments made by the referee(s) in the space provided.  You can use this space to document any changes you make to the original manuscript.
    540 
    541 If you would like help with English language editing, or other article preparation support, Wiley Editing Services offers expert help with English Language Editing, as well as translation, manuscript formatting, and figure formatting at www.wileyauthors.com/eeo/preparation. You can also check out our resources for Preparing Your Article for general guidance about writing and preparing your manuscript at www.wileyauthors.com/eeo/prepresources.
    542 
    543 Once again, thank you for submitting your manuscript to Software: Practice and Experience and I look forward to receiving your revision.
    544 
    545 Sincerely,
    546 Richard
    547 
    548 Prof. Richard Jones
    549 Software: Practice and Experience
    550 R.E.Jones@kent.ac.uk
    551 
    552 
    553 Referee(s)' Comments to Author:
    554 
    555 Reviewing: 1
    556 
    557 Comments to the Author
    558 (A relatively short second review)
    559 
    560 I thank the authors for their revisions and comprehensive response to
    561 reviewers' comments --- many of my comments have been successfully
    562 addressed by the revisions.  Here I'll structure my comments around
    563 the main salient points in that response which I consider would
    564 benefit from further explanation.
    565 
    566 >  Table 1 is moved to the start and explained in detail.
    567 
    568 I consider this change makes a significant improvement to the paper,
    569 laying out the landscape of language features at the start, and thus
    570 addresses my main concerns about the paper.
    571 
    572 I still have a couple of issues --- perhaps the largest is that it's
    573 still not clear at this point in the paper what some of these options
    574 are, or crucially how they would be used. I don't know if it's
    575 possbile to give high-level examples or use cases to be clear about
    576 these up front - or if that would duplicate too much information from
    577 later in the paper - either way expanding out the discussion - even if
    578 just two a couple of sentences for each row - would help me more.  The
    579 point is not just to define these categories but to ensure the
    580 readers' understanding of these definitons agrees with that used in
    581 the paper.
    582 
    583 in a little more detail:
    584 
    585  * 1st para section 2 begs the question: why not support each
    586    dimension independently, and let the programmer or library designer
    587    combiine features?
    588 
    589  * "execution state" seems a relatively low-level description here.
    590   I don't think of e.g. the lambda calculus that way. Perhaps it's as
    591   good a term as any.
    592 
    593  * Why must there "be language mechanisms to create, block/unblock,
    594    and join with a thread"?  There aren't in Smalltalk (although there
    595    are in the runtime).  Especially given in Cforall those mechanisms
    596    are *implicit* on thread creation and destruction?
    597 
    598  * "Case 1 is a function that borrows storage for its state (stack
    599    frame/activation) and a thread from its invoker"
    600 
    601    this much makes perfect sense to me, but I don't understand how a
    602    non-stateful, non-theaded function can then retain
    603 
    604    "this state across callees, ie, function local-variables are
    605    retained on the stack across calls."
    606 
    607    how can it retain function-local values *across calls* when it
    608    doesn't have any functional-local state?
    609 
    610    I'm not sure if I see two separate cases here - rougly equivalent
    611    to C functions without static storage, and then C functions *with*
    612    static storage. I assumed that was the distinction between cases 1
    613    & 3; but perhpas the actual distinction is that 3 has a
    614    suspend/resume point, and so the "state" in figure 1 is this
    615    component of execution state (viz figs 1 & 2), not the state
    616    representing the cross-call variables?
    617 
    618 >    but such evaluation isn't appropriate for garbage-collected or JITTed
    619    languages like Java or Go.
    620 
    621 For JITTed languages in particular, reporting peak performance needs
    622 to "warm up" the JIT with a number of iterators before beginning
    623 measurement. Actually for JIT's its even worse: see Edd Barrett et al
    624 OOPSLA 2017.
    625    
    626 
    627 
    628 minor issues:
    629 
    630  * footnote A - I've looked at various other papers & the website to
    631    try to understand how "object-oriented" Cforall is - I'm still not
    632    sure.  This footnote says Cforall has "virtuals" - presumably
    633    virtual functions, i.e. dynamic dispatch - and inheritance: that
    634    really is OO as far as I (and most OO people) are concerned.  For
    635    example Haskell doesn't have inheritance, so it's not OO; while
    636    CLOS (the Common Lisp *Object* System) or things like Cecil and
    637    Dylan are considered OO even though they have "multiple function
    638    parameters as receivers", lack "lexical binding between a structure
    639    and set of functions", and don't have explicit receiver invocation
    640    syntax.  Python has receiver syntax, but unlike Java or Smalltalk
    641    or C++, method declarations still need to have an explicit "self"
    642    receiver parameter.  Seems to me that Go, for example, is
    643    more-or-less OO with interfaces, methods, and dynamic dispatch (yes
    644    also and an explicit receiver syntax but that's not
    645    determiniative); while Rust lacks dynamic dispatch built-in.  C is
    646    not OO as a language, but as you say given it supports function
    647    pointers with structures, it does support an OO programm style.
    648  
    649    This is why I again recommend just not buying into this fight: not
    650    making any claims about whether Cforall is OO or is not - because
    651    as I see it, the rest of the paper doesn't depend on whether
    652    Cforall is OO or not.  That said: this is just a recommendation,
    653    and I won't quibble over this any further.
    654 
    655  * is a "monitor function" the same as a "mutex function"?
    656    if so the paper should pick one term; if not, make the distinction clear.
    657 
    658 
    659  * "As stated on line 1 because state declarations from the generator
    660     type can be moved out of the coroutine type into the coroutine main"
    661 
    662     OK sure, but again: *why* would a programmer want to do that?
    663     (Other than, I guess, to show the difference between coroutines &
    664     generators?)  Perhaps another way to put this is that the first
    665     para of 3.2 gives the disadvantages of coroutines vs-a-vs
    666     generators, briefly describes the extended semantics, but never
    667     actualy says why a programmer may want those extended semantics,
    668     or how they would benefit.  I don't mean to belabour the point,
    669     but (generalist?) readers like me would generally benefit from
    670     those kinds of discussions about each feature throughout the
    671     paper: why might a programmer want to use them?
    672    
    673 
    674 > p17 if the multiple-monitor entry procedure really is novel, write a paper
    675 > about that, and only about that.
    676 
    677 > We do not believe this is a practical suggestion.
    678 
    679  * I'm honestly not trying to be snide here: I'm not an expert on
    680    monitor or concurrent implementations. Brinch Hansen's original
    681    monitors were single acquire; this draft does not cite any other
    682    previous work that I could see. I'm not suggesting that the brief
    683    mention of this mechanism necessarily be removed from this paper,
    684    but if this is novel (and a clear advance over a classical OO
    685    monitor a-la Java which only acquires the distinguished reciever)
    686    then that would be worth another paper in itself.
    687  
    688 > * conclusion should conclude the paper, not the related.
    689 > We do not understand this comment.if ithis
    690 
    691 My typo: the paper's conclusion should come at the end, after the
    692 future work section.
    693 
    694 
    695 
    696 
    697 To encourage accountability, I'm signing my reviews in 2020.
    698 For the record, I am James Noble, kjx@ecs.vuw.ac.nz.
    699 
    700 
    701 Reviewing: 2
    702 
    703 Comments to the Author
    704 I thank the authors for their detailed response. To respond to a couple of points raised  in response to my review (number 2):
    705 
    706 - on the Boehm paper and whether code is "all sequential to the compiler": I now understand the authors' position better and suspect we are in violent agreement, except for whether it's appropriate to use the rather breezy phrase "all sequential to the compiler". It would be straightforward to clarify that code not using the atomics features is optimized *as if* it were sequential, i.e. on the assumption of a lack of data races.
    707 
    708 - on the distinction between "mutual exclusion" and "synchronization": the added citation does help, in that it makes a coherent case for the definition the authors prefer. However, the text could usefully clarify that this is a matter of definition not of fact, given especially that in my assessment the authors' preferred definition is not the most common one. (Although the mention of Hoare's apparent use of this definition is one data point, countervailing ones are found in many contemporaneous or later papers, e.g. Habermann's 1972 "Synchronization of Communicating Processes" (CACM 15(3)), Reed & Kanodia's 1979 "Synchronization with eventcounts and sequencers" (CACM (22(2)) and so on.)
    709 
    710 I am glad to see that the authors have taken on board most of the straightforward improvements I suggested.
    711 
    712 However, a recurring problem of unclear writing still remains through many parts of the paper, including much of sections 2, 3 and 6. To highlight a couple of problem patches (by no means exhaustive):
    713 
    714 - section 2 (an expanded version of what was previously section 5.9) lacks examples and is generally obscure and allusory ("the most advanced feature" -- name it! "in triplets" -- there is only one triplet!; what are "execution locations"? "initialize" and "de-initialize" what? "borrowed from the invoker" is a concept in need of explaining or at least a fully explained example -- in what sense does a plain function borrow" its stack frame? "computation only" as opposed to what? in 2.2, in what way is a "request" fundamental to "synchronization"? and the "implicitly" versus "explicitly" point needs stating as elsewhere, with a concrete example e.g. Java built-in mutexes versus java.util.concurrent).
    715 
    716 - section 6: 6.2 omits the most important facts in preference for otherwise inscrutable detail: "identify the kind of parameter" (first say *that there are* kinds of parameter, and what "kinds" means!); "mutex parameters are documentation" is misleading (they are also semantically significant!) and fails to say *what* they mean; the most important thing is surely that 'mutex' is a language feature for performing lock/unlock operations at function entry/exit. So say it! The meanings of examples f3 and f4 remain unclear. Meanwhile in 6.3, "urgent" is not introduced (we are supposed to infer its meaning from Figure 12, but that Figure is incomprehensible to me), and we are told of "external scheduling"'s long history in Ada but not clearly what it actually means; 6.4's description of "waitfor" tells us it is different from an if-else chain but tries to use two *different* inputs to tell us that the behavior is different; tell us an instance where *the same* values of C1 and C2 give different behavior (I even wrote out a truth table and still don't see the semantic difference)
    717 
    718 The authors frequently use bracketed phrases, and sometimes slashes "/", in ways that are confusing and/or detrimental to readability. Page 13 line 2's "forward (backward)" is one particularly egregious example. In general I would recommend the the authors try to limit their use of parentheses and slashes as a means of forcing a clearer wording to emerge. Also, the use of "eg." is often cursory and does not explain the examples given, which are frequently a one- or two-word phrase of unclear referent.
    719 
    720 Considering the revision more broadly, none of the more extensive or creative rewrites I suggested in my previous review have been attempted, nor any equivalent efforts to improve its readability. The hoisting of the former section 5.9 is a good idea, but the newly added material accompanying it (around Table 1) suffers fresh deficiencies in clarity. Overall the paper is longer than before, even though (as my previous review stated), I believe a shorter paper is required in order to serve the likely purpose of publication. (Indeed, the authors' letter implies that a key goal of publication is to build community and gain external users.)
    721 
    722 Given this trajectory, I no longer see a path to an acceptable revision of the present submission. Instead I suggest the authors consider splitting the paper in two: one half about coroutines and stack management, the other about mutexes, monitors and the runtime. (A briefer presentation of the runtime may be helpful in the first paper also, and a brief recap of the generator and coroutine support is obviously needed in the second too.) Both of these new papers would need to be written with a strong emphasis on clarity, paying great care to issues of structure, wording, choices of example, and restraint (saying what's important, not everything that could be said). I am confident the authors could benefit from getting early feedback from others at their institution. For the performance experiments, of course these do not split evenly -- most (but not all) belong in the second of these two hypothetical papers. But the first of them would still have plenty of meat to it; for me, a clear and thorough study of the design space around coroutines is the most interesting and tantalizing prospect.
    723 
    724 I do not buy the authors' defense of the limited practical experience or "non-micro" benchmarking presented. Yes, gaining external users is hard and I am sympathetic on that point. But building something at least *somewhat* substantial with your own system should be within reach, and without it the "practice and experience" aspects of the work have not been explored. Clearly C\/ is the product of a lot of work over an extended period, so it is a surprise that no such experience is readily available for inclusion.
    725 
    726 Some smaller points:
    727 
    728 It does not seem right to state that a stack is essential to Von Neumann architectures -- since the earliest Von Neumann machines (and indeed early Fortran) did not use one.
    729 
    730 To elaborate on something another reviewer commented on: it is a surprise to find a "Future work" section *after* the "Conclusion" section. A "Conclusions and future work" section often works well.
    731 
    732 
    733 Reviewing: 3
    734 
    735 Comments to the Author
    736 This is the second round of reviewing.
    737 
    738 As in the first review, I found that the paper (and Cforall) contains
    739 a lot of really interesting ideas, but it remains really difficult to
    740 have a good sense of which idea I should use and when. This applies in
    741 different ways to different features from the language:
    742 
    743 * coroutines/generators/threads: here there is
    744   some discussion, but it can be improved.
    745 * interal/external scheduling: I didn't find any direct comparison
    746   between these features, except by way of example.
    747 
    748 I requested similar things in my previous review and I see that
    749 content was added in response to those requests. Unfortunately, I'm
    750 not sure that I can say it improved the paper's overall read. I think
    751 in some sense the additions were "too much" -- I would have preferred
    752 something more like a table or a few paragraphs highlighting the key
    753 reasons one would pick one construct or the other.
    754 
    755 In general, I do wonder if the paper is just trying to do too much.
    756 The discussion of clusters and pre-emption in particular feels quite
    757 rushed.
    758 
    759 ## Summary
    760 
    761 I make a number of suggestions below but the two most important
    762 I think are:
    763 
    764 * Recommend to shorten the comparison on coroutine/generator/threads
    765   in Section 2 to a paragraph with a few examples, or possibly a table
    766   explaining the trade-offs between the constructs
    767 * Recommend to clarify the relationship between internal/external
    768   scheduling -- is one more general but more error-prone or low-level?
    769 
    770 ## Coroutines/generators/threads
    771 
    772 There is obviously a lot of overlap between these features, and in
    773 particular between coroutines and generators. As noted in the previous
    774 review, many languages have chosen to offer *only* generators, and to
    775 build coroutines by stacks of generators invoking one another.
    776 
    777 I believe the newly introduced Section 2 of the paper is trying to
    778 motivate why each of these constructs exist, but I did not find it
    779 effective. It was dense and difficult to understand. I think the
    780 problem is that Section 2 seems to be trying to derive "from first
    781 principles" why each construct exists, but I think that a more "top
    782 down" approach would be easier to understand.
    783 
    784 In fact, the end of Section 2.1 (on page 5) contains a particular
    785 paragraph that embodies this "top down" approach. It starts,
    786 "programmers can now answer three basic questions", and thus gives
    787 some practical advice for which construct you should use and when. I
    788 think giving some examples of specific applications that this
    789 paragraph, combined with some examples of cases where each construct
    790 was needed, would be a better approach.
    791 
    792 I don't think this compariosn needs to be very long. It seems clear
    793 enough that one would
    794 
    795 * prefer generators for simple computations that yield up many values,
    796 * prefer coroutines for more complex processes that have significant
    797   internal structure,
    798 * prefer threads for cases where parallel execution is desired or
    799   needed.
    800 
    801 I did appreciate the comparison in Section 2.3 between async-await in
    802 JS/Java and generators/coroutines. I agree with its premise that those
    803 mechanisms are a poor replacement for generators (and, indeed, JS has
    804 a distinct generator mechanism, for example, in part for this reason).
    805 I believe I may have asked for this in a previous review, but having
    806 read it, I wonder if it is really necessary, since those mechanisms
    807 are so different in purpose.
    808 
    809 ## Internal vs external scheduling
    810 
    811 I find the motivation for supporting both internal and external
    812 scheduling to be fairly implicit. After several reads through the
    813 section, I came to the conclusion that internal scheduling is more
    814 expressive than external scheduling, but sometimes less convenient or
    815 clear. Is this correct? If not, it'd be useful to clarify where
    816 external scheduling is more expressive.
    817 
    818 The same is true, I think, of the `signal_block` function, which I
    819 have not encountered before; it seems like its behavior can be modeled
    820 with multiple condition variables, but that's clearly more complex.
    821 
    822 One question I had about `signal_block`: what happens if one signals
    823 but no other thread is waiting? Does it block until some other thread
    824 waits? Or is that user error?
    825 
    826 I would find it very interesting to try and capture some of the
    827 properties that make internal vs external scheduling the better
    828 choice.
    829 
    830 For example, it seems to me that external scheduling works well if
    831 there are only a few "key" operations, but that internal scheduling
    832 might be better otherwise, simply because it would be useful to have
    833 the ability to name a signal that can be referenced by many
    834 methods. Consider the bounded buffer from Figure 13: if it had
    835 multiple methods for removing elements, and not just `remove`, then
    836 the `waitfor(remove)` call in `insert` might not be sufficient.
    837 
    838 ## Comparison of external scheduling to messaging
    839 
    840 I did enjoy the section comparing external scheduling to Go's
    841 messaging mechanism, which I believe is a new addition.
    842 
    843 I believe that one difference between the Go program and the Cforall
    844 equivalent is that the Goroutine has an associated queue, so that
    845 multiple messages could be enqueued, whereas the Cforall equivalent is
    846 effectively a "bounded buffer" of length 1. Is that correct? I think
    847 this should be stated explicitly. (Presumably, one could modify the
    848 Cforall program to include an explicit vector of queued messages if
    849 desired, but you would also be reimplementing the channel
    850 abstraction.)
    851 
    852 Also, in Figure 20, I believe that there is a missing `mutex` keyword.
    853 The fiugre states:
    854 
    855 ```
    856 void main(GoRtn & gortn) with(gortn) {
    857 ```
    858 
    859 but I think it should probably be as follows:
    860 
    861 ```
    862 void main(GoRtn & mutex gortn) with(gortn) {
    863 ```
    864 
    865 Unless there is some implicit `mutex` associated with being a main
    866 function for a `monitor thread`.
    867 
    868 ## Atomic operations and race freedom
    869 
    870 I was glad to see that the paper acknowledged that Cforall still had
    871 low-level atomic operations, even if their use is discouraged in favor
    872 of higher-level alternatives.
    873 
    874 However, I still feel that the conclusion overstates the value of the
    875 contribution here when it says that "Cforall high-level race-free
    876 monitors and threads provide the core mechanisms for mutual exclusion
    877 and synchronization, without the need for volatile and atomics". I
    878 feel confident that Java programmers, for example, would be advised to
    879 stick with synchronized methods whenever possible, and it seems to me
    880 that they offer similar advantages -- but they sometimes wind up using
    881 volatiles for performance reasons.
    882 
    883 I was also confused by the term "race-free" in that sentence. In
    884 particular, I don't think that Cforall has any mechanisms for
    885 preventing *data races*, and it clearly doesn't prevent "race
    886 conditions" (which would bar all sorts of useful programs). I suppose
    887 that "race free" here might be referring to the improvements such as
    888 removing barging behavior.
    889 
    890 ## Performance comparisons
    891 
    892 In my previous review, I requested comparisons against Rust and
    893 node.js, and I see that the new version of the paper includes both,
    894 which is a good addition.
    895 
    896 One note on the Rust results: I believe that the results are comparing
    897 against the threads found in Rust's standard library, which are
    898 essentially a shallow wrapper around pthreads, and hence the
    899 performance is quite close to pthread performance (as one would
    900 expect). It would perhaps be more interesting to see a comparison
    901 built using [tokio] or [async-std], two of the more prominent
    902 user-space threading libraries that build on Rust's async-await
    903 feature (which operates quite differently than Javascript's
    904 async-await, in that it doesn't cause every aync function call to
    905 schedule a distinct task).
    906 
    907 [tokio]: https://tokio.rs/
    908 [async-std]: https://async.rs/
    909 
    910 That said, I am satisfied with the performance results as they are in
    911 the current revision.
    912 
    913 ## Minor notes and typos
    914 
    915 Several figures used the `with` keyword. I deduced that `with(foo)`
    916 permits one to write `bar` instead of `foo.bar`. It seems worth
    917 introducing. Apologies if this is stated in the paper, if so I missed
    918 it.
    919 
    920 On page 20, section 6.3, "external scheduling and vice versus" should be
    921 "external scheduling and vice versa".
    922 
    923 On page 5, section 2.3, the paper states "we content" but it should be
    924 "we contend".
    925 
    926 Reviewing: Editor
    927 
    928 A few small comments in addition to those of the referees.
    929 
    930 Page 1. I don't believe that it s fair to imply that Scala is  "research vehicle" as it is used by major players, Twitter being the most prominent example.
    931 
    932 Page 15. Must Cforall threads start after construction (e.g. see your example on page 15, line 21)? I can think of examples where it is not desirable that threads start immediately after construction, e.g. a game with N players, each of whom is expensive to create, but all of whom should be started at the same time.
    933 
    934 Page 18, line 17: is using
    935 
  • driver/cc1.cc

    r97392b69 ra5873bd  
    1010// Created On       : Fri Aug 26 14:23:51 2005
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sat May 30 18:09:05 2020
    13 // Update Count     : 404
     12// Last Modified On : Sun Oct 20 08:14:33 2019
     13// Update Count     : 385
    1414//
    1515
     
    3838static string o_file;
    3939static string bprefix;
    40 static string lang;                                                                             // -x flag
    4140
    4241
     
    7473                        if ( prefix( val, "-compiler=" ) ) {
    7574                                compiler_path = val.substr( 10 );
    76                         } else if ( prefix( val, "-x=" ) ) {
    77                                 lang = val.substr( 3 );
    7875                        } // if
    7976                } // if
     
    103100                        } else if ( prefix( val, "-B=" ) ) {            // location of cfa-cpp
    104101                                bprefix = val.substr( 3 );
    105                         } else if ( prefix( val, "-x=" ) ) {            // ignore
    106102                        } else {                                                                        // normal flag for cfa-cpp
    107103                                args[nargs++] = ( *new string( arg.substr( arg.find_first_of( "=" ) + 1 ) ) ).c_str();
     
    251247
    252248                args[0] = compiler_path.c_str();
    253                 if ( lang.size() == 0 ) {
    254                         suffix( cpp_in, args, nargs );                          // check suffix
    255                 } else {
    256                         args[nargs++] = "-x";
    257                         args[nargs++] = ( *new string( lang.c_str() ) ).c_str();
    258                 } // if
     249                suffix( cpp_in, args, nargs );                                  // check suffix
    259250                args[nargs++] = cpp_in;
    260251                if ( o_flag ) {                                                                 // location for output
     
    289280
    290281                args[0] = compiler_path.c_str();
    291                 if ( lang.size() == 0 ) {
    292                         suffix( cpp_in, args, nargs );                          // check suffix
    293                 } else {
    294                         args[nargs++] = "-x";
    295                         args[nargs++] = ( *new string( lang.c_str() ) ).c_str();
    296                 } // if
     282                suffix( cpp_in, args, nargs );                                  // check suffix
    297283                args[nargs++] = cpp_in;                                                 // input to cpp
    298284                args[nargs] = nullptr;                                                  // terminate argument list
  • driver/cfa.cc

    r97392b69 ra5873bd  
    1010// Created On       : Tue Aug 20 13:44:49 2002
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sat May 30 18:28:23 2020
    13 // Update Count     : 433
     12// Last Modified On : Mon May 18 13:26:26 2020
     13// Update Count     : 424
    1414//
    1515
     
    243243                                        lang = arg.substr( 2 );
    244244                                } // if
    245                                 if ( x_flag ) {
    246                                         cerr << argv[0] << " warning, only one -x flag per compile, ignoring subsequent flag." << endl;
    247                                 } else {
    248                                         x_flag = true;
    249                                         Putenv( argv, string( "-x=" ) + lang );
    250                                 } // if
     245                                x_flag = lang != "none";
    251246                        } else if ( prefix( arg, "-std=" ) || prefix( arg, "--std=" ) ) {
    252247                                std_flag = true;                                                // -std=XX provided
     
    306301        } // for
    307302
    308         #ifdef __x86_64__
    309         args[nargs++] = "-mcx16";                                                       // allow double-wide CAS
    310         #endif // __x86_64__
    311 
    312303        #ifdef __DEBUG_H__
    313304        cerr << "args:";
     
    424415                args[nargs++] = "-lcfa";
    425416                args[nargs++] = "-Wl,--pop-state";
     417                #ifdef __x86_64__
     418                args[nargs++] = "-mcx16";                                               // allow double-wide CAS
     419                args[nargs++] = "-latomic";
     420                #endif // __x86_64__
    426421                args[nargs++] = "-pthread";
    427                 #ifdef __x86_64__
    428                 args[nargs++] = "-latomic";                                             // allow double-wide CAS
    429                 #endif // __x86_64__
    430422                args[nargs++] = "-ldl";
    431423                args[nargs++] = "-lrt";
  • libcfa/src/Makefile.am

    r97392b69 ra5873bd  
    1111## Created On       : Sun May 31 08:54:01 2015
    1212## Last Modified By : Peter A. Buhr
    13 ## Last Modified On : Mon Jun  1 13:35:33 2020
    14 ## Update Count     : 248
     13## Last Modified On : Sun May 17 21:10:26 2020
     14## Update Count     : 243
    1515###############################################################################
    1616
     
    3939#----------------------------------------------------------------------------------------------------------------
    4040if BUILDLIB
    41 headers_nosrc = bitmanip.hfa exception.hfa math.hfa gmp.hfa time_t.hfa clock.hfa \
    42                 bits/align.hfa bits/containers.hfa bits/defs.hfa bits/debug.hfa bits/locks.hfa containers/list.hfa containers/stackLockFree.hfa
    43 headers = common.hfa fstream.hfa heap.hfa iostream.hfa iterator.hfa limits.hfa rational.hfa \
    44                 time.hfa stdlib.hfa memory.hfa \
    45                 containers/maybe.hfa containers/pair.hfa containers/result.hfa containers/vector.hfa
     41headers_nosrc = bitmanip.hfa math.hfa gmp.hfa time_t.hfa clock.hfa \
     42                bits/align.hfa bits/containers.hfa bits/defs.hfa bits/debug.hfa bits/locks.hfa containers/list.hfa
     43headers = fstream.hfa iostream.hfa iterator.hfa limits.hfa rational.hfa time.hfa stdlib.hfa common.hfa \
     44                containers/maybe.hfa containers/pair.hfa containers/result.hfa containers/stackLockFree.hfa containers/vector.hfa
    4645
    47 libsrc = startup.cfa interpose.cfa bits/debug.cfa assert.cfa exception.c virtual.c ${headers:.hfa=.cfa}
     46libsrc = startup.cfa interpose.cfa bits/debug.cfa assert.cfa exception.c virtual.c heap.cfa ${headers:.hfa=.cfa}
    4847
    4948# not all platforms support concurrency, add option do disable it
  • libcfa/src/Makefile.in

    r97392b69 ra5873bd  
    139139libcfa_la_LIBADD =
    140140am__libcfa_la_SOURCES_DIST = prelude.cfa startup.cfa interpose.cfa \
    141         bits/debug.cfa assert.cfa exception.c virtual.c common.cfa \
    142         fstream.cfa heap.cfa iostream.cfa iterator.cfa limits.cfa \
    143         rational.cfa time.cfa stdlib.cfa memory.cfa \
    144         containers/maybe.cfa containers/pair.cfa containers/result.cfa \
     141        bits/debug.cfa assert.cfa exception.c virtual.c heap.cfa \
     142        fstream.cfa iostream.cfa iterator.cfa limits.cfa rational.cfa \
     143        time.cfa stdlib.cfa common.cfa containers/maybe.cfa \
     144        containers/pair.cfa containers/result.cfa \
    145145        containers/vector.cfa
    146146am__dirstamp = $(am__leading_dot)dirstamp
    147 @BUILDLIB_TRUE@am__objects_1 = common.lo fstream.lo heap.lo \
    148 @BUILDLIB_TRUE@ iostream.lo iterator.lo limits.lo rational.lo \
    149 @BUILDLIB_TRUE@ time.lo stdlib.lo memory.lo containers/maybe.lo \
     147@BUILDLIB_TRUE@am__objects_1 = fstream.lo iostream.lo iterator.lo \
     148@BUILDLIB_TRUE@ limits.lo rational.lo time.lo stdlib.lo \
     149@BUILDLIB_TRUE@ common.lo containers/maybe.lo \
    150150@BUILDLIB_TRUE@ containers/pair.lo containers/result.lo \
    151151@BUILDLIB_TRUE@ containers/vector.lo
    152152@BUILDLIB_TRUE@am__objects_2 = startup.lo interpose.lo bits/debug.lo \
    153 @BUILDLIB_TRUE@ assert.lo exception.lo virtual.lo \
     153@BUILDLIB_TRUE@ assert.lo exception.lo virtual.lo heap.lo \
    154154@BUILDLIB_TRUE@ $(am__objects_1)
    155155am_libcfa_la_OBJECTS = prelude.lo $(am__objects_2)
     
    237237  esac
    238238am__nobase_cfa_include_HEADERS_DIST = $(shell find $(srcdir)/stdhdr \
    239         -type f -printf "%p ") common.hfa fstream.hfa heap.hfa \
    240         iostream.hfa iterator.hfa limits.hfa rational.hfa time.hfa \
    241         stdlib.hfa memory.hfa containers/maybe.hfa containers/pair.hfa \
    242         containers/result.hfa containers/vector.hfa bitmanip.hfa \
    243         exception.hfa math.hfa gmp.hfa time_t.hfa clock.hfa \
    244         bits/align.hfa bits/containers.hfa bits/defs.hfa \
     239        -type f -printf "%p ") fstream.hfa iostream.hfa iterator.hfa \
     240        limits.hfa rational.hfa time.hfa stdlib.hfa common.hfa \
     241        containers/maybe.hfa containers/pair.hfa containers/result.hfa \
     242        containers/vector.hfa bitmanip.hfa math.hfa gmp.hfa time_t.hfa \
     243        clock.hfa bits/align.hfa bits/containers.hfa bits/defs.hfa \
    245244        bits/debug.hfa bits/locks.hfa containers/list.hfa \
    246         containers/stackLockFree.hfa concurrency/coroutine.hfa \
    247         concurrency/thread.hfa concurrency/kernel.hfa \
    248         concurrency/monitor.hfa concurrency/mutex.hfa \
    249         concurrency/invoke.h
     245        concurrency/coroutine.hfa concurrency/thread.hfa \
     246        concurrency/kernel.hfa concurrency/monitor.hfa \
     247        concurrency/mutex.hfa concurrency/invoke.h
    250248HEADERS = $(nobase_cfa_include_HEADERS)
    251249am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
     
    467465
    468466#----------------------------------------------------------------------------------------------------------------
    469 @BUILDLIB_TRUE@headers_nosrc = bitmanip.hfa exception.hfa math.hfa gmp.hfa time_t.hfa clock.hfa \
    470 @BUILDLIB_TRUE@         bits/align.hfa bits/containers.hfa bits/defs.hfa bits/debug.hfa bits/locks.hfa containers/list.hfa containers/stackLockFree.hfa
     467@BUILDLIB_TRUE@headers_nosrc = bitmanip.hfa math.hfa gmp.hfa time_t.hfa clock.hfa \
     468@BUILDLIB_TRUE@         bits/align.hfa bits/containers.hfa bits/defs.hfa bits/debug.hfa bits/locks.hfa containers/list.hfa
    471469
    472470@BUILDLIB_FALSE@headers =
    473 @BUILDLIB_TRUE@headers = common.hfa fstream.hfa heap.hfa iostream.hfa iterator.hfa limits.hfa rational.hfa \
    474 @BUILDLIB_TRUE@         time.hfa stdlib.hfa memory.hfa \
     471@BUILDLIB_TRUE@headers = fstream.hfa iostream.hfa iterator.hfa limits.hfa rational.hfa time.hfa stdlib.hfa common.hfa \
    475472@BUILDLIB_TRUE@         containers/maybe.hfa containers/pair.hfa containers/result.hfa containers/vector.hfa
    476473
    477474@BUILDLIB_FALSE@libsrc =
    478 @BUILDLIB_TRUE@libsrc = startup.cfa interpose.cfa bits/debug.cfa assert.cfa exception.c virtual.c ${headers:.hfa=.cfa}
     475@BUILDLIB_TRUE@libsrc = startup.cfa interpose.cfa bits/debug.cfa assert.cfa exception.c virtual.c heap.cfa ${headers:.hfa=.cfa}
    479476@BUILDLIB_FALSE@thread_headers_nosrc =
    480477
  • libcfa/src/bitmanip.hfa

    r97392b69 ra5873bd  
    1111// Created On       : Sat Mar 14 18:12:27 2020
    1212// Last Modified By : Peter A. Buhr
    13 // Last Modified On : Tue Jun  9 15:14:04 2020
    14 // Update Count     : 123
     13// Last Modified On : Sun Apr 19 22:29:58 2020
     14// Update Count     : 121
    1515//
    1616
     
    4848
    4949        // Count all 0 bits.
    50         unsigned int all0s( unsigned char n ) { return __builtin_popcount( (typeof(n))~n ); }
    51         unsigned int all0s( unsigned short int n ) { return __builtin_popcount( (typeof(n))~n ); }
    52         unsigned int all0s( unsigned int n ) { return __builtin_popcount( ~n ); }
    53         unsigned int all0s( unsigned long int n ) { return __builtin_popcountl( ~n ); }
    54         unsigned int all0s( unsigned long long int n ) { return __builtin_popcountll( ~n ); }
     50        unsigned int all0s( unsigned char n ) { return __bitsizeof(n) - __builtin_popcount( n ); }
     51        unsigned int all0s( unsigned short int n ) { return __bitsizeof(n) - __builtin_popcount( n ); }
     52        unsigned int all0s( unsigned int n ) { return __bitsizeof(n) - __builtin_popcount( n ); }
     53        unsigned int all0s( unsigned long int n ) { return __bitsizeof(n) - __builtin_popcountl( n ); }
     54        unsigned int all0s( unsigned long long int n ) { return __bitsizeof(n) - __builtin_popcountll( n ); }
    5555
    5656        // Find least significiant zero bit. (ffs)
  • libcfa/src/concurrency/coroutine.cfa

    r97392b69 ra5873bd  
    1010// Created On       : Mon Nov 28 12:27:26 2016
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Tue May 26 22:06:09 2020
    13 // Update Count     : 21
     12// Last Modified On : Tue Feb  4 12:29:25 2020
     13// Update Count     : 16
    1414//
    1515
     
    1818#include "coroutine.hfa"
    1919
     20extern "C" {
    2021#include <stddef.h>
    2122#include <malloc.h>
     
    2324#include <string.h>
    2425#include <unistd.h>
    25 #include <sys/mman.h>                                                                   // mprotect
    26 extern "C" {
    27 // use this define to make unwind.h play nice, definitely a hack
     26// use this define to make unwind.h play nice, definetely a hack
    2827#define HIDE_EXPORTS
    2928#include <unwind.h>
    3029#undef HIDE_EXPORTS
     30#include <sys/mman.h>
    3131}
    3232
  • libcfa/src/concurrency/kernel.cfa

    r97392b69 ra5873bd  
    1010// Created On       : Tue Jan 17 12:27:26 2017
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Tue May 26 22:05:19 2020
    13 // Update Count     : 59
     12// Last Modified On : Tue Feb  4 13:03:15 2020
     13// Update Count     : 58
    1414//
    1515
     
    2121#include <errno.h>
    2222#include <string.h>
     23extern "C" {
    2324#include <stdio.h>
    2425#include <fenv.h>
     26#include <sys/resource.h>
    2527#include <signal.h>
    2628#include <unistd.h>
    2729#include <limits.h>                                                                             // PTHREAD_STACK_MIN
    2830#include <sys/mman.h>                                                                   // mprotect
    29 extern "C" {
    30 #include <sys/resource.h>
    3131}
    3232
  • libcfa/src/containers/list.hfa

    r97392b69 ra5873bd  
    118118        Telem& $tempcv_n2e(Tnode &);
    119119        Tnode& $tempcv_e2n(Telem &);
    120 
    121         Telem& ?`next(Tnode &);
    122         Telem& ?`prev(Tnode &);
    123120};
    124121
  • libcfa/src/executor.cfa

    r97392b69 ra5873bd  
    44// buffer.
    55
     6#include <containers/list.hfa>
    67#include <thread.hfa>
    7 #include <containers/list.hfa>
     8#include <stdio.h>
    89
    9 forall( dtype T | $dlistable(T, T) ) {
    10         monitor Buffer {                                                                        // unbounded buffer
    11                 dlist( T, T ) queue;                                                    // unbounded list of work requests
    12                 condition delay;
    13         }; // Buffer
    14 
    15         void insert( Buffer(T) & mutex buf, T * elem ) with(buf) {
    16                 dlist( T, T ) * qptr = &queue;                                  // workaround https://cforall.uwaterloo.ca/trac/ticket/166
    17                 insert_last( *qptr, *elem );                                    // insert element into buffer
    18                 signal( delay );                                                                // restart
    19         } // insert
    20 
    21         T * remove( Buffer(T) & mutex buf ) with(buf) {
    22                 dlist( T, T ) * qptr = &queue;                                  // workaround https://cforall.uwaterloo.ca/trac/ticket/166
    23                 // if ( (*qptr)`is_empty ) wait( delay );                       // no request to process ? => wait
    24           if ( (*qptr)`is_empty ) return 0p;                            // no request to process ? => wait
    25                 return &pop_first( *qptr );
    26         } // remove
    27 } // forall
    28 
    29 struct WRequest {                                                                               // client request, no return
    30         void (* action)( void );
    31         DLISTED_MGD_IMPL_IN(WRequest)
     10struct WRequest {                                       // client request, no return
     11    void (* action)( void );
     12    DLISTED_MGD_IMPL_IN(WRequest)
    3213}; // WRequest
    3314DLISTED_MGD_IMPL_OUT(WRequest)
     
    3819void doit( WRequest & req ) { req.action(); }
    3920
    40 // Each worker has its own set (when requests buffers > workers) of work buffers to reduce contention between client
    41 // and server, where work requests arrive and are distributed into buffers in a roughly round-robin order.
     21monitor WRBuffer {                                      // unbounded buffer
     22    dlist( WRequest, WRequest ) queue;                  // unbounded list of work requests
     23    condition delay;
     24}; // WRBuffer
     25
     26void insert( WRBuffer & mutex buf, WRequest * elem ) with(buf) {
     27    insert_last( queue, *elem );                        // insert element into buffer
     28    signal( delay );                                    // restart
     29} // insert
     30
     31WRequest * remove( WRBuffer & mutex buf ) with(buf) {
     32    if ( queue`is_empty ) wait( delay );                // no request to process ? => wait
     33    return & pop_first( queue );
     34} // remove
     35
     36// Each worker has its own work buffer to reduce contention between client and server. Hence, work requests arrive and
     37// are distributed into buffers in a roughly round-robin order.
    4238
    4339thread Worker {
    44         Buffer(WRequest) * requests;
    45         WRequest * request;
    46         unsigned int start, range;
     40    WRBuffer * requests;
     41    unsigned int start, range;
    4742}; // Worker
    4843
    4944void main( Worker & w ) with(w) {
    50         for ( int i = 0;; i = (i + 1) % range ) {
    51                 request = remove( requests[i + start] );
    52           if ( ! request ) { yield(); continue; }
    53           if ( stop( *request ) ) break;
    54                 doit( *request );
    55                 delete( request );
    56         } // for
     45    for ( int i = 0;; i = (i + 1) % range ) {
     46        WRequest * request = remove( requests[i + start] );
     47      if ( ! request ) { yield(); continue; }
     48      if ( stop( *request ) ) break;
     49        doit( *request );
     50        delete( request );
     51    } // for
    5752} // Worker::main
    5853
    59 void ?{}( Worker & worker, cluster * wc, Buffer(WRequest) * requests, unsigned int start, unsigned int range ) {
    60         ((thread &)worker){ *wc };
    61         worker.[requests, request, start, range] = [requests, 0p, start, range];
     54void ?{}( Worker & worker, cluster * wc, WRBuffer * requests, unsigned int start, unsigned int range ) {
     55    (*get_thread(worker)){ *wc };                       // create on given cluster
     56    worker.[requests, start, range] = [requests, start, range];
    6257} // ?{}
    6358
    64 WRequest * current_request( Worker & worker ) { return worker.request; }
    65 
    6659struct Executor {
    67         cluster * cluster;                                                                      // if workers execute on separate cluster
    68         processor ** processors;                                                        // array of virtual processors adding parallelism for workers
    69         Buffer(WRequest) * requests;                                            // list of work requests
    70         Worker ** workers;                                                                      // array of workers executing work requests
    71         unsigned int nprocessors, nworkers, nrqueues;           // number of processors/threads/request queues
    72         bool sepClus;                                                                           // use same or separate cluster for executor
    73         unsigned int next;                                                                      // demultiplexed across worker buffers
     60    cluster * cluster;                                  // if workers execute on separate cluster
     61    processor ** processors;                            // array of virtual processors adding parallelism for workers
     62    WRBuffer * requests;                                // list of work requests
     63    Worker ** workers;                                  // array of workers executing work requests
     64    unsigned int nprocessors, nworkers, nmailboxes;     // number of mailboxes/workers/processor tasks
     65    bool sepClus;                                       // use same or separate cluster for executor
    7466}; // Executor
    7567
     68static thread_local unsigned int next;                  // demultiplexed across worker buffers
    7669unsigned int tickets( Executor & ex ) with(ex) {
    77         //return uFetchAdd( next, 1 ) % nrqueues;
    78         return next++ % nrqueues;                                                       // no locking, interference randomizes
     70    //return uFetchAdd( next, 1 ) % nmailboxes;
     71    return next++ % nmailboxes;                         // no locking, interference randomizes
    7972} // tickets
    8073
    81 void ?{}( Executor & ex, unsigned int np, unsigned int nw, unsigned int nr, bool sc = false ) with(ex) {
    82         [nprocessors, nworkers, nrqueues, sepClus] = [np, nw, nr, sc];
    83         assert( nrqueues >= nworkers );
    84         cluster = sepClus ? new( "Executor" ) : active_cluster();
    85         processors = aalloc( nprocessors );
    86         requests = anew( nrqueues );
    87         workers = aalloc( nworkers );
     74void ?{}( Executor & ex, unsigned int np, unsigned int nw, unsigned int nm, bool sc = false ) with(ex) {
     75    [nprocessors, nworkers, nmailboxes, sepClus] = [np, nw, nm, sc];
     76    assert( nmailboxes >= nworkers );
     77    cluster = sepClus ? new( "Executor" ) : active_cluster();
     78    processors = (processor **)anew( nprocessors );
     79    requests = (WRBuffer *)anew( nmailboxes );
     80    workers = (Worker **)anew( nworkers );
    8881
    89         for ( i; nprocessors ) {
    90                 processors[i] = new( *cluster );
    91         } // for
     82    for ( i; nprocessors ) {
     83        processors[ i ] = new( *cluster );
     84    } // for
    9285
    93         unsigned int reqPerWorker = nrqueues / nworkers, extras = nrqueues % nworkers;
    94 //      for ( unsigned int i = 0, start = 0, range; i < nworkers; i += 1, start += range ) {
    95     for ( i; nworkers : start; 0u ~ @ ~ range : range; ) {
    96             range = reqPerWorker + ( i < extras ? 1 : 0 );
    97                 workers[i] = new( cluster, requests, start, range );
    98         } // for
     86    unsigned int reqPerWorker = nmailboxes / nworkers, extras = nmailboxes % nworkers;
     87    for ( unsigned int i = 0, step = 0; i < nworkers; i += 1, step += reqPerWorker + ( i < extras ? 1 : 0 ) ) {
     88        workers[ i ] = new( cluster, requests, step, reqPerWorker + ( i < extras ? 1 : 0 ) );
     89    } // for
    9990} // ?{}
    10091
    10192void ?{}( Executor & ex, unsigned int nprocessors, unsigned int nworkers, bool sepClus = false ) {
    102         ex{ nprocessors, nworkers, nworkers, sepClus };
     93    ex{ nprocessors, nworkers, nworkers, sepClus };
    10394}
    10495void ?{}( Executor & ex, unsigned int nprocessors, bool sepClus = false ) {
    105         ex{ nprocessors, nprocessors, nprocessors, sepClus };
     96    ex{ nprocessors, nprocessors, nprocessors, sepClus };
    10697}
    107 void ?{}( Executor & ex ) {                                                             // special for current cluster, no processors added
    108         ex{ 0, active_cluster()->nprocessors, false };
     98void ?{}( Executor & ex ) {                             // special for current cluster
     99    ex{ 0, active_cluster()->nprocessors, false };
    109100}
    110101void ^?{}( Executor & ex ) with(ex) {
    111         // Add one sentinel per worker to stop them. Since in destructor, no new external work should be queued.  Cannot
    112         // combine next two loops and only have a single sentinel because workers arrive in arbitrary order, so worker1 may
    113         // take the single sentinel while waiting for worker 0 to end.
     102    // Add one sentinel per worker to stop them. Since in destructor, no new work should be queued.  Cannot combine next
     103    // two loops and only have a single sentinel because workers arrive in arbitrary order, so worker1 may take the
     104    // single sentinel while waiting for worker 0 to end.
    114105
    115         WRequest sentinel[nworkers];
    116         unsigned int reqPerWorker = nrqueues / nworkers;
    117         for ( unsigned int i = 0, step = 0; i < nworkers; i += 1, step += reqPerWorker ) {
    118                 insert( requests[step], &sentinel[i] );                 // force eventually termination
    119         } // for
    120         for ( i; nworkers ) {
    121                 delete( workers[i] );
    122         } // for
    123         for ( i; nprocessors ) {
    124                 delete( processors[i] );
    125         } // for
     106    WRequest sentinel[nworkers];
     107    unsigned int reqPerWorker = nmailboxes / nworkers;
     108    for ( unsigned int i = 0, step = 0; i < nworkers; i += 1, step += reqPerWorker ) {
     109        insert( requests[step], &sentinel[i] );         // force eventually termination
     110    } // for
     111    for ( i; nworkers ) {
     112        delete( workers[ i ] );
     113    } // for
     114    for ( i; nprocessors ) {
     115        delete( processors[ i ] );
     116    } // for
    126117
    127         free( workers );
    128 //      adelete( nrqueues, requests );
    129         for ( i; nrqueues ) ^?{}( requests[i] );                        // FIX ME: problem with resolver
    130         free( requests );
    131         free( processors );
    132         if ( sepClus ) { delete( cluster ); }
     118    delete( workers );
     119    delete( requests );
     120    delete( processors );
     121    if ( sepClus ) { delete( cluster ); }
    133122} // ^?{}
    134123
    135124void send( Executor & ex, void (* action)( void ) ) {   // asynchronous call, no return value
    136         WRequest * node = new( action );
    137         insert( ex.requests[tickets( ex )], node );
     125    WRequest * node = new( action );
     126    insert( ex.requests[tickets( ex )], node );
    138127} // send
    139 
    140128
    141129int counter = 0;
    142130
    143 void work( void ) {
    144         __atomic_add_fetch( &counter, 1, __ATOMIC_SEQ_CST );
    145         // fprintf( stderr, "workie\n" );
     131void workie( void ) {
     132    __atomic_add_fetch( &counter, 1, __ATOMIC_SEQ_CST );
     133//    fprintf( stderr, "workie\n" );
    146134}
    147135
    148 int main( int argc, char * argv[] ) {
    149         int times = 1_000_000;
    150         if ( argc == 2 ) times = atoi( argv[1] );
    151         processor p[7];
    152         {
    153                 Executor exector;
    154                 for ( i; times ) {
    155                         send( exector, work );
    156                         if ( i % 100 == 0 ) yield();
    157                 } // for
    158         }
    159         printf( "%d\n", counter );
     136int main() {
     137    {
     138        Executor exector;
     139        for ( i; 3000 ) {
     140            send( exector, workie );
     141            if ( i % 100 == 0 ) {
     142//              fprintf( stderr, "%d\n", i );
     143                yield();
     144            }
     145        } // for
     146    }
     147    printf( "%d\n", counter );
    160148}
    161149
    162150// Local Variables: //
    163 // tab-width: 4" //
    164151// compile-command: "cfa executor.cfa" //
    165152// End: //
  • libcfa/src/heap.cfa

    r97392b69 ra5873bd  
    1010// Created On       : Tue Dec 19 21:58:35 2017
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Wed May 27 15:08:49 2020
    13 // Update Count     : 770
     12// Last Modified On : Sun May 17 20:58:17 2020
     13// Update Count     : 762
    1414//
    1515
     
    2020#include <string.h>                                                                             // memset, memcpy
    2121#include <limits.h>                                                                             // ULONG_MAX
    22 #include <malloc.h>                                                                             // memalign, malloc_usable_size
     22extern "C" {
    2323#include <sys/mman.h>                                                                   // mmap, munmap
     24} // extern "C"
    2425
    2526#include "bits/align.hfa"                                                               // libPow2
     
    2829#include "startup.hfa"                                                                  // STARTUP_PRIORITY_MEMORY
    2930//#include "stdlib.hfa"                                                                 // bsearchl
     31#include "malloc.h"
    3032#include "bitmanip.hfa"                                                                 // ceiling
    3133
  • libcfa/src/stdhdr/malloc.h

    r97392b69 ra5873bd  
    1010// Created On       : Thu Jul 20 15:58:16 2017
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Wed May 27 14:13:14 2020
    13 // Update Count     : 18
     12// Last Modified On : Thu Apr 16 22:44:06 2020
     13// Update Count     : 13
    1414//
     15
     16
     17size_t default_mmap_start();                                                    // CFA extras
     18size_t default_heap_expansion();
     19
     20bool traceHeap();
     21bool traceHeapOn();
     22bool traceHeapOff();
     23
     24bool traceHeapTerm();
     25bool traceHeapTermOn();
     26bool traceHeapTermOff();
     27
     28bool checkFree();
     29bool checkFreeOn();
     30bool checkFreeOff();
     31
     32extern "C" {
     33void * aalloc( size_t noOfElems, size_t elemSize );
     34void * amemalign( size_t alignment, size_t noOfElems, size_t elemSize );
     35void * cmemalign( size_t alignment, size_t noOfElems, size_t elemSize );
     36size_t malloc_alignment( void * );
     37bool malloc_zero_fill( void * );
     38size_t malloc_size( void * );
     39int malloc_stats_fd( int fd );
     40} // extern "C"
    1541
    1642extern "C" {
    1743#include_next <malloc.h>                                                                // has internal check for multiple expansion
    1844} // extern "C"
    19 
    20 #include <heap.hfa>
    2145
    2246// Local Variables: //
  • libcfa/src/stdlib.cfa

    r97392b69 ra5873bd  
    99// Author           : Peter A. Buhr
    1010// Created On       : Thu Jan 28 17:10:29 2016
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Tue Jun  2 16:46:00 2020
    13 // Update Count     : 500
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Thu Apr 16 22:43:33 2020
     13// Update Count     : 498
    1414//
    1515
     
    7878} // new
    7979
    80 forall( dtype T | { void ^?{}( T & ); } )
     80forall( dtype T | sized(T) | { void ^?{}( T & ); } )
    8181void delete( T * ptr ) {
    8282        if ( ptr ) {                                                                            // ignore null
     
    8686} // delete
    8787
    88 forall( dtype T, ttype Params | { void ^?{}( T & ); void delete( Params ); } )
     88forall( dtype T, ttype Params | sized(T) | { void ^?{}( T & ); void delete( Params ); } )
    8989void delete( T * ptr, Params rest ) {
    90         delete( ptr );
     90        if ( ptr ) {                                                                            // ignore null
     91                ^(*ptr){};                                                                              // run destructor
     92                free( ptr );
     93        } // if
    9194        delete( rest );
    9295} // delete
     
    274277extern "C" {                                                                                    // override C version
    275278        void srandom( unsigned int seed ) { srand48( (long int)seed ); }
    276         long int random( void ) { return mrand48(); }           // GENERATES POSITIVE AND NEGATIVE VALUES
     279        long int random( void ) { return mrand48(); }
    277280} // extern "C"
    278281
  • libcfa/src/stdlib.hfa

    r97392b69 ra5873bd  
    99// Author           : Peter A. Buhr
    1010// Created On       : Thu Jan 28 17:12:35 2016
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Tue Jun  2 16:47:00 2020
    13 // Update Count     : 451
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Wed May 13 17:23:51 2020
     13// Update Count     : 435
    1414//
    1515
     
    2020
    2121#include <stdlib.h>                                                                             // *alloc, strto*, ato*
    22 #include <heap.hfa>
    2322
    2423// Reduce includes by explicitly defining these routines.
    2524extern "C" {
    26         void * memalign( size_t alignment, size_t size );       // malloc.h
    27         void * pvalloc( size_t size );                                          // malloc.h
     25        void * aalloc( size_t dim, size_t elemSize );           // CFA heap
     26        void * resize( void * oaddr, size_t size );                     // CFA heap
     27        void * memalign( size_t align, size_t size );           // malloc.h
     28        void * amemalign( size_t align, size_t dim, size_t elemSize ); // CFA heap
     29        void * cmemalign( size_t align, size_t noOfElems, size_t elemSize ); // CFA heap
     30        size_t malloc_size( void * addr );                                      // CFA heap
     31        size_t malloc_usable_size( void * ptr );                        // malloc.h
    2832        void * memset( void * dest, int fill, size_t size ); // string.h
    2933        void * memcpy( void * dest, const void * src, size_t size ); // string.h
    3034} // extern "C"
     35
     36void * resize( void * oaddr, size_t nalign, size_t size ); // CFA heap
     37void * realloc( void * oaddr, size_t nalign, size_t size ); // CFA heap
    3138
    3239//---------------------------------------
     
    8491                return posix_memalign( (void **)ptr, align, sizeof(T) ); // C posix_memalign
    8592        } // posix_memalign
    86 
    87         T * valloc( void ) {
    88                 return (T *)valloc( sizeof(T) );                                // C valloc
    89         } // valloc
    90 
    91         T * pvalloc( void ) {
    92                 return (T *)pvalloc( sizeof(T) );                               // C pvalloc
    93         } // pvalloc
    9493} // distribution
    9594
     
    229228// Cforall allocation/deallocation and constructor/destructor, non-array types
    230229forall( dtype T | sized(T), ttype Params | { void ?{}( T &, Params ); } ) T * new( Params p );
    231 forall( dtype T | { void ^?{}( T & ); } ) void delete( T * ptr );
    232 forall( dtype T, ttype Params | { void ^?{}( T & ); void delete( Params ); } ) void delete( T * ptr, Params rest );
     230forall( dtype T | sized(T) | { void ^?{}( T & ); } ) void delete( T * ptr );
     231forall( dtype T, ttype Params | sized(T) | { void ^?{}( T & ); void delete( Params ); } ) void delete( T * ptr, Params rest );
    233232
    234233// Cforall allocation/deallocation and constructor/destructor, array types
     
    301300extern "C" {                                                                                    // override C version
    302301        void srandom( unsigned int seed );
    303         long int random( void );                                                        // GENERATES POSITIVE AND NEGATIVE VALUES
    304         // For positive values, use unsigned int, e.g., unsigned int r = random() % 100U;
     302        long int random( void );
    305303} // extern "C"
    306304
     
    309307        long int random( long int u ) { if ( u < 0 ) return random( u, 0 ); else return random( 0, u ); } // [0,u)
    310308        unsigned long int random( void ) { return lrand48(); }
     309        unsigned long int random( unsigned long int l, unsigned long int u ) { if ( u < l ) [u, l] = [l, u]; return lrand48() % (u - l) + l; } // [l,u)
    311310        unsigned long int random( unsigned long int u ) { return lrand48() % u; } // [0,u)
    312         unsigned long int random( unsigned long int l, unsigned long int u ) { if ( u < l ) [u, l] = [l, u]; return lrand48() % (u - l) + l; } // [l,u)
    313311
    314312        char random( void ) { return (unsigned long int)random(); }
  • src/ControlStruct/ExceptTranslate.cc

    r97392b69 ra5873bd  
    1010// Created On       : Wed Jun 14 16:49:00 2017
    1111// Last Modified By : Andrew Beach
    12 // Last Modified On : Tue May 26 10:56:00 2020
    13 // Update Count     : 16
     12// Last Modified On : Thr May 21 13:18:00 2020
     13// Update Count     : 15
    1414//
    1515
     
    107107                        nameOf( terminate_handler_except ),
    108108                        new ConstantExpr( Constant::null(
    109                                 terminate_handler_except->get_type()->clone()
     109                                //new PointerType(
     110                                //      noQualifiers,
     111                                        terminate_handler_except->get_type()->clone()
     112                                //      )
    110113                                ) )
    111114                        ) ) );
     
    134137                ObjectDecl * decl = dynamic_cast<ObjectDecl *>( catchStmt->get_decl() );
    135138                // Also checking the type would be nice.
    136                 if ( !decl || !dynamic_cast<PointerType *>( decl->type ) ) {
    137                         std::string kind = (CatchStmt::Terminate == catchStmt->kind) ? "catch" : "catchResume";
    138                         SemanticError( catchStmt->location, kind + " must have pointer to an exception type" );
     139                if ( decl ) {
     140                        // Pass.
     141                } else if ( CatchStmt::Terminate == catchStmt->get_kind() ) {
     142                        SemanticError(catchStmt->location, "catch must have exception type");
     143                } else {
     144                        SemanticError(catchStmt->location, "catchResume must have exception type");
    139145                }
    140146
     
    226232
    227233                void premutate( StructDecl *structDecl );
     234                Statement * postmutate( ThrowStmt *throwStmt );
    228235                Statement * postmutate( TryStmt *tryStmt );
    229236        };
     
    614621        }
    615622
     623        Statement * TryMutatorCore::postmutate( ThrowStmt * ) {
     624                // All throws should be removed by this point.
     625                assert( false );
     626        }
     627
    616628        Statement * TryMutatorCore::postmutate( TryStmt *tryStmt ) {
    617629                assert( except_decl );
  • src/ControlStruct/ExceptTranslate.h

    r97392b69 ra5873bd  
    2929        /* Replaces all try blocks (and their many clauses) with function definitions and calls.
    3030         * This uses the exception built-ins to produce typed output and should take place after
    31          * the resolver. It also produces virtual casts and should happen before they are expanded.
     31         * the resolver.
    3232         */
    3333}
  • src/Parser/parser.yy

    r97392b69 ra5873bd  
    1010// Created On       : Sat Sep  1 20:22:55 2001
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu May 28 12:11:45 2020
    13 // Update Count     : 4500
     12// Last Modified On : Mon Apr 27 12:25:42 2020
     13// Update Count     : 4483
    1414//
    1515
     
    329329%type<en> conditional_expression                constant_expression                     assignment_expression           assignment_expression_opt
    330330%type<en> comma_expression                              comma_expression_opt
    331 %type<en> argument_expression_list_opt          argument_expression                     default_initialize_opt
     331%type<en> argument_expression_list              argument_expression                     default_initialize_opt
    332332%type<ifctl> if_control_expression
    333333%type<fctl> for_control_expression              for_control_expression_list
     
    624624                // equivalent to the old x[i,j].
    625625                { $$ = new ExpressionNode( build_binary_val( OperKinds::Index, $1, $3 ) ); }
    626         | postfix_expression '{' argument_expression_list_opt '}' // CFA, constructor call
     626        | postfix_expression '{' argument_expression_list '}' // CFA, constructor call
    627627                {
    628628                        Token fn;
     
    630630                        $$ = new ExpressionNode( new ConstructorExpr( build_func( new ExpressionNode( build_varref( fn ) ), (ExpressionNode *)( $1 )->set_last( $3 ) ) ) );
    631631                }
    632         | postfix_expression '(' argument_expression_list_opt ')'
     632        | postfix_expression '(' argument_expression_list ')'
    633633                { $$ = new ExpressionNode( build_func( $1, $3 ) ); }
    634634        | postfix_expression '`' identifier                                     // CFA, postfix call
     
    662662        | '(' type_no_function ')' '@' '{' initializer_list_opt comma_opt '}' // CFA, explicit C compound-literal
    663663                { $$ = new ExpressionNode( build_compoundLiteral( $2, (new InitializerNode( $6, true ))->set_maybeConstructed( false ) ) ); }
    664         | '^' primary_expression '{' argument_expression_list_opt '}' // CFA, destructor call
     664        | '^' primary_expression '{' argument_expression_list '}' // CFA, destructor call
    665665                {
    666666                        Token fn;
     
    670670        ;
    671671
    672 argument_expression_list_opt:
     672argument_expression_list:
    673673        // empty
    674674                { $$ = nullptr; }
    675675        | argument_expression
    676         | argument_expression_list_opt ',' argument_expression
     676        | argument_expression_list ',' argument_expression
    677677                { $$ = (ExpressionNode *)($1->set_last( $3 )); }
    678678        ;
     
    11961196                { $$ = forCtrl( $1, new string( DeclarationNode::anonymous.newName() ), new ExpressionNode( build_constantInteger( *new string( "0" ) ) ),
    11971197                                                OperKinds::LThan, $1->clone(), new ExpressionNode( build_constantInteger( *new string( "1" ) ) ) ); }
    1198         | '=' comma_expression                                                          // CFA
     1198        | '=' comma_expression                                                                  // CFA
    11991199                { $$ = forCtrl( $2, new string( DeclarationNode::anonymous.newName() ), new ExpressionNode( build_constantInteger( *new string( "0" ) ) ),
    12001200                                                OperKinds::LEThan, $2->clone(), new ExpressionNode( build_constantInteger( *new string( "1" ) ) ) ); }
     
    12031203        | comma_expression inclexcl comma_expression '~' comma_expression // CFA
    12041204                { $$ = forCtrl( $1, new string( DeclarationNode::anonymous.newName() ), $1->clone(), $2, $3, $5 ); }
    1205         | comma_expression ';'                                                          // CFA
    1206                 { $$ = forCtrl( new ExpressionNode( build_constantInteger( *new string( "0u" ) ) ), $1, nullptr, OperKinds::LThan, nullptr, nullptr ); }
    12071205        | comma_expression ';' comma_expression                         // CFA
    12081206                { $$ = forCtrl( $3, $1, new ExpressionNode( build_constantInteger( *new string( "0" ) ) ),
    12091207                                                OperKinds::LThan, $3->clone(), new ExpressionNode( build_constantInteger( *new string( "1" ) ) ) ); }
    1210         | comma_expression ';' '=' comma_expression                     // CFA
     1208        | comma_expression ';' '=' comma_expression                             // CFA
    12111209                { $$ = forCtrl( $4, $1, new ExpressionNode( build_constantInteger( *new string( "0" ) ) ),
    12121210                                                OperKinds::LEThan, $4->clone(), new ExpressionNode( build_constantInteger( *new string( "1" ) ) ) ); }
     
    13061304// If MUTEX becomes a general qualifier, there are shift/reduce conflicts, so change syntax to "with mutex".
    13071305mutex_statement:
    1308         MUTEX '(' argument_expression_list_opt ')' statement
     1306        MUTEX '(' argument_expression_list ')' statement
    13091307                { SemanticError( yylloc, "Mutex statement is currently unimplemented." ); $$ = nullptr; }
    13101308        ;
     
    13231321        WAITFOR '(' cast_expression ')'
    13241322                { $$ = $3; }
    1325 //      | WAITFOR '(' cast_expression ',' argument_expression_list_opt ')'
     1323//      | WAITFOR '(' cast_expression ',' argument_expression_list ')'
    13261324//              { $$ = (ExpressionNode *)$3->set_last( $5 ); }
    1327         | WAITFOR '(' cast_expression_list ':' argument_expression_list_opt ')'
     1325        | WAITFOR '(' cast_expression_list ':' argument_expression_list ')'
    13281326                { $$ = (ExpressionNode *)($3->set_last( $5 )); }
    13291327        ;
     
    13321330        cast_expression
    13331331        | cast_expression_list ',' cast_expression
    1334                 // { $$ = (ExpressionNode *)($1->set_last( $3 )); }
    1335                 { SemanticError( yylloc, "List of mutex member is currently unimplemented." ); $$ = nullptr; }
     1332                { $$ = (ExpressionNode *)($1->set_last( $3 )); }
    13361333        ;
    13371334
     
    20982095
    20992096aggregate_control:                                                                              // CFA
    2100         MONITOR
    2101                 { yyy = true; $$ = AggregateDecl::Monitor; }
    2102         | MUTEX STRUCT
    2103                 { yyy = true; $$ = AggregateDecl::Monitor; }
    2104         | GENERATOR
     2097        GENERATOR
    21052098                { yyy = true; $$ = AggregateDecl::Generator; }
    2106         | MUTEX GENERATOR
     2099        | MONITOR GENERATOR
    21072100                { SemanticError( yylloc, "monitor generator is currently unimplemented." ); $$ = AggregateDecl::NoAggregate; }
    21082101        | COROUTINE
    21092102                { yyy = true; $$ = AggregateDecl::Coroutine; }
    2110         | MUTEX COROUTINE
     2103        | MONITOR
     2104                { yyy = true; $$ = AggregateDecl::Monitor; }
     2105        | MONITOR COROUTINE
    21112106                { SemanticError( yylloc, "monitor coroutine is currently unimplemented." ); $$ = AggregateDecl::NoAggregate; }
    21122107        | THREAD
    21132108                { yyy = true; $$ = AggregateDecl::Thread; }
    2114         | MUTEX THREAD
     2109        | MONITOR THREAD
    21152110                { SemanticError( yylloc, "monitor thread is currently unimplemented." ); $$ = AggregateDecl::NoAggregate; }
    21162111        ;
     
    27792774        | attr_name
    27802775                { $$ = DeclarationNode::newAttribute( $1 ); }
    2781         | attr_name '(' argument_expression_list_opt ')'
     2776        | attr_name '(' argument_expression_list ')'
    27822777                { $$ = DeclarationNode::newAttribute( $1, $3 ); }
    27832778        ;
  • src/Virtual/ExpandCasts.cc

    r97392b69 ra5873bd  
    1010// Created On       : Mon Jul 24 13:59:00 2017
    1111// Last Modified By : Andrew Beach
    12 // Last Modified On : Tue May 26 14:37:00 2020
    13 // Update Count     : 2
     12// Last Modified On : Tus Aug  2 14:59:00 2017
     13// Update Count     : 1
    1414//
    1515
     
    111111        }
    112112
    113         // Better error locations for generated casts.
    114         static CodeLocation castLocation( VirtualCastExpr * castExpr ) {
    115                 if ( castExpr->location.isSet() ) {
    116                         return castExpr->location;
    117                 } else if ( castExpr->arg->location.isSet() ) {
    118                         return castExpr->arg->location;
    119                 } else if ( castExpr->result->location.isSet() ) {
    120                         return castExpr->result->location;
    121                 } else {
    122                         return CodeLocation();
    123                 }
    124         }
    125 
    126113        Expression * VirtualCastCore::postmutate( VirtualCastExpr * castExpr ) {
    127114                assertf( castExpr->get_result(), "Virtual Cast target not found before expansion." );
     
    130117                assert( pvt_decl );
    131118
    132                 // Get the base type of the pointer/reference.
    133                 Type * base;
    134                 Type * result_type = castExpr->result;
    135                 if ( PointerType * target = dynamic_cast<PointerType *>( result_type ) ) {
    136                         base = target->base;
    137                 } else if ( ReferenceType * target = dynamic_cast<ReferenceType *>( result_type ) ) {
    138                         base = target->base;
    139                 } else {
    140                         SemanticError( castLocation( castExpr ),
    141                                 "Virtual cast type must be a pointer or reference type." );
    142                 }
     119                // May only cast to a pointer or reference type.
     120                // A earlier validation should give a syntax error, this is
     121                // just to make sure errors don't creep during translation.
     122                // Move to helper with more detailed error messages.
     123                PointerType * target_type =
     124                        dynamic_cast<PointerType *>( castExpr->get_result() );
     125                assert( target_type );
    143126
    144                 StructInstType * target_struct = dynamic_cast<StructInstType *>( base );
    145                 if ( nullptr == target_struct ) {
    146                         SemanticError( castLocation( castExpr ),
    147                                 "Virtual cast type must refer to a structure type." );
    148                 }
     127                StructInstType * target_struct =
     128                        dynamic_cast<StructInstType *>( target_type->get_base() );
     129                assert( target_struct );
     130
    149131                StructDecl * target_decl = target_struct->get_baseStruct();
    150132
    151133                std::map<std::string, ObjectDecl *>::iterator found =
    152                         vtable_instances.find( get_vtable_inst_name( target_decl->get_name() ) );
     134                        vtable_instances.find(
     135                                get_vtable_inst_name( target_decl->get_name() ) );
    153136                if ( vtable_instances.end() == found ) {
    154                         SemanticError( castLocation( castExpr ),
    155                                 "Virtual cast type does not have a virtual table instance." );
     137                        assertf( false, "virtual table instance not found." );
    156138                }
    157139                ObjectDecl * table = found->second;
    158140
    159141                Expression * result = new CastExpr(
     142                        //new ApplicationExpr(
     143                                //new AddressExpr( new VariableExpr( vcast_decl ) ),
     144                                //new CastExpr( new VariableExpr( vcast_decl ),
     145                                //      new PointerType( noQualifiers,
     146                                //              vcast_decl->get_type()->clone()
     147                                //              )
     148                                //      ),
    160149                        new ApplicationExpr( VariableExpr::functionPointer( vcast_decl ), {
    161150                                        new CastExpr(
  • tests/.expect/copyfile.txt

    r97392b69 ra5873bd  
    1010// Created On       : Tue Jul 16 16:47:22 2019
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Jun  1 09:10:58 2020
    13 // Update Count     : 28
     12// Last Modified On : Wed Jul 17 18:04:44 2019
     13// Update Count     : 26
    1414//
    1515
     
    1818
    1919int main( int argc, char * argv[] ) {
    20         ifstream & in  = stdin;                                                         // default files
    21         ofstream & out = stdout;
     20        ifstream * in  = &stdin;                                                        // default files
     21        ofstream * out = &stdout;
    2222        try {
    2323                choose ( argc ) {
    2424                  case 2, 3:
    25                           &in = new( (const char *)argv[1] );           // open input file first as output creates file
    26                           if ( argc == 3 ) &out = new( (const char *)argv[2] ); // only open output if input opens as output created if nonexistent
     25                          in = new( (const char *)argv[1] );            // open input file first as output creates file
     26                          if ( argc == 3 ) out = new( (const char *)argv[2] ); // only open output if input opens as output created if nonexistent
    2727                  case 1: ;                                     // use default files
    2828                  default:
     
    3131
    3232                char ch;
    33                 out | nlOff;                                                                    // turn off auto newline
    34                 in  | nlOn;                                                                             // turn on reading newline
     33                *out | nlOff;                                                                   // turn off auto newline
     34                *in  | nlOn;                                                                    // turn on reading newline
    3535
    3636                for () {                                                                                // read all characters
    37                         in | ch;
    38                   if ( eof( in ) ) break;                                               // eof ?
    39                         out | ch;
     37                        *in | ch;
     38                  if ( eof( *in ) ) break;                                              // eof ?
     39                        *out | ch;
    4040                } // for
    4141        } finally {
    42                 if ( &in  != &stdin  ) delete( &in );                   // close file, do not delete stdin!
    43                 if ( &out != &stdout ) delete( &out );                  // close file, do not delete stdout!
     42                if ( in  != &stdin  ) delete( in );                             // close file, do not delete stdin!
     43                if ( out != &stdout ) delete( out );                    // close file, do not delete stdout!
    4444        } // try
    4545} // main
  • tests/.in/copyfile.txt

    r97392b69 ra5873bd  
    1010// Created On       : Tue Jul 16 16:47:22 2019
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Jun  1 09:10:58 2020
    13 // Update Count     : 28
     12// Last Modified On : Wed Jul 17 18:04:44 2019
     13// Update Count     : 26
    1414//
    1515
     
    1818
    1919int main( int argc, char * argv[] ) {
    20         ifstream & in  = stdin;                                                         // default files
    21         ofstream & out = stdout;
     20        ifstream * in  = &stdin;                                                        // default files
     21        ofstream * out = &stdout;
    2222        try {
    2323                choose ( argc ) {
    2424                  case 2, 3:
    25                           &in = new( (const char *)argv[1] );           // open input file first as output creates file
    26                           if ( argc == 3 ) &out = new( (const char *)argv[2] ); // only open output if input opens as output created if nonexistent
     25                          in = new( (const char *)argv[1] );            // open input file first as output creates file
     26                          if ( argc == 3 ) out = new( (const char *)argv[2] ); // only open output if input opens as output created if nonexistent
    2727                  case 1: ;                                     // use default files
    2828                  default:
     
    3131
    3232                char ch;
    33                 out | nlOff;                                                                    // turn off auto newline
    34                 in  | nlOn;                                                                             // turn on reading newline
     33                *out | nlOff;                                                                   // turn off auto newline
     34                *in  | nlOn;                                                                    // turn on reading newline
    3535
    3636                for () {                                                                                // read all characters
    37                         in | ch;
    38                   if ( eof( in ) ) break;                                               // eof ?
    39                         out | ch;
     37                        *in | ch;
     38                  if ( eof( *in ) ) break;                                              // eof ?
     39                        *out | ch;
    4040                } // for
    4141        } finally {
    42                 if ( &in  != &stdin  ) delete( &in );                   // close file, do not delete stdin!
    43                 if ( &out != &stdout ) delete( &out );                  // close file, do not delete stdout!
     42                if ( in  != &stdin  ) delete( in );                             // close file, do not delete stdin!
     43                if ( out != &stdout ) delete( out );                    // close file, do not delete stdout!
    4444        } // try
    4545} // main
  • tests/copyfile.cfa

    r97392b69 ra5873bd  
    1010// Created On       : Tue Jul 16 16:47:22 2019
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Jun  1 09:10:58 2020
    13 // Update Count     : 28
     12// Last Modified On : Wed Jul 17 18:04:44 2019
     13// Update Count     : 26
    1414//
    1515
     
    1818
    1919int main( int argc, char * argv[] ) {
    20         ifstream & in  = stdin;                                                         // default files
    21         ofstream & out = stdout;
     20        ifstream * in  = &stdin;                                                        // default files
     21        ofstream * out = &stdout;
    2222        try {
    2323                choose ( argc ) {
    2424                  case 2, 3:
    25                           &in = new( (const char *)argv[1] );           // open input file first as output creates file
    26                           if ( argc == 3 ) &out = new( (const char *)argv[2] ); // only open output if input opens as output created if nonexistent
     25                          in = new( (const char *)argv[1] );            // open input file first as output creates file
     26                          if ( argc == 3 ) out = new( (const char *)argv[2] ); // only open output if input opens as output created if nonexistent
    2727                  case 1: ;                                     // use default files
    2828                  default:
     
    3131
    3232                char ch;
    33                 out | nlOff;                                                                    // turn off auto newline
    34                 in  | nlOn;                                                                             // turn on reading newline
     33                *out | nlOff;                                                                   // turn off auto newline
     34                *in  | nlOn;                                                                    // turn on reading newline
    3535
    3636                for () {                                                                                // read all characters
    37                         in | ch;
    38                   if ( eof( in ) ) break;                                               // eof ?
    39                         out | ch;
     37                        *in | ch;
     38                  if ( eof( *in ) ) break;                                              // eof ?
     39                        *out | ch;
    4040                } // for
    4141        } finally {
    42                 if ( &in  != &stdin  ) delete( &in );                   // close file, do not delete stdin!
    43                 if ( &out != &stdout ) delete( &out );                  // close file, do not delete stdout!
     42                if ( in  != &stdin  ) delete( in );                             // close file, do not delete stdin!
     43                if ( out != &stdout ) delete( out );                    // close file, do not delete stdout!
    4444        } // try
    4545} // main
Note: See TracChangeset for help on using the changeset viewer.