Changeset cf966b5 for doc


Ignore:
Timestamp:
Nov 28, 2017, 3:52:01 PM (6 years ago)
Author:
Thierry Delisle <tdelisle@…>
Branches:
ADT, aaron-thesis, arm-eh, ast-experimental, cleanup-dtors, deferred_resn, demangler, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, pthread-emulation, qualifiedEnum, resolv-new, with_gc
Children:
6c2ba38
Parents:
f7a4f89
Message:

Results need to be updated but otherwise, tentative final draft

Location:
doc/proposals/concurrency
Files:
1 added
3 deleted
16 edited

Legend:

Unmodified
Added
Removed
  • doc/proposals/concurrency/.gitignore

    rf7a4f89 rcf966b5  
    1313build/*.ind
    1414build/*.ist
     15build/*.lof
    1516build/*.log
     17build/*.lol
     18build/*.lot
    1619build/*.out
    1720build/*.ps
  • doc/proposals/concurrency/Makefile

    rf7a4f89 rcf966b5  
    1212style/cfa-format \
    1313annex/glossary \
     14text/frontpgs \
    1415text/intro \
    1516text/basics \
     
    2021text/results \
    2122text/together \
    22 text/conclusion \
    2323text/future \
    24 text/acknowledge \
    2524}
    2625
  • doc/proposals/concurrency/annex/glossary.tex

    rf7a4f89 rcf966b5  
    44{name={callsite-locking}}
    55{
    6 Locking done by the calling routine. With this technique, a routine calling a monitor routine will aquire the monitor \emph{before} making the call to the actuall routine.
     6Locking done by the calling routine. With this technique, a routine calling a monitor routine aquires the monitor \emph{before} making the call to the actuall routine.
    77}
    88
     
    1010{name={entry-point-locking}}
    1111{
    12 Locking done by the called routine. With this technique, a monitor routine called by another routine will aquire the monitor \emph{after} entering the routine body but prior to any other code.
     12Locking done by the called routine. With this technique, a monitor routine called by another routine aquires the monitor \emph{after} entering the routine body but prior to any other code.
    1313}
    1414
     
    2222{name={multiple-acquisition}}
    2323{
    24 Any locking technique which allow any single thread to acquire a lock multiple times.
     24Any locking technique that allows a single thread to acquire the same lock multiple times.
    2525}
    2626
     
    3535{name={user-level thread}}
    3636{
    37 Threads created and managed inside user-space. Each thread has its own stack and its own thread of execution. User-level threads are insisible to the underlying operating system.
     37Threads created and managed inside user-space. Each thread has its own stack and its own thread of execution. User-level threads are invisible to the underlying operating system.
    3838
    3939\textit{Synonyms : User threads, Lightweight threads, Green threads, Virtual threads, Tasks.}
     
    5151{name={fiber}}
    5252{
    53 Fibers are non-preemptive user-level threads. They share most of the caracteristics of user-level threads except that they cannot be preempted by an other fiber.
     53Fibers are non-preemptive user-level threads. They share most of the caracteristics of user-level threads except that they cannot be preempted by another fiber.
    5454
    5555\textit{Synonyms : Tasks.}
     
    5959{name={job}}
    6060{
    61 Unit of work, often send to a thread pool or worker pool to be executed. Has neither its own stack or its own thread of execution.
     61Unit of work, often sent to a thread pool or worker pool to be executed. Has neither its own stack nor its own thread of execution.
    6262
    6363\textit{Synonyms : Tasks.}
     
    7575{name={cluster}}
    7676{
    77 TBD...
    78 
    79 \textit{Synonyms : None.}
    80 }
    81 
    82 \longnewglossaryentry{cfacpu}
    83 {name={processor}}
    84 {
    85 TBD...
     77A group of \gls{kthread} executed in isolation.
    8678
    8779\textit{Synonyms : None.}
     
    9183{name={thread}}
    9284{
    93 TBD...
     85User level threads that are the default in \CFA. Generally declared using the \code{thread} keyword.
    9486
    9587\textit{Synonyms : None.}
     
    9991{name={preemption}}
    10092{
    101 TBD...
     93Involuntary context switch imposed on threads at a specified rate.
    10294
    10395\textit{Synonyms : None.}
  • doc/proposals/concurrency/annex/local.bib

    rf7a4f89 rcf966b5  
    3838        keywords        = {Intel, TBB},
    3939        title   = {Intel Thread Building Blocks},
     40        note            = "\url{https://www.threadingbuildingblocks.org/}"
    4041}
    4142
     
    7475        title   = {TwoHardThings},
    7576        author  = {Martin Fowler},
    76         address = {https://martinfowler.com/bliki/TwoHardThings.html},
     77        howpublished= "\url{https://martinfowler.com/bliki/TwoHardThings.html}",
    7778        year            = 2009
    7879}
     
    8889}
    8990
    90 @misc{affinityLinux,
     91@book{Herlihy93,
     92        title={Transactional memory: Architectural support for lock-free data structures},
     93        author={Herlihy, Maurice and Moss, J Eliot B},
     94        volume={21},
     95        number={2},
     96        year={1993},
     97        publisher={ACM}
     98}
     99
     100@manual{affinityLinux,
    91101        title           = "{Linux man page - sched\_setaffinity(2)}"
    92102}
    93103
    94 @misc{affinityWindows,
     104@manual{affinityWindows,
    95105        title           = "{Windows (vs.85) - SetThreadAffinityMask function}"
    96106}
    97107
    98 @misc{affinityFreebsd,
     108@manual{switchToWindows,
     109        title           = "{Windows (vs.85) - SwitchToFiber function}"
     110}
     111
     112@manual{affinityFreebsd,
    99113        title           = "{FreeBSD General Commands Manual - CPUSET(1)}"
    100114}
    101115
    102 @misc{affinityNetbsd,
     116@manual{affinityNetbsd,
    103117        title           = "{NetBSD Library Functions Manual - AFFINITY(3)}"
    104118}
    105119
    106 @misc{affinityMacosx,
     120@manual{affinityMacosx,
    107121        title           = "{Affinity API Release Notes for OS X v10.5}"
    108122}
     123
     124
     125@misc{NodeJs,
     126        title           = "{Node.js}",
     127        howpublished= "\url{https://nodejs.org/en/}",
     128}
     129
     130@misc{SpringMVC,
     131        title           = "{Spring Web MVC}",
     132        howpublished= "\url{https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html}",
     133}
     134
     135@misc{Django,
     136        title           = "{Django}",
     137        howpublished= "\url{https://www.djangoproject.com/}",
     138}
  • doc/proposals/concurrency/figures/ext_monitor.fig

    rf7a4f89 rcf966b5  
    6969         5250 3150 5250 2400
    70702 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
    71          3150 3150 3750 3150 3750 2850 5850 2850 5850 1650
     71         3150 3150 3750 3150 3750 2850 5700 2850 5700 1650
    72722 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
    73          5850 2850 6150 3000
     73         5700 2850 6150 3000
    74742 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
    7575         5100 1800 5400 1800 5400 2400 5100 2400 5100 1800
     
    91914 1 -1 0 0 0 12 0.0000 2 135 735 5100 3975 variables\001
    92924 0 0 50 -1 0 11 0.0000 2 165 855 4275 3150 Acceptables\001
     934 0 0 50 -1 0 11 0.0000 2 120 165 5775 2700 W\001
     944 0 0 50 -1 0 11 0.0000 2 120 135 5775 2400 X\001
     954 0 0 50 -1 0 11 0.0000 2 120 105 5775 2100 Z\001
     964 0 0 50 -1 0 11 0.0000 2 120 135 5775 1800 Y\001
  • doc/proposals/concurrency/figures/int_monitor.fig

    rf7a4f89 rcf966b5  
    47471 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 1200 2850 125 125 1200 2850 1082 2809
    48481 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 900 2850 125 125 900 2850 782 2809
    49 1 3 0 1 -1 -1 0 0 4 0.000 1 0.0000 6225 4650 105 105 6225 4650 6330 4755
    50 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 3150 4650 80 80 3150 4650 3230 4730
    51 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4575 4650 105 105 4575 4650 4680 4755
     491 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 6000 4650 105 105 6000 4650 6105 4755
     501 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 3900 4650 80 80 3900 4650 3980 4730
    52512 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
    5352         3900 1950 4200 2100
     
    1071064 1 -1 0 0 0 12 0.0000 2 165 420 4050 1050 entry\001
    1081074 0 0 50 -1 0 11 0.0000 2 120 705 600 2325 Condition\001
    109 4 0 -1 0 0 0 12 0.0000 2 180 930 6450 4725 routine ptrs\001
    110 4 0 -1 0 0 0 12 0.0000 2 135 1050 3300 4725 active thread\001
    111 4 0 -1 0 0 0 12 0.0000 2 135 1215 4725 4725 blocked thread\001
     1084 0 -1 0 0 0 12 0.0000 2 135 1215 6150 4725 blocked thread\001
     1094 0 -1 0 0 0 12 0.0000 2 135 1050 4050 4725 active thread\001
  • doc/proposals/concurrency/style/cfa-format.tex

    rf7a4f89 rcf966b5  
    178178    language = C,
    179179    style=defaultStyle,
     180    captionpos=b,
    180181    #1
    181182  }
     
    186187    language = CFA,
    187188    style=cfaStyle,
     189    captionpos=b,
    188190    #1
    189191  }
     
    194196    language = pseudo,
    195197    style=pseudoStyle,
     198    captionpos=b,
    196199    #1
    197200  }
     
    202205    language = c++,
    203206    style=defaultStyle,
     207    captionpos=b,
    204208    #1
    205209  }
     
    210214    language = c++,
    211215    style=defaultStyle,
     216    captionpos=b,
    212217    #1
    213218  }
     
    218223    language = java,
    219224    style=defaultStyle,
     225    captionpos=b,
    220226    #1
    221227  }
     
    226232    language = scala,
    227233    style=defaultStyle,
     234    captionpos=b,
    228235    #1
    229236  }
     
    234241    language = sml,
    235242    style=defaultStyle,
     243    captionpos=b,
    236244    #1
    237245  }
     
    242250    language = D,
    243251    style=defaultStyle,
     252    captionpos=b,
    244253    #1
    245254  }
     
    250259    language = rust,
    251260    style=defaultStyle,
     261    captionpos=b,
    252262    #1
    253263  }
     
    258268    language = Golang,
    259269    style=defaultStyle,
     270    captionpos=b,
    260271    #1
    261272  }
  • doc/proposals/concurrency/text/basics.tex

    rf7a4f89 rcf966b5  
    2121While the main focus of this proposal is concurrency and parallelism, it is important to address coroutines, which are actually a significant building block of a concurrency system. Coroutines need to deal with context-switches and other context-management operations. Therefore, this proposal includes coroutines both as an intermediate step for the implementation of threads, and a first class feature of \CFA. Furthermore, many design challenges of threads are at least partially present in designing coroutines, which makes the design effort that much more relevant. The core \acrshort{api} of coroutines revolve around two features: independent call stacks and \code{suspend}/\code{resume}.
    2222
    23 \begin{figure}
     23\begin{table}
    2424\begin{center}
    2525\begin{tabular}{c @{\hskip 0.025in}|@{\hskip 0.025in} c @{\hskip 0.025in}|@{\hskip 0.025in} c}
     
    129129\end{tabular}
    130130\end{center}
    131 \caption{Different implementations of a Fibonacci sequence generator in C.}
     131\caption{Different implementations of a Fibonacci sequence generator in C.},
    132132\label{lst:fibonacci-c}
    133 \end{figure}
    134 
    135 A good example of a problem made easier with coroutines is generators, like the Fibonacci sequence. This problem comes with the challenge of decoupling how a sequence is generated and how it is used. Figure \ref{lst:fibonacci-c} shows conventional approaches to writing generators in C. All three of these approach suffer from strong coupling. The left and center approaches require that the generator have knowledge of how the sequence is used, while the rightmost approach requires holding internal state between calls on behalf of the generator and makes it much harder to handle corner cases like the Fibonacci seed.
    136 
    137 Figure \ref{lst:fibonacci-cfa} is an example of a solution to the Fibonacci problem using \CFA coroutines, where the coroutine stack holds sufficient state for the next generation. This solution has the advantage of having very strong decoupling between how the sequence is generated and how it is used. Indeed, this version is as easy to use as the \code{fibonacci_state} solution, while the implementation is very similar to the \code{fibonacci_func} example.
     133\end{table}
     134
     135A good example of a problem made easier with coroutines is generators, like the Fibonacci sequence. This problem comes with the challenge of decoupling how a sequence is generated and how it is used. Table \ref{lst:fibonacci-c} shows conventional approaches to writing generators in C. All three of these approach suffer from strong coupling. The left and center approaches require that the generator have knowledge of how the sequence is used, while the rightmost approach requires holding internal state between calls on behalf of the generator and makes it much harder to handle corner cases like the Fibonacci seed.
     136
     137Listing \ref{lst:fibonacci-cfa} is an example of a solution to the Fibonacci problem using \CFA coroutines, where the coroutine stack holds sufficient state for the next generation. This solution has the advantage of having very strong decoupling between how the sequence is generated and how it is used. Indeed, this version is as easy to use as the \code{fibonacci_state} solution, while the implementation is very similar to the \code{fibonacci_func} example.
    138138
    139139\begin{figure}
    140 \begin{cfacode}
     140\begin{cfacode}[caption={Implementation of Fibonacci using coroutines},label={lst:fibonacci-cfa}]
    141141coroutine Fibonacci {
    142142        int fn; //used for communication
     
    179179}
    180180\end{cfacode}
    181 \caption{Implementation of Fibonacci using coroutines}
    182 \label{lst:fibonacci-cfa}
    183181\end{figure}
    184182
    185 Figure \ref{lst:fmt-line} shows the \code{Format} coroutine for restructuring text into groups of character blocks of fixed size. The example takes advantage of resuming coroutines in the constructor to simplify the code and highlights the idea that interesting control flow can occur in the constructor.
     183Listing \ref{lst:fmt-line} shows the \code{Format} coroutine for restructuring text into groups of character blocks of fixed size. The example takes advantage of resuming coroutines in the constructor to simplify the code and highlights the idea that interesting control flow can occur in the constructor.
    186184
    187185\begin{figure}
    188 \begin{cfacode}[tabsize=3]
     186\begin{cfacode}[tabsize=3,caption={Formatting text into lines of 5 blocks of 4 characters.},label={lst:fmt-line}]
    189187//format characters into blocks of 4 and groups of 5 blocks per line
    190188coroutine Format {
     
    230228}
    231229\end{cfacode}
    232 \caption{Formatting text into lines of 5 blocks of 4 characters.}
    233 \label{lst:fmt-line}
    234230\end{figure}
    235231
  • doc/proposals/concurrency/text/cforall.tex

    rf7a4f89 rcf966b5  
    1010values''~\cite[3.15]{C11}}, most importantly construction and destruction of objects. Most of the following code examples can be found on the \CFA website~\cite{www-cfa}
    1111
     12% ======================================================================
    1213\section{References}
    1314
     
    2829The important take away from this code example is that a reference offers a handle to an object, much like a pointer, but which is automatically dereferenced for convenience.
    2930
     31% ======================================================================
    3032\section{Overloading}
    3133
     
    4850This feature is particularly important for concurrency since the runtime system relies on creating different types to represent concurrency objects. Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions that prevent name clashes. As seen in chapter \ref{basics}, routine \code{main} is an example that benefits from overloading.
    4951
     52% ======================================================================
    5053\section{Operators}
    5154Overloading also extends to operators. The syntax for denoting operator-overloading is to name a routine with the symbol of the operator and question marks where the arguments of the operation occur, e.g.:
     
    6770While concurrency does not use operator overloading directly, this feature is more important as an introduction for the syntax of constructors.
    6871
     72% ======================================================================
    6973\section{Constructors/Destructors}
    7074Object life-time is often a challenge in concurrency. \CFA uses the approach of giving concurrent meaning to object life-time as a mean of synchronization and/or mutual exclusion. Since \CFA relies heavily on the life time of objects, constructors and destructors are a core feature required for concurrency and parallelism. \CFA uses the following syntax for constructors and destructors :
     
    101105Note that like \CC, \CFA introduces \code{new} and \code{delete}, which behave like \code{malloc} and \code{free} in addition to constructing and destructing objects, after calling \code{malloc} and before calling \code{free}, respectively.
    102106
     107% ======================================================================
    103108\section{Parametric Polymorphism}
    104109Routines in \CFA can also be reused for multiple types. This capability is done using the \code{forall} clause, which gives \CFA its name. \code{forall} clauses allow separately compiled routines to support generic usage over multiple types. For example, the following sum function works for any type that supports construction from 0 and addition :
     
    130135\end{cfacode}
    131136
     137Note that the type use for assertions can be either an \code{otype} or a \code{dtype}. Types declares as \code{otype} refer to ``complete'' objects, i.e., objects with a size, a default constructor, a copy constructor, a destructor and an assignment operator. Using \code{dtype} on the other hand has none of these assumptions but is extremely restrictive, it only guarantees the object is addressable.
     138
     139% ======================================================================
    132140\section{with Clause/Statement}
    133141Since \CFA lacks the concept of a receiver, certain functions end-up needing to repeat variable names often. To remove this inconvenience, \CFA provides the \code{with} statement, which opens an aggregate scope making its fields directly accessible (like Pascal).
     
    156164\end{cfacode}
    157165
    158 \section{otype/dtype}
    159 
    160166For more information on \CFA see \cite{cforall-ug,rob-thesis,www-cfa}.
  • doc/proposals/concurrency/text/concurrency.tex

    rf7a4f89 rcf966b5  
    88Approaches based on shared memory are more closely related to non-concurrent paradigms since they often rely on basic constructs like routine calls and shared objects. At the lowest level, concurrent paradigms are implemented as atomic operations and locks. Many such mechanisms have been proposed, including semaphores~\cite{Dijkstra68b} and path expressions~\cite{Campbell74}. However, for productivity reasons it is desirable to have a higher-level construct be the core concurrency paradigm~\cite{HPP:Study}.
    99
    10 An approach that is worth mentioning because it is gaining in popularity is transactional memory~\cit. While this approach is even pursued by system languages like \CC~\cite{Cpp-Transactions}, the performance and feature set is currently too restrictive to be the main concurrency paradigm for systems language, which is why it was rejected as the core paradigm for concurrency in \CFA.
     10An approach that is worth mentioning because it is gaining in popularity is transactional memory~\cite{Herlihy93}. While this approach is even pursued by system languages like \CC~\cite{Cpp-Transactions}, the performance and feature set is currently too restrictive to be the main concurrency paradigm for systems language, which is why it was rejected as the core paradigm for concurrency in \CFA.
    1111
    1212One of the most natural, elegant, and efficient mechanisms for synchronization and communication, especially for shared-memory systems, is the \emph{monitor}. Monitors were first proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}. Many programming languages---e.g., Concurrent Pascal~\cite{ConcurrentPascal}, Mesa~\cite{Mesa}, Modula~\cite{Modula-2}, Turing~\cite{Turing:old}, Modula-3~\cite{Modula-3}, NeWS~\cite{NeWS}, Emerald~\cite{Emerald}, \uC~\cite{Buhr92a} and Java~\cite{Java}---provide monitors as explicit language constructs. In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as semaphores or locks to simulate monitors. For these reasons, this project proposes monitors as the core concurrency-construct.
     
    7373Notice how the counter is used without any explicit synchronization and yet supports thread-safe semantics for both reading and writing, which is similar in usage to \CC \code{atomic} template.
    7474
    75 Here, the constructor (\code{?\{\}}) uses the \code{nomutex} keyword to signify that it does not acquire the monitor mutual-exclusion when constructing. This semantics is because an object not yet con\-structed should never be shared and therefore does not require mutual exclusion. Furthermore, it allows the implementation greater freedom when it initialiezes the monitor locking. The prefix increment operator uses \code{mutex} to protect the incrementing process from race conditions. Finally, there is a conversion operator from \code{counter_t} to \code{size_t}. This conversion may or may not require the \code{mutex} keyword depending on whether or not reading a \code{size_t} is an atomic operation.
    76 
    77 For maximum usability, monitors use \gls{multi-acq} semantics, which means a single thread can acquire the same monitor multiple times without deadlock. For example, figure \ref{fig:search} uses recursion and \gls{multi-acq} to print values inside a binary tree.
     75Here, the constructor (\code{?\{\}}) uses the \code{nomutex} keyword to signify that it does not acquire the monitor mutual-exclusion when constructing. This semantics is because an object not yet con\-structed should never be shared and therefore does not require mutual exclusion. Furthermore, it allows the implementation greater freedom when it initializes the monitor locking. The prefix increment operator uses \code{mutex} to protect the incrementing process from race conditions. Finally, there is a conversion operator from \code{counter_t} to \code{size_t}. This conversion may or may not require the \code{mutex} keyword depending on whether or not reading a \code{size_t} is an atomic operation.
     76
     77For maximum usability, monitors use \gls{multi-acq} semantics, which means a single thread can acquire the same monitor multiple times without deadlock. For example, listing \ref{fig:search} uses recursion and \gls{multi-acq} to print values inside a binary tree.
    7878\begin{figure}
    79 \begin{cfacode}
     79\begin{cfacode}[caption={Recursive printing algorithm using \gls{multi-acq}.},label={fig:search}]
    8080monitor printer { ... };
    8181struct tree {
     
    9191}
    9292\end{cfacode}
    93 \caption{Recursive printing algorithm using \gls{multi-acq}.}
    94 \label{fig:search}
    9593\end{figure}
    9694
    97 Having both \code{mutex} and \code{nomutex} keywords is redundant based on the meaning of a routine having neither of these keywords. For example, given a routine without qualifiers \code{void foo(counter_t & this)}, then it is reasonable that it should default to the safest option \code{mutex}, whereas assuming \code{nomutex} is unsafe and may cause subtle errors. In fact, \code{nomutex} is the ``normal'' parameter behaviour, with the \code{nomutex} keyword effectively stating explicitly that ``this routine is not special''. Another alternative is making exactly one of these keywords mandatory, which provides the same semantics but without the ambiguity of supporting routines with neither keyword. Mandatory keywords would also have the added benefit of being self-documented but at the cost of extra typing. While there are several benefits to mandatory keywords, they do bring a few challenges. Mandatory keywords in \CFA would imply that the compiler must know without doubt whether or not a parameter is a monitor or not. Since \CFA relies heavily on traits as an abstraction mechanism, the distinction between a type that is a monitor and a type that looks like a monitor can become blurred. For this reason, \CFA only has the \code{mutex} keyword and uses no keyword to mean \code{nomutex}.
     95Having both \code{mutex} and \code{nomutex} keywords is redundant based on the meaning of a routine having neither of these keywords. For example, it is reasonable that it should default to the safest option (\code{mutex}) when given a routine without qualifiers \code{void foo(counter_t & this)}, whereas assuming \code{nomutex} is unsafe and may cause subtle errors. On the other hand, \code{nomutex} is the ``normal'' parameter behaviour, it effectively states explicitly that ``this routine is not special''. Another alternative is making exactly one of these keywords mandatory, which provides the same semantics but without the ambiguity of supporting routines with neither keyword. Mandatory keywords would also have the added benefit of being self-documented but at the cost of extra typing. While there are several benefits to mandatory keywords, they do bring a few challenges. Mandatory keywords in \CFA would imply that the compiler must know without doubt whether or not a parameter is a monitor or not. Since \CFA relies heavily on traits as an abstraction mechanism, the distinction between a type that is a monitor and a type that looks like a monitor can become blurred. For this reason, \CFA only has the \code{mutex} keyword and uses no keyword to mean \code{nomutex}.
    9896
    9997The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
     
    144142        \item Implement rollback semantics.
    145143\end{enumerate}
    146 While the first requirement is already a significant constraint on the system, implementing a general rollback semantics in a C-like language is still prohibitively complex~\cite{Dice10}. In \CFA, users simply need to be careful when acquiring multiple monitors at the same time or only use \gls{bulk-acq} of all the monitors. While \CFA provides only a partial solution, nost systems provide no solution and the \CFA partial solution handles many useful cases.
     144While the first requirement is already a significant constraint on the system, implementing a general rollback semantics in a C-like language is still prohibitively complex~\cite{Dice10}. In \CFA, users simply need to be careful when acquiring multiple monitors at the same time or only use \gls{bulk-acq} of all the monitors. While \CFA provides only a partial solution, most systems provide no solution and the \CFA partial solution handles many useful cases.
    147145
    148146For example, \gls{multi-acq} and \gls{bulk-acq} can be used together in interesting ways:
     
    161159\subsection{\code{mutex} statement} \label{mutex-stmt}
    162160
    163 The call semantics discussed above have one software engineering issue, only a named routine can acquire the mutual-exclusion of a set of monitor. \CFA offers the \code{mutex} statement to workaround the need for unnecessary names, avoiding a major software engineering problem~\cite{2FTwoHardThings}. Listing \ref{lst:mutex-stmt} shows an example of the \code{mutex} statement, which introduces a new scope in which the mutual-exclusion of a set of monitor is acquired. Beyond naming, the \code{mutex} statement has no semantic difference from a routine call with \code{mutex} parameters.
    164 
    165 \begin{figure}
     161The call semantics discussed above have one software engineering issue, only a named routine can acquire the mutual-exclusion of a set of monitor. \CFA offers the \code{mutex} statement to workaround the need for unnecessary names, avoiding a major software engineering problem~\cite{2FTwoHardThings}. Table \ref{lst:mutex-stmt} shows an example of the \code{mutex} statement, which introduces a new scope in which the mutual-exclusion of a set of monitor is acquired. Beyond naming, the \code{mutex} statement has no semantic difference from a routine call with \code{mutex} parameters.
     162
     163\begin{table}
    166164\begin{center}
    167165\begin{tabular}{|c|c|}
     
    191189\caption{Regular call semantics vs. \code{mutex} statement}
    192190\label{lst:mutex-stmt}
    193 \end{figure}
     191\end{table}
    194192
    195193% ======================================================================
     
    255253}
    256254\end{cfacode}
    257 There are two details to note here. First, the \code{signal} is a delayed operation, it only unblocks the waiting thread when it reaches the end of the critical section. This semantic is needed to respect mutual-exclusion. The alternative is to return immediately after the call to \code{signal}, which is significantly more restrictive. Second, in \CFA, while it is common to store a \code{condition} as a field of the monitor, a \code{condition} variable can be stored/created independently of a monitor. Here routine \code{foo} waits for the \code{signal} from \code{bar} before making further progress, effectively ensuring a basic ordering.
    258 
    259 An important aspect of the implementation is that \CFA does not allow barging, which means that once function \code{bar} releases the monitor, \code{foo} is guaranteed to resume immediately after (unless some other thread waited on the same condition). This guarantees offers the benefit of not having to loop around waits in order to guarantee that a condition is still met. The main reason \CFA offers this guarantee is that users can easily introduce barging if it becomes a necessity but adding barging prevention or barging avoidance is more involved without language support. Supporting barging prevention as well as extending internal scheduling to multiple monitors is the main source of complexity in the design of \CFA concurrency.
     255There are two details to note here. First, the \code{signal} is a delayed operation, it only unblocks the waiting thread when it reaches the end of the critical section. This semantic is needed to respect mutual-exclusion, i.e., the signaller and signalled thread cannot be in the monitor simultaneously. The alternative is to return immediately after the call to \code{signal}, which is significantly more restrictive. Second, in \CFA, while it is common to store a \code{condition} as a field of the monitor, a \code{condition} variable can be stored/created independently of a monitor. Here routine \code{foo} waits for the \code{signal} from \code{bar} before making further progress, effectively ensuring a basic ordering.
     256
     257An important aspect of the implementation is that \CFA does not allow barging, which means that once function \code{bar} releases the monitor, \code{foo} is guaranteed to resume immediately after (unless some other thread waited on the same condition). This guarantee offers the benefit of not having to loop around waits to recheck that a condition is met. The main reason \CFA offers this guarantee is that users can easily introduce barging if it becomes a necessity but adding barging prevention or barging avoidance is more involved without language support. Supporting barging prevention as well as extending internal scheduling to multiple monitors is the main source of complexity in the design of \CFA concurrency.
    260258
    261259% ======================================================================
     
    264262% ======================================================================
    265263% ======================================================================
    266 It is easier to understand the problem of multi-monitor scheduling using a series of pseudo-code examples. Note that for simplicity in the following snippets of pseudo-code, waiting and signalling is done using an implicit condition variable, like Java built-in monitors. Indeed, \code{wait} statements always use the implicit condition as parameter and explicitly names the monitors (A and B) associated with the condition. Note that in \CFA, condition variables are tied to a \emph{group} of monitors on first use (called branding), which means that using internal scheduling with distinct sets of monitors requires one condition variable per set of monitors.
     264It is easier to understand the problem of multi-monitor scheduling using a series of pseudo-code examples. Note that for simplicity in the following snippets of pseudo-code, waiting and signalling is done using an implicit condition variable, like Java built-in monitors. Indeed, \code{wait} statements always use the implicit condition variable as parameter and explicitly names the monitors (A and B) associated with the condition. Note that in \CFA, condition variables are tied to a \emph{group} of monitors on first use (called branding), which means that using internal scheduling with distinct sets of monitors requires one condition variable per set of monitors. The example below shows the simple case of having two threads (one for each column) and a single monitor A.
    267265
    268266\begin{multicols}{2}
     
    283281\end{pseudo}
    284282\end{multicols}
    285 The example shows the simple case of having two threads (one for each column) and a single monitor A. One thread acquires before waiting (atomically blocking and releasing A) and the other acquires before signalling. It is important to note here that both \code{wait} and \code{signal} must be called with the proper monitor(s) already acquired. This semantic is a logical requirement for barging prevention.
     283One thread acquires before waiting (atomically blocking and releasing A) and the other acquires before signalling. It is important to note here that both \code{wait} and \code{signal} must be called with the proper monitor(s) already acquired. This semantic is a logical requirement for barging prevention.
    286284
    287285A direct extension of the previous example is a \gls{bulk-acq} version:
    288 
    289286\begin{multicols}{2}
    290287\begin{pseudo}
     
    293290release A & B
    294291\end{pseudo}
    295 
    296292\columnbreak
    297 
    298293\begin{pseudo}
    299294acquire A & B
     
    324319\end{pseudo}
    325320\end{multicols}
    326 The \code{wait} only releases monitor \code{B} so the signalling thread cannot acquire monitor \code{A} to get to the \code{signal}. Attempting release of all acquired monitors at the \code{wait} results in another set of problems such as releasing monitor \code{C}, which has nothing to do with the \code{signal}.
    327 
    328 However, for monitors as for locks, it is possible to write a program using nesting without encountering any problems if nesting is done correctly. For example, the next pseudo-code snippet acquires monitors {\sf A} then {\sf B} before waiting, while only acquiring {\sf B} when signalling, effectively avoiding the nested monitor problem.
     321The \code{wait} only releases monitor \code{B} so the signalling thread cannot acquire monitor \code{A} to get to the \code{signal}. Attempting release of all acquired monitors at the \code{wait} introduces a different set of problems, such as releasing monitor \code{C}, which has nothing to do with the \code{signal}.
     322
     323However, for monitors as for locks, it is possible to write a program using nesting without encountering any problems if nesting is done correctly. For example, the next pseudo-code snippet acquires monitors {\sf A} then {\sf B} before waiting, while only acquiring {\sf B} when signalling, effectively avoiding the Nested Monitor Problem~\cite{Lister77}.
    329324
    330325\begin{multicols}{2}
     
    348343\end{multicols}
    349344
     345This simple refactoring may not be possible, forcing more complex restructuring.
    350346
    351347% ======================================================================
     
    355351% ======================================================================
    356352
    357 A larger example is presented to show complex issues for \gls{bulk-acq} and all the implementation options are analyzed. Listing \ref{lst:int-bulk-pseudo} shows an example where \gls{bulk-acq} adds a significant layer of complexity to the internal signalling semantics, and listing \ref{lst:int-bulk-cfa} shows the corresponding \CFA code to implement the pseudo-code in listing \ref{lst:int-bulk-pseudo}. For the purpose of translating the given pseudo-code into \CFA-code, any method of introducing a monitor is acceptable, e.g., \code{mutex} parameter global variables, pointer parameters or using locals with the \code{mutex}-statement.
    358 
    359 \begin{figure}[!b]
     353A larger example is presented to show complex issues for \gls{bulk-acq} and all the implementation options are analyzed. Listing \ref{lst:int-bulk-pseudo} shows an example where \gls{bulk-acq} adds a significant layer of complexity to the internal signalling semantics, and listing \ref{lst:int-bulk-cfa} shows the corresponding \CFA code to implement the pseudo-code in listing \ref{lst:int-bulk-pseudo}. For the purpose of translating the given pseudo-code into \CFA-code, any method of introducing a monitor is acceptable, e.g., \code{mutex} parameter, global variables, pointer parameters or using locals with the \code{mutex}-statement.
     354
     355\begin{figure}[!t]
    360356\begin{multicols}{2}
    361357Waiting thread
     
    371367release A
    372368\end{pseudo}
    373 
    374369\columnbreak
    375 
    376370Signalling thread
    377371\begin{pseudo}[numbers=left, firstnumber=10,escapechar=|]
     
    384378        release A & B
    385379        //Code Section 8
    386 release A
     380|\label{line:lastRelease}|release A
    387381\end{pseudo}
    388382\end{multicols}
    389 \caption{Internal scheduling with \gls{bulk-acq}}
    390 \label{lst:int-bulk-pseudo}
     383\begin{cfacode}[caption={Internal scheduling with \gls{bulk-acq}},label={lst:int-bulk-pseudo}]
     384\end{cfacode}
    391385\begin{center}
    392386\begin{cfacode}[xleftmargin=.4\textwidth]
     
    409403}
    410404\end{cfacode}
    411 
    412405\columnbreak
    413 
    414406Signalling thread
    415407\begin{cfacode}
     
    425417\end{cfacode}
    426418\end{multicols}
    427 \caption{Equivalent \CFA code for listing \ref{lst:int-bulk-pseudo}}
    428 \label{lst:int-bulk-cfa}
    429 \end{figure}
    430 
    431 The complexity begins at code sections 4 and 8, which are where the existing semantics of internal scheduling need to be extended for multiple monitors. The root of the problem is that \gls{bulk-acq} is used in a context where one of the monitors is already acquired and is why it is important to define the behaviour of the previous pseudo-code. When the signaller thread reaches the location where it should ``release \code{A & B}'' (line \ref{line:signal1}), it must actually transfer ownership of monitor \code{B} to the waiting thread. This ownership transfer is required in order to prevent barging into \code{B} by another thread, since both the signalling and signalled threads still need monitor \code{A}. There are three options.
    432 
    433 \subsubsection{Delaying signals}
    434 The obvious solution to solve the problem of multi-monitor scheduling is to keep ownership of all locks until the last lock is ready to be transferred. It can be argued that that moment is when the last lock is no longer needed because this semantics fits most closely to the behaviour of single-monitor scheduling. This solution has the main benefit of transferring ownership of groups of monitors, which simplifies the semantics from multiple objects to a single group of objects, effectively making the existing single-monitor semantic viable by simply changing monitors to monitor groups.
     419\begin{cfacode}[caption={Equivalent \CFA code for listing \ref{lst:int-bulk-pseudo}},label={lst:int-bulk-cfa}]
     420\end{cfacode}
    435421\begin{multicols}{2}
    436422Waiter
     
    456442\end{pseudo}
    457443\end{multicols}
    458 However, this solution can become much more complicated depending on what is executed while secretly holding B (at line \ref{line:secret}). The goal in this solution is to avoid the need to transfer ownership of a subset of the condition monitors. However, listing \ref{lst:dependency} shows a slitghtly different example where a third thread iw waiting on monitor \code{A}, using a different condition variable. Because the thread is signalled when secretly holding \code{B}, the goal  becomes unreachable. Depending on the order of signals (line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen :
    459 
    460 \paragraph{Case 1: thread 1 goes first.} In this case, the problem is that monitor A needs to be passed to thread 2 when thread 1 is done with it.
    461 \paragraph{Case 2: thread 2 goes first.} In this case, the problem is that monitor B needs to be passed to thread 1, which can be done directly or using thread 2 as an intermediate.
     444\begin{cfacode}[caption={Listing \ref{lst:int-bulk-pseudo}, with delayed signalling comments},label={lst:int-secret}]
     445\end{cfacode}
     446\end{figure}
     447
     448The complexity begins at code sections 4 and 8, which are where the existing semantics of internal scheduling need to be extended for multiple monitors. The root of the problem is that \gls{bulk-acq} is used in a context where one of the monitors is already acquired and is why it is important to define the behaviour of the previous pseudo-code. When the signaller thread reaches the location where it should ``release \code{A & B}'' (listing \ref{lst:int-bulk-pseudo} line \ref{line:signal1}), it must actually transfer ownership of monitor \code{B} to the waiting thread. This ownership transfer is required in order to prevent barging into \code{B} by another thread, since both the signalling and signalled threads still need monitor \code{A}. There are three options.
     449
     450\subsubsection{Delaying signals}
     451The obvious solution to solve the problem of multi-monitor scheduling is to keep ownership of all locks until the last lock is ready to be transferred. It can be argued that that moment is when the last lock is no longer needed because this semantics fits most closely to the behaviour of single-monitor scheduling. This solution has the main benefit of transferring ownership of groups of monitors, which simplifies the semantics from multiple objects to a single group of objects, effectively making the existing single-monitor semantic viable by simply changing monitors to monitor groups. The naive approach to this solution is to only release monitors once every monitor in a group can be released. However, since some monitors are never released (i.e., the monitor of a thread), this interpretation means groups can grow but may never shrink. A more interesting interpretation is to only transfer groups as one but to recreate the groups on every operation, i.e., limit ownership transfer to one per \code{signal}/\code{release}.
     452
     453However, this solution can become much more complicated depending on what is executed while secretly holding B (listing \ref{lst:int-secret} line \ref{line:secret}).
     454The goal in this solution is to avoid the need to transfer ownership of a subset of the condition monitors. However, listing \ref{lst:dependency} shows a slightly different example where a third thread is waiting on monitor \code{A}, using a different condition variable. Because the third thread is signalled when secretly holding \code{B}, the goal  becomes unreachable. Depending on the order of signals (listing \ref{lst:dependency} line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen :
     455
     456\paragraph{Case 1: thread $\alpha$ goes first.} In this case, the problem is that monitor \code{A} needs to be passed to thread $\beta$ when thread $\alpha$ is done with it.
     457\paragraph{Case 2: thread $\beta$ goes first.} In this case, the problem is that monitor \code{B} needs to be retained and passed to thread $\alpha$ along with monitor \code{A}, which can be done directly or possibly using thread $\beta$ as an intermediate.
    462458\\
    463459
    464 Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order. However, regardless of the answer, users can move line \ref{line:signal-a} before line \ref{line:signal-ab} and get the reverse effect.
     460Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order. However, regardless of the answer, users can move line \ref{line:signal-a} before line \ref{line:signal-ab} and get the reverse effect for listing \ref{lst:dependency}.
    465461
    466462In both cases, the threads need to be able to distinguish, on a per monitor basis, which ones need to be released and which ones need to be transferred, which means monitors cannot be handled as a single homogeneous group and therefore effectively precludes this approach.
     
    479475release A
    480476\end{pseudo}
    481 
    482477\columnbreak
    483 
    484478Thread $\gamma$
    485479\begin{pseudo}[numbers=left, firstnumber=6, escapechar=|]
     
    487481        acquire A & B
    488482                |\label{line:signal-ab}|signal A & B
    489         release A & B
     483        |\label{line:release-ab}|release A & B
    490484        |\label{line:signal-a}|signal A
    491 release A
    492 \end{pseudo}
    493 
     485|\label{line:release-a}|release A
     486\end{pseudo}
    494487\columnbreak
    495 
    496488Thread $\beta$
    497 \begin{pseudo}[numbers=left, firstnumber=12]
     489\begin{pseudo}[numbers=left, firstnumber=12, escapechar=|]
    498490acquire A
    499491        wait A
    500 release A
    501 \end{pseudo}
    502 
     492|\label{line:release-aa}|release A
     493\end{pseudo}
    503494\end{multicols}
    504 \caption{Dependency graph}
    505 \label{lst:dependency}
     495\begin{cfacode}[caption={Pseudo-code for the three thread example.},label={lst:dependency}]
     496\end{cfacode}
    506497\begin{center}
    507498\input{dependency}
     
    536527\end{pseudo}
    537528\end{multicols}
    538 \caption{Extension to three monitors of listing \ref{lst:int-bulk-pseudo}}
    539 \label{lst:explosion}
     529\begin{cfacode}[caption={Extension to three monitors of listing \ref{lst:int-bulk-pseudo}},label={lst:explosion}]
     530\end{cfacode}
    540531\end{figure}
    541532
     
    543534
    544535\subsubsection{Partial signalling} \label{partial-sig}
    545 Finally, the solution that is chosen for \CFA is to use partial signalling. Again using listing \ref{lst:int-bulk-pseudo}, the partial signalling solution transfers ownership of monitor B at lines 10 but does not wake the waiting thread since it is still using monitor A. Only when it reaches line 11 does it actually wakeup the waiting thread. This solution has the benefit that complexity is encapsulated into only two actions, passing monitors to the next owner when they should be release and conditionally waking threads if all conditions are met. This solution has a much simpler implementation than a dependency graph solving algorithm, which is why it was chosen. Furthermore, after being fully implemented, this solution does not appear to have any significant downsides.
     536Finally, the solution that is chosen for \CFA is to use partial signalling. Again using listing \ref{lst:int-bulk-pseudo}, the partial signalling solution transfers ownership of monitor \code{B} at lines \ref{line:signal1} to the waiter but does not wake the waiting thread since it is still using monitor \code{A}. Only when it reaches line \ref{line:lastRelease} does it actually wakeup the waiting thread. This solution has the benefit that complexity is encapsulated into only two actions, passing monitors to the next owner when they should be released and conditionally waking threads if all conditions are met. This solution has a much simpler implementation than a dependency graph solving algorithm, which is why it was chosen. Furthermore, after being fully implemented, this solution does not appear to have any significant downsides.
     537
     538While listing \ref{lst:dependency} is a complicated problem for previous solutions, it can be solved easily with partial signalling :
     539\begin{itemize}
     540        \item When thread $\gamma$ reaches line \ref{line:release-ab} it transfers monitor \code{B} to thread $\alpha$ and continues to hold monitor \code{A}.
     541        \item When thread $\gamma$ reaches line \ref{line:release-a}  it transfers monitor \code{A} to thread $\beta$  and wakes it up.
     542        \item When thread $\beta$  reaches line \ref{line:release-aa} it transfers monitor \code{A} to thread $\alpha$ and wakes it up.
     543        \item Problem solved!
     544\end{itemize}
    546545
    547546% ======================================================================
     
    550549% ======================================================================
    551550% ======================================================================
    552 \begin{figure}
     551\begin{table}
    553552\begin{tabular}{|c|c|}
    554553\code{signal} & \code{signal_block} \\
     
    651650\end{tabular}
    652651\caption{Dating service example using \code{signal} and \code{signal_block}. }
    653 \label{lst:datingservice}
    654 \end{figure}
    655 An important note is that, until now, signalling a monitor was a delayed operation. The ownership of the monitor is transferred only when the monitor would have otherwise been released, not at the point of the \code{signal} statement. However, in some cases, it may be more convenient for users to immediately transfer ownership to the thread that is waiting for cooperation, which is achieved using the \code{signal_block} routine\footnote{name to be discussed}.
    656 
    657 The example in listing \ref{lst:datingservice} highlights the difference in behaviour. As mentioned, \code{signal} only transfers ownership once the current critical section exits, this behaviour requires additional synchronization when a two-way handshake is needed. To avoid this explicit synchronization, the \code{condition} type offers the \code{signal_block} routine, which handles the two-way handshake as shown in the example. This feature removes the need for a second condition variables and simplifies programming. Like every other monitor semantic, \code{signal_block} uses barging prevention, which means mutual-exclusion is baton-passed both on the frond-end and the back-end of the call to \code{signal_block}, meaning no other thread can acquire the monitor either before or after the call.
     652\label{tbl:datingservice}
     653\end{table}
     654An important note is that, until now, signalling a monitor was a delayed operation. The ownership of the monitor is transferred only when the monitor would have otherwise been released, not at the point of the \code{signal} statement. However, in some cases, it may be more convenient for users to immediately transfer ownership to the thread that is waiting for cooperation, which is achieved using the \code{signal_block} routine.
     655
     656The example in table \ref{tbl:datingservice} highlights the difference in behaviour. As mentioned, \code{signal} only transfers ownership once the current critical section exits, this behaviour requires additional synchronization when a two-way handshake is needed. To avoid this explicit synchronization, the \code{condition} type offers the \code{signal_block} routine, which handles the two-way handshake as shown in the example. This feature removes the need for a second condition variables and simplifies programming. Like every other monitor semantic, \code{signal_block} uses barging prevention, which means mutual-exclusion is baton-passed both on the frond-end and the back-end of the call to \code{signal_block}, meaning no other thread can acquire the monitor either before or after the call.
    658657
    659658% ======================================================================
     
    733732% ======================================================================
    734733% ======================================================================
    735 In \uC, monitor declarations include an exhaustive list of monitor operations. Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user:
     734In \uC, a monitor class declaration includee an exhaustive list of monitor operations. Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user:
    736735
    737736\begin{cfacode}
     
    749748\end{cfacode}
    750749
    751 Furthermore, external scheduling is an example where implementation constraints become visible from the interface. Indeed, since there is no hard limit to the number of threads trying to acquire a monitor concurrently, performance is a significant concern. Here is the pseudo code for the entering phase of a monitor:
    752 
     750Furthermore, external scheduling is an example where implementation constraints become visible from the interface. Here is the pseudo code for the entering phase of a monitor:
    753751\begin{center}
    754752\begin{tabular}{l}
     
    765763\end{tabular}
    766764\end{center}
    767 
    768765For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instruction. However, a fast check for \pscode{monitor accepts me} is much harder to implement depending on the constraints put on the monitors. Indeed, monitors are often expressed as an entry queue and some acceptor queue as in the following figure:
    769766
     
    775772\end{figure}
    776773
    777 There are other alternatives to these pictures, but in the case of this picture, implementing a fast accept check is relatively easy. Restricted to a fixed number of mutex members, N, the accept check reduces to updating a bitmask when the acceptor queue changes, a check that executes in a single instruction even with a fairly large number (e.g., 128) of mutex members. This approach requires a dense unique ordering of routines with an upper-bound and that ordering must be consistent across translation units. For OO languages this constraint is not problematic since objects do not offer means of adding member routines only in selected translation units. However, in \CFA users can extend objects with mutex routines that are only visible in certain translation unit. This means that establishing a program-wide dense-ordering between mutex routines can only be done in the program linking phase, and still could have issues when using dynamically shared objects.
     774There are other alternatives to these pictures, but in the case of this picture, implementing a fast accept check is relatively easy. Restricted to a fixed number of mutex members, N, the accept check reduces to updating a bitmask when the acceptor queue changes, a check that executes in a single instruction even with a fairly large number (e.g., 128) of mutex members. This approach requires a dense unique ordering of routines with an upper-bound and that ordering must be consistent across translation units. For OO languages these constraints are common, since objects only offer adding member routines consistently across translation units via inheritence. However, in \CFA users can extend objects with mutex routines that are only visible in certain translation unit. This means that establishing a program-wide dense-ordering among mutex routines can only be done in the program linking phase, and still could have issues when using dynamically shared objects.
     775
    778776The alternative is to alter the implementation like this:
    779777
     
    782780\end{center}
    783781
    784 Generating a mask dynamically means that the storage for the mask information can vary between calls to \code{waitfor}, allowing for more flexibility and extensions. Storing an array of accepted function-pointers replaces the single instruction bitmask compare with dereferencing a pointer followed by a linear search. Furthermore, supporting nested external scheduling (e.g., listing \ref{lst:nest-ext}) may now require additional searches for the \code{waitfor} statement to check if a routine is already queued.
     782Here, the mutex routine called is associated with a thread on the entry queue while a list of acceptable routines is kept seperately. Generating a mask dynamically means that the storage for the mask information can vary between calls to \code{waitfor}, allowing for more flexibility and extensions. Storing an array of accepted function-pointers replaces the single instruction bitmask compare with dereferencing a pointer followed by a linear search. Furthermore, supporting nested external scheduling (e.g., listing \ref{lst:nest-ext}) may now require additional searches for the \code{waitfor} statement to check if a routine is already queued.
    785783
    786784\begin{figure}
    787 \begin{cfacode}
     785\begin{cfacode}[caption={Example of nested external scheduling},label={lst:nest-ext}]
    788786monitor M {};
    789787void foo( M & mutex a ) {}
     
    797795
    798796\end{cfacode}
    799 \caption{Example of nested external scheduling}
    800 \label{lst:nest-ext}
    801797\end{figure}
    802798
     
    880876Syntactically, the \code{waitfor} statement takes a function identifier and a set of monitors. While the set of monitors can be any list of expression, the function name is more restricted because the compiler validates at compile time the validity of the function type and the parameters used with the \code{waitfor} statement. It checks that the set of monitors passed in matches the requirements for a function call. Listing \ref{lst:waitfor} shows various usage of the waitfor statement and which are acceptable. The choice of the function type is made ignoring any non-\code{mutex} parameter. One limitation of the current implementation is that it does not handle overloading but overloading is possible.
    881877\begin{figure}
    882 \begin{cfacode}
     878\begin{cfacode}[caption={Various correct and incorrect uses of the waitfor statement},label={lst:waitfor}]
    883879monitor A{};
    884880monitor B{};
     
    910906}
    911907\end{cfacode}
    912 \caption{Various correct and incorrect uses of the waitfor statement}
    913 \label{lst:waitfor}
    914908\end{figure}
    915909
     
    917911
    918912\begin{figure}
    919 \begin{cfacode}
     913\begin{cfacode}[caption={Various correct and incorrect uses of the or, else, and timeout clause around a waitfor statement},label={lst:waitfor2}]
    920914monitor A{};
    921915
     
    975969}
    976970\end{cfacode}
    977 \caption{Various correct and incorrect uses of the or, else, and timeout clause around a waitfor statement}
    978 \label{lst:waitfor2}
    979971\end{figure}
    980972
     
    986978An interesting use for the \code{waitfor} statement is destructor semantics. Indeed, the \code{waitfor} statement can accept any \code{mutex} routine, which includes the destructor (see section \ref{data}). However, with the semantics discussed until now, waiting for the destructor does not make any sense since using an object after its destructor is called is undefined behaviour. The simplest approach is to disallow \code{waitfor} on a destructor. However, a more expressive approach is to flip execution ordering when waiting for the destructor, meaning that waiting for the destructor allows the destructor to run after the current \code{mutex} routine, similarly to how a condition is signalled.
    987979\begin{figure}
    988 \begin{cfacode}
     980\begin{cfacode}[caption={Example of an executor which executes action in series until the destructor is called.},label={lst:dtor-order}]
    989981monitor Executer {};
    990982struct  Action;
     
    1001993}
    1002994\end{cfacode}
    1003 \caption{Example of an executor which executes action in series until the destructor is called.}
    1004 \label{lst:dtor-order}
    1005995\end{figure}
    1006996For example, listing \ref{lst:dtor-order} shows an example of an executor with an infinite loop, which waits for the destructor to break out of this loop. Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction.
  • doc/proposals/concurrency/text/future.tex

    rf7a4f89 rcf966b5  
     1
     2\chapter{Conclusion}
     3As mentionned in the introduction, this thesis provides a minimal concurrency \acrshort{api} that is simple, efficient and usable as the basis for higher-level features. The approach presented is based on a lighweight thread system for parallelism which sits on top of clusters of processors. This M:N model is jugded to be both more efficient and allow more flexibility for users. Furthermore, this document introduces monitors as the main concurrency tool for users. This thesis also offers a novel approach which allows using multiple monitors at once without running into the Nested Monitor Problem~\cite{Lister77}. It also offers a full implmentation of the concurrency runtime wirtten enterily in \CFA, effectively the largest \CFA code base to date.
     4
     5
    16% ======================================================================
    27% ======================================================================
    3 \chapter{Future Work}
     8\section{Future Work}
    49% ======================================================================
    510% ======================================================================
    611
    7 \section{Flexible Scheduling} \label{futur:sched}
    8 An important part of concurrency is scheduling. Different scheduling algorithm can affect performance (both in terms of average and variation). However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs. One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted the to requirements of the workload. However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms to the scheduler. For example, a web server could attach Type-of-Service information to threads and have a ``ToS aware'' scheduling algorithm tailored to this specific web server. This path of flexible schedulers will be explored for \CFA.
     12\subsection{Performance} \label{futur:perf}
     13This thesis presents a first implementation of the \CFA runtime. Therefore, there is still significant work to do to improve performance. Many of the data structures and algorithms will change in the future to more efficient versions. For example, \CFA the number of monitors in a single \gls{bulk-acq} is only bound by the stack size, this is probably unnecessarily generous. It may be possible that limiting the number help increase performance. However, it is not obvious that the benefit would be significant.
    914
    10 \section{Non-Blocking IO} \label{futur:nbio}
    11 While most of the parallelism tools
    12 However, many modern workloads are not bound on computation but on IO operations, an common case being web-servers and XaaS (anything as a service). These type of workloads often require significant engineering around amortizing costs of blocking IO operations. While improving throughput of these operations is outside what \CFA can do as a language, it can help users to make better use of the CPU time otherwise spent waiting on IO operations. The current trend is to use asynchronous programming using tools like callbacks and/or futures and promises~\cit. However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear
     15\subsection{Flexible Scheduling} \label{futur:sched}
     16An important part of concurrency is scheduling. Different scheduling algorithm can affect performance (both in terms of average and variation). However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs. One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted to the requirements of the workload. However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms to the scheduler. For example, a web server could attach Type-of-Service information to threads and have a ``ToS aware'' scheduling algorithm tailored to this specific web server. This path of flexible schedulers will be explored for \CFA.
    1317
    14 \section{Other concurrency tools} \label{futur:tools}
    15 While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package. Example of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, and executors. These additional features are useful when monitors offer a level of abstraction which is inadequate for certain tasks.
     18\subsection{Non-Blocking IO} \label{futur:nbio}
     19While most of the parallelism tools are aimed at data parallelism and control-flow parallelism, many modern workloads are not bound on computation but on IO operations, a common case being web-servers and XaaS (anything as a service). These type of workloads often require significant engineering around amortizing costs of blocking IO operations. At its core, Non-Blocking IO is a operating system level feature that allows queuing IO operations (e.g., network operations) and registering for notifications instead of waiting for requests to complete. In this context, the role of the language make Non-Blocking IO easily available and with low overhead. The current trend is to use asynchronous programming using tools like callbacks and/or futures and promises, which can be seen in frameworks like Node.js~\cite{NodeJs} for JavaScript, Spring MVC~\cite{SpringMVC} for Java and Django~\cite{Django} for Python. However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear.
    1620
    17 \section{Implicit threading} \label{futur:implcit}
    18 Simpler applications can benefit greatly from having implicit parallelism. That is, parallelism that does not rely on the user to write concurrency. This type of parallelism can be achieved both at the language level and at the library level. The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithm~\cite{uC++book}. Listing \ref{lst:parfor} shows three different code examples that accomplish point-wise sums of large arrays. Note that none of these example explicitly declare any concurrency or parallelism objects.
     21\subsection{Other concurrency tools} \label{futur:tools}
     22While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package. Example of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, executors and actors. These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
    1923
    20 \begin{figure}
     24\subsection{Implicit threading} \label{futur:implcit}
     25Simpler applications can benefit greatly from having implicit parallelism. That is, parallelism that does not rely on the user to write concurrency. This type of parallelism can be achieved both at the language level and at the library level. The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithm~\cite{uC++book}. Table \ref{lst:parfor} shows three different code examples that accomplish point-wise sums of large arrays. Note that none of these examples explicitly declare any concurrency or parallelism objects.
     26
     27\begin{table}
    2128\begin{center}
    2229\begin{tabular}[t]{|c|c|c|}
     
    99106\caption{For loop to sum numbers: Sequential, using library parallelism and language parallelism.}
    100107\label{lst:parfor}
    101 \end{figure}
     108\end{table}
    102109
    103 Implicit parallelism is a general solution and therefore has its limitations. However, it is a quick and simple approach to parallelism which may very well be sufficient for smaller applications and reduces the amount of boiler-plate that is needed to start benefiting from parallelism in modern CPUs.
     110Implicit parallelism is a restrictive solution and therefore has its limitations. However, it is a quick and simple approach to parallelism, which may very well be sufficient for smaller applications and reduces the amount of boiler-plate needed to start benefiting from parallelism in modern CPUs.
    104111
    105112
  • doc/proposals/concurrency/text/internals.tex

    rf7a4f89 rcf966b5  
    11
    22\chapter{Behind the scene}
    3 There are several challenges specific to \CFA when implementing concurrency. These challenges are a direct result of \gls{bulk-acq} and loose object-definitions. These two constraints are the root cause of most design decisions in the implementation. Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs. This is to avoid the chicken and egg problem~\cite{Chicken} of having a memory allocator that relies on the threading system and a threading system that relies on the runtime. This extra goal, means that memory management is a constant concern in the design of the system.
    4 
    5 The main memory concern for concurrency is queues. All blocking operations are made by parking threads onto queues. The queue design needs to be intrusive~\cite{IntrusiveData} to avoid the need for memory allocation, which entails that all the nodes need specific fields to keep track of all needed information. Since many concurrency operations can use an unbound amount of memory (depending on \gls{bulk-acq}), statically defining information in the intrusive fields of threads is insufficient. The only variable sized container that does not require memory allocation is the call-stack, which is heavily used in the implementation of internal scheduling. Particularly variable length arrays, which are used extensively.
    6 
    7 Since stack allocation is based around scope, the first step of the implementation is to identify the scopes that are available to store the information, and which of these can have a variable length. The threads and the condition both allow a fixed amount of memory to be stored, while mutex-routines and the actual blocking call allow for an unbound amount (though the later is preferable in terms of performance).
    8 
    9 Note that since the major contributions of this thesis are extending monitor semantics to \gls{bulk-acq} and loose object definitions, any challenges that are not resulting of these characteristics of \CFA are considered as solved problems and therefore not discussed further.
     3There are several challenges specific to \CFA when implementing concurrency. These challenges are a direct result of \gls{bulk-acq} and loose object-definitions. These two constraints are the root cause of most design decisions in the implementation. Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs. This approach avoids the chicken and egg problem~\cite{Chicken} of having a memory allocator that relies on the threading system and a threading system that relies on the runtime. This extra goal means that memory management is a constant concern in the design of the system.
     4
     5The main memory concern for concurrency is queues. All blocking operations are made by parking threads onto queues and all queues are designed with intrusive nodes, where each not has pre-allocated link fields for chaining, to avoid the need for memory allocation. Since several concurrency operations can use an unbound amount of memory (depending on \gls{bulk-acq}), statically defining information in the intrusive fields of threads is insufficient.The only way to use a variable amount of memory without requiring memory allocation is to pre-allocate large buffers of memory eagerly and store the information in these buffers. Conveniently, the callstack fits that description and is easy to use, which is why it is used heavily in the implementation of internal scheduling, particularly variable-length arrays. Since stack allocation is based around scope, the first step of the implementation is to identify the scopes that are available to store the information, and which of these can have a variable-length array. The threads and the condition both have a fixed amount of memory, while mutex-routines and the actual blocking call allow for an unbound amount, within the stack size.
     6
     7Note that since the major contributions of this thesis are extending monitor semantics to \gls{bulk-acq} and loose object definitions, any challenges that are not resulting of these characteristics of \CFA are considered as solved problems and therefore not discussed.
    108
    119% ======================================================================
     
    1513% ======================================================================
    1614
    17 The first step towards the monitor implementation is simple mutex-routines using monitors. In the single monitor case, this is done using the entry/exit procedure highlighted in listing \ref{lst:entry1}. This entry/exit procedure does not actually have to be extended to support multiple monitors, indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlocks~\cite{Havender68}. In \CFA, ordering of monitor relies on memory ordering, this is sufficient because all objects are guaranteed to have distinct non-overlapping memory layouts and mutual-exclusion for a monitor is only defined for its lifetime, meaning that destroying a monitor while it is acquired is Undefined Behavior. When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer array and sorted based on pointer values. This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively.
     15The first step towards the monitor implementation is simple mutex-routines. In the single monitor case, mutual-exclusion is done using the entry/exit procedure in listing \ref{lst:entry1}. The entry/exit procedures do not have to be extended to support multiple monitors. Indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlock~\cite{Havender68}. In \CFA, ordering of monitor acquisition relies on memory ordering. This approach is sufficient because all objects are guaranteed to have distinct non-overlapping memory layouts and mutual-exclusion for a monitor is only defined for its lifetime, meaning that destroying a monitor while it is acquired is Undefined Behavior. When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer-array and sorted based on pointer values. This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively.
    1816\begin{figure}
    1917\begin{multicols}{2}
     
    3735\end{pseudo}
    3836\end{multicols}
    39 \caption{Initial entry and exit routine for monitors}
    40 \label{lst:entry1}
     37\begin{pseudo}[caption={Initial entry and exit routine for monitors},label={lst:entry1}]
     38\end{pseudo}
    4139\end{figure}
    4240
     
    4442Depending on the choice of semantics for when monitor locks are acquired, interaction between monitors and \CFA's concept of polymorphism can be more complex to support. However, it is shown that entry-point locking solves most of the issues.
    4543
    46 First of all, interaction between \code{otype} polymorphism and monitors is impossible since monitors do not support copying. Therefore, the main question is how to support \code{dtype} polymorphism. It is important to present the difference between the two acquiring options : \glspl{callsite-locking} and entry-point locking, i.e. acquiring the monitors before making a mutex routine call or as the first operation of the mutex routine-call. For example:
    47 \begin{figure}[H]
     44First of all, interaction between \code{otype} polymorphism and monitors is impossible since monitors do not support copying. Therefore, the main question is how to support \code{dtype} polymorphism. It is important to present the difference between the two acquiring options : \glspl{callsite-locking} and entry-point locking, i.e., acquiring the monitors before making a mutex routine-call or as the first operation of the mutex routine-call. For example:
     45\begin{table}[H]
    4846\begin{center}
    4947\begin{tabular}{|c|c|c|}
     
    9795\end{center}
    9896\caption{Call-site vs entry-point locking for mutex calls}
    99 \label{fig:locking-site}
    100 \end{figure}
    101 
    102 Note the \code{mutex} keyword relies on the type system, which means that in cases where a generic monitor routine is desired, writing the mutex routine is possible with the proper trait, for example:
     97\label{tbl:locking-site}
     98\end{table}
     99
     100Note the \code{mutex} keyword relies on the type system, which means that in cases where a generic monitor-routine is desired, writing the mutex routine is possible with the proper trait, e.g.:
    103101\begin{cfacode}
    104102//Incorrect: T may not be monitor
     
    111109\end{cfacode}
    112110
    113 Both entry-point and \gls{callsite-locking} are feasible implementations. The current \CFA implementations uses entry-point locking because it requires less work when using \gls{raii}, effectively transferring the burden of implementation to object construction/destruction. The same could be said of call-site locking, the difference being that the later does not necessarily have an existing scope that matches exactly the scope of the mutual exclusion, i.e.: the function body. Furthermore, entry-point locking requires less code generation since any useful routine is called at least as often as it is define, there can be only one entry-point but many call-sites.
     111Both entry-point and \gls{callsite-locking} are feasible implementations. The current \CFA implementations uses entry-point locking because it requires less work when using \gls{raii}, effectively transferring the burden of implementation to object construction/destruction. It is harder to use \gls{raii} for call-site locking, as it does not necessarily have an existing scope that matches exactly the scope of the mutual exclusion, i.e.: the function body. For example, the monitor call can appear in the middle of an expression. Furthermore, entry-point locking requires less code generation since any useful routine multiple times, but there is only one entry-point for many call-sites.
    114112
    115113% ======================================================================
     
    130128
    131129\subsection{Context Switching}
    132 As mentioned in section \ref{coroutine}, coroutines are a stepping stone for implementing threading. This is because they share the same mechanism for context-switching between different stacks. To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific function call. This assumption means that the context-switch only has to copy the callee-saved registers onto the stack and then switch the stack registers with the ones of the target coroutine/thread. Note that the instruction pointer can be left untouched since the context-switch is always inside the same function. Threads however do not context-switch between each other directly. They context-switch to the scheduler. This method is called a 2-step context-switch and has the advantage of having a clear distinction between user code and the kernel where scheduling and other system operation happen. Obviously, this has the cost of doubling the context-switch cost because threads must context-switch to an intermediate stack. However, the performance of the 2-step context-switch is still superior to a \code{pthread_yield}(see section \ref{results}). additionally, for users in need for optimal performance, it is important to note that having a 2-step context-switch as the default does not prevent \CFA from offering a 1-step context-switch to use manually (or as part of monitors). This option is not currently present in \CFA but the changes required to add it are strictly additive.
     130As mentioned in section \ref{coroutine}, coroutines are a stepping stone for implementing threading, because they share the same mechanism for context-switching between different stacks. To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific function call. This assumption means that the context-switch only has to copy the callee-saved registers onto the stack and then switch the stack registers with the ones of the target coroutine/thread. Note that the instruction pointer can be left untouched since the context-switch is always inside the same function. Threads however do not context-switch between each other directly. They context-switch to the scheduler. This method is called a 2-step context-switch and has the advantage of having a clear distinction between user code and the kernel where scheduling and other system operation happen. Obviously, this doubles the context-switch cost because threads must context-switch to an intermediate stack. The alternative 1-step context-switch uses the stack of the ``from'' thread to schedule and then context-switches directly to the ``to'' thread. However, the performance of the 2-step context-switch is still superior to a \code{pthread_yield} (see section \ref{results}). Additionally, for users in need for optimal performance, it is important to note that having a 2-step context-switch as the default does not prevent \CFA from offering a 1-step context-switch (akin to the Microsoft \code{SwitchToFiber}~\cite{switchToWindows} routine). This option is not currently present in \CFA but the changes required to add it are strictly additive.
    133131
    134132\subsection{Processors}
    135 Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically pthreads in the current implementation of \CFA. Indeed, any parallelism must go through operating-system libraries. However, \glspl{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism. Indeed, processor \glspl{kthread} simply fetch a \glspl{uthread} from the scheduler and run, they are effectively executers for user-threads. The main benefit of this approach is that it offers a well defined boundary between kernel code and user code, for example, kernel thread quiescing, scheduling and interrupt handling. Processors internally use coroutines to take advantage of the existing context-switching semantics.
     133Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically pthreads in the current implementation of \CFA. Indeed, any parallelism must go through operating-system libraries. However, \glspl{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism. Indeed, processor \glspl{kthread} simply fetch a \gls{uthread} from the scheduler and run it; they are effectively executers for user-threads. The main benefit of this approach is that it offers a well defined boundary between kernel code and user code, for example, kernel thread quiescing, scheduling and interrupt handling. Processors internally use coroutines to take advantage of the existing context-switching semantics.
    136134
    137135\subsection{Stack management}
    138 One of the challenges of this system is to reduce the footprint as much as possible. Specifically, all pthreads created also have a stack created with them, which should be used as much as possible. Normally, coroutines also create there own stack to run on, however, in the case of the coroutines used for processors, these coroutines run directly on the kernel thread stack, effectively stealing the processor stack. The exception to this rule is the Main Processor, i.e. the initial kernel thread that is given to any program. In order to respect user expectations, the stack of the initial kernel thread, the main stack of the program, is used by the main user thread rather than the main processor.
     136One of the challenges of this system is to reduce the footprint as much as possible. Specifically, all pthreads created also have a stack created with them, which should be used as much as possible. Normally, coroutines also create there own stack to run on, however, in the case of the coroutines used for processors, these coroutines run directly on the \gls{kthread} stack, effectively stealing the processor stack. The exception to this rule is the Main Processor, i.e. the initial \gls{kthread} that is given to any program. In order to respect C user-expectations, the stack of the initial kernel thread, the main stack of the program, is used by the main user thread rather than the main processor, which can grow very large
    139137
    140138\subsection{Preemption} \label{preemption}
    141 Finally, an important aspect for any complete threading system is preemption. As mentioned in chapter \ref{basics}, preemption introduces an extra degree of uncertainty, which enables users to have multiple threads interleave transparently, rather than having to cooperate among threads for proper scheduling and CPU distribution. Indeed, preemption is desirable because it adds a degree of isolation among threads. In a fully cooperative system, any thread that runs into a long loop can starve other threads, while in a preemptive system starvation can still occur but it does not rely on every thread having to yield or block on a regular basis, which reduces significantly a programmer burden. Obviously, preemption is not optimal for every workload, however any preemptive system can become a cooperative system by making the time-slices extremely large. Which is why \CFA uses a preemptive threading system.
    142 
    143 Preemption in \CFA is based on kernel timers, which are used to run a discrete-event simulation. Every processor keeps track of the current time and registers an expiration time with the preemption system. When the preemption system receives a change in preemption, it sorts these expiration times in a list and sets a kernel timer for the closest one, effectively stepping between preemption events on each signals sent by the timer. These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread. This results in an implementation problem,because when delivering signals to a process, the kernel documentation states that the signal can be delivered to any kernel thread for which the signal is not blocked i.e. :
     139Finally, an important aspect for any complete threading system is preemption. As mentioned in chapter \ref{basics}, preemption introduces an extra degree of uncertainty, which enables users to have multiple threads interleave transparently, rather than having to cooperate among threads for proper scheduling and CPU distribution. Indeed, preemption is desirable because it adds a degree of isolation among threads. In a fully cooperative system, any thread that runs a long loop can starve other threads, while in a preemptive system, starvation can still occur but it does not rely on every thread having to yield or block on a regular basis, which reduces significantly a programmer burden. Obviously, preemption is not optimal for every workload, however any preemptive system can become a cooperative system by making the time-slices extremely large. Therefore, \CFA uses a preemptive threading system.
     140
     141Preemption in \CFA is based on kernel timers, which are used to run a discrete-event simulation. Every processor keeps track of the current time and registers an expiration time with the preemption system. When the preemption system receives a change in preemption, it inserts the time in a sorted order and sets a kernel timer for the closest one, effectively stepping through preemption events on each signal sent by the timer. These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread. This results in an implementation problem, because when delivering signals to a process, the kernel can deliver the signal to any kernel thread for which the signal is not blocked, i.e. :
    144142\begin{quote}
    145143A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked. If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
    146144SIGNAL(7) - Linux Programmer's Manual
    147145\end{quote}
    148 For the sake of simplicity and in order to prevent the case of having two threads receiving alarms simultaneously, \CFA programs block the {\tt SIGALRM} signal on every thread except one. Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread.
    149 
    150 Involuntary context-switching is done by sending signal {\tt SIGUSER1} to the corresponding processor and having the thread yield from inside the signal handler. Effectively context-switching away from the signal-handler back to the kernel and the signal-handler frame is eventually unwound when the thread is scheduled again. This approach means that a signal-handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread). It is important to note that signal-handlers save and restore signal masks because user-thread migration can cause signal mask to migrate from one kernel thread to another. This behaviour is only a problem if all kernel threads among which a user thread can migrate differ in terms of signal masks\footnote{Sadly, official POSIX documentation is silent on what distinguishes ``async-signal-safe'' functions from other functions}. However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel alarm thread can cause deadlocks. For this reason, the alarm thread is on a tight loop around a system call to \code{sigwaitinfo}, requiring very little CPU time for preemption. One final detail about the alarm thread is how to wake it when additional communication is required (e.g., on thread termination). This unblocking is also done using {\tt SIGALRM}, but sent through the \code{pthread_sigqueue}. Indeed, \code{sigwait} can differentiate signals sent from \code{pthread_sigqueue} from signals sent from alarms or the kernel.
     146For the sake of simplicity and in order to prevent the case of having two threads receiving alarms simultaneously, \CFA programs block the {\tt SIGALRM} signal on every kernel thread except one. Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread.
     147
     148Involuntary context-switching is done by sending signal {\tt SIGUSER1} to the corresponding proces\-sor and having the thread yield from inside the signal handler. This approach effectively context-switches away from the signal-handler back to the kernel and the signal-handler frame is eventually unwound when the thread is scheduled again. As a result, a signal-handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread). It is important to note that signal-handlers save and restore signal masks because user-thread migration can cause a signal mask to migrate from one kernel thread to another. This behaviour is only a problem if all kernel threads, among which a user thread can migrate, differ in terms of signal masks\footnote{Sadly, official POSIX documentation is silent on what distinguishes ``async-signal-safe'' functions from other functions.}. However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel-alarm thread can cause deadlocks. For this reason, the alarm thread is in a tight loop around a system call to \code{sigwaitinfo}, requiring very little CPU time for preemption. One final detail about the alarm thread is how to wake it when additional communication is required (e.g., on thread termination). This unblocking is also done using {\tt SIGALRM}, but sent through the \code{pthread_sigqueue}. Indeed, \code{sigwait} can differentiate signals sent from \code{pthread_sigqueue} from signals sent from alarms or the kernel.
    151149
    152150\subsection{Scheduler}
    153 Finally, an aspect that was not mentioned yet is the scheduling algorithm. Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling. Further discussion on scheduling is present in section \label{futur:sched}.
     151Finally, an aspect that was not mentioned yet is the scheduling algorithm. Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling. Further discussion on scheduling is present in section \ref{futur:sched}.
    154152
    155153% ======================================================================
     
    165163\end{center}
    166164\caption{Traditional illustration of a monitor}
    167 \label{fig:monitor}
    168165\end{figure}
    169166
    170167This picture has several components, the two most important being the entry-queue and the AS-stack. The entry-queue is an (almost) FIFO list where threads waiting to enter are parked, while the acceptor-signaler (AS) stack is a FILO list used for threads that have been signalled or otherwise marked as running next.
    171168
    172 For \CFA, this picture does not have support for blocking multiple monitors on a single condition. To support \gls{bulk-acq} two changes to this picture are required. First, it is non longer helpful to attach the condition to \emph{a single} monitor. Secondly, the thread waiting on the conditions has to be separated multiple monitors, which yields :
     169For \CFA, this picture does not have support for blocking multiple monitors on a single condition. To support \gls{bulk-acq} two changes to this picture are required. First, it is no longer helpful to attach the condition to \emph{a single} monitor. Secondly, the thread waiting on the condition has to be separated across multiple monitors, seen in figure \ref{fig:monitor_cfa}.
    173170
    174171\begin{figure}[H]
     
    180177\end{figure}
    181178
    182 This picture and the proper entry and leave algorithms is the fundamental implementation of internal scheduling (see listing \ref{lst:entry2}). Note that when threads are moved from the condition to the AS-stack, it splits the thread into to pieces. The thread is woken up when all the pieces have moved from the AS-stacks to the active thread seat. In this picture, the threads are split into halves but this is only because there are two monitors in this picture. For a specific signaling operation every monitor needs a piece of thread on its AS-stack.
     179This picture and the proper entry and leave algorithms (see listing \ref{lst:entry2}) is the fundamental implementation of internal scheduling. Note that when a thread is moved from the condition to the AS-stack, it is conceptually split the thread into N pieces, where N is the number of monitors specified in the parameter list. The thread is woken up when all the pieces have popped from the AS-stacks and made active. In this picture, the threads are split into halves but this is only because there are two monitors. For a specific signaling operation every monitor needs a piece of thread on its AS-stack.
    183180
    184181\begin{figure}[b]
     
    209206\end{pseudo}
    210207\end{multicols}
    211 \caption{Entry and exit routine for monitors with internal scheduling}
    212 \label{lst:entry2}
     208\begin{pseudo}[caption={Entry and exit routine for monitors with internal scheduling},label={lst:entry2}]
     209\end{pseudo}
    213210\end{figure}
    214211
     
    223220\end{figure}
    224221
    225 Figure \ref{fig:structs} shows a high level representation of these data-structures. The main idea behind them is that, while figure \ref{fig:monitor_cfa} is a nice illustration in theory, in practice breaking a threads into multiple pieces to put unto intrusive stacks does not make sense. The \code{condition node} is the data structure that is queued into a condition variable and, when signaled, the condition queue is popped and each \code{condition criterion} are moved to the AS-stack. Once all the criterion have be popped from their respective AS-stacks, the thread is woken-up, which is what is shown in listing \ref{lst:entry2}.
     222Figure \ref{fig:structs} shows a high-level representation of these data-structures. The main idea behind them is that, a thread cannot contain an arbitrary number of intrusive stacks for linking onto monitor. The \code{condition node} is the data structure that is queued onto a condition variable and, when signaled, the condition queue is popped and each \code{condition criterion} are moved to the AS-stack. Once all the criterion have be popped from their respective AS-stacks, the thread is woken-up, which is what is shown in listing \ref{lst:entry2}.
    226223
    227224% ======================================================================
     
    230227% ======================================================================
    231228% ======================================================================
    232 Similarly to internal scheduling, external scheduling for multiple monitors relies on the idea that waiting-thread queues are no longer specific to a single monitor, as mentioned in section \ref{extsched}. For internal scheduling, these queues are part of condition variables which are still unique for a given scheduling operation (e.g., no single statement uses multiple conditions). However, in the case of external scheduling, there is no equivalent object which is associated with \code{waitfor} statements. This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired. The monitors being the only objects that have sufficient lifetime and are available on both sides of the \code{waitfor} statement. This requires an algorithm to choose which monitor holds the relevant queue. It is also important that said algorithm be independent of the order in which users list parameters. The proposed algorithm is to fall back on monitor lock ordering and specify that the monitor that is acquired first is the one with the relevant waiting queue. This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint.
     229Similarly to internal scheduling, external scheduling for multiple monitors relies on the idea that waiting-thread queues are no longer specific to a single monitor, as mentioned in section \ref{extsched}. For internal scheduling, these queues are part of condition variables, which are still unique for a given scheduling operation (e.g., no signal statement uses multiple conditions). However, in the case of external scheduling, there is no equivalent object which is associated with \code{waitfor} statements. This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired. These monitors being the only objects that have sufficient lifetime and are available on both sides of the \code{waitfor} statement. This requires an algorithm to choose which monitor holds the relevant queue. It is also important that said algorithm be independent of the order in which users list parameters. The proposed algorithm is to fall back on monitor lock ordering (sorting by address) and specify that the monitor that is acquired first is the one with the relevant waiting queue. This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint.
    233230
    234231This algorithm choice has two consequences :
    235232\begin{itemize}
    236         \item The queue of the highest priority monitor is no longer a true FIFO queue because threads can be moved to the front of the queue. These queues need to contain a set of monitors for each of the waiting threads. Therefore, another thread whose set contains the same highest priority monitor but different lower priority monitors may arrive first but enter the critical section after a thread with the correct pairing.
    237         \item The queue of the lowest priority monitor is both required and potentially unused. Indeed, since it is not known at compile time which monitor will be the lowest priority monitor, every monitor needs to have the correct queues even though it is possible that some queues will go unused for the entire duration of the program, for example if a monitor is only used in a specific pair.
     233        \item The queue of the monitor with the lowest address is no longer a true FIFO queue because threads can be moved to the front of the queue. These queues need to contain a set of monitors for each of the waiting threads. Therefore, another thread whose set contains the same lowest address monitor but different lower priority monitors may arrive first but enter the critical section after a thread with the correct pairing.
     234        \item The queue of the lowest priority monitor is both required and potentially unused. Indeed, since it is not known at compile time which monitor is the monitor with have the lowest address, every monitor needs to have the correct queues even though it is possible that some queues go unused for the entire duration of the program, for example if a monitor is only used in a specific pair.
    238235\end{itemize}
    239 
    240236Therefore, the following modifications need to be made to support external scheduling :
    241237\begin{itemize}
    242         \item The threads waiting on the entry-queue need to keep track of which routine is trying to enter, and using which set of monitors. The \code{mutex} routine already has all the required information on its stack so the thread only needs to keep a pointer to that information.
    243         \item The monitors need to keep a mask of acceptable routines. This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it. It also needs storage to keep track of which routine was accepted. Since this information is not specific to any monitor, the monitors actually contain a pointer to an integer on the stack of the waiting thread. Note that the complete mask can be pushed to any owned monitors, regardless of \code{when} statements, the \code{waitfor} statement is used in a context where the thread already has full ownership of (at least) every concerned monitor and therefore monitors will refuse all calls no matter what.
     238        \item The threads waiting on the entry-queue need to keep track of which routine it is trying to enter, and using which set of monitors. The \code{mutex} routine already has all the required information on its stack so the thread only needs to keep a pointer to that information.
     239        \item The monitors need to keep a mask of acceptable routines. This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it. It also needs storage to keep track of which routine was accepted. Since this information is not specific to any monitor, the monitors actually contain a pointer to an integer on the stack of the waiting thread. Note that if a thread has acquired two monitors but executes a \code{waitfor} with only one monitor as a parameter, setting the mask of acceptable routines to both monitors will not cause any problems since the extra monitor will not change ownership regardless. This becomes relevant when \code{when} clauses affect the number of monitors passed to a \code{waitfor} statement.
    244240        \item The entry/exit routine need to be updated as shown in listing \ref{lst:entry3}.
    245241\end{itemize}
     
    280276\end{pseudo}
    281277\end{multicols}
    282 \caption{Entry and exit routine for monitors with internal scheduling and external scheduling}
    283 \label{lst:entry3}
     278\begin{pseudo}[caption={Entry and exit routine for monitors with internal scheduling and external scheduling},label={lst:entry3}]
     279\end{pseudo}
    284280\end{figure}
    285281
     
    326322\end{pseudo}
    327323\end{multicols}
    328 \caption{Pseudo code for the \code{waitfor} routine and the \code{mutex} entry routine for destructors}
    329 \label{lst:entry-dtor}
    330 \end{figure}
     324\begin{pseudo}[caption={Pseudo code for the \code{waitfor} routine and the \code{mutex} entry routine for destructors},label={lst:entry-dtor}]
     325\end{pseudo}
     326\end{figure}
  • doc/proposals/concurrency/text/results.tex

    rf7a4f89 rcf966b5  
    66\section{Machine setup}
    77Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks. All tests where made on this machine.
    8 \begin{figure}[H]
     8\begin{table}[H]
    99\begin{center}
    1010\begin{tabular}{| l | r | l | r |}
     
    2828\hline
    2929Compiler                        & GCC 6.3.0             & Translator    & CFA 1.0.0 \\
     30\hline
     31Java version            & OpenJDK-9             & Go version    & 1.9.2 \\
    3032\hline
    3133\end{tabular}
     
    3335\caption{Machine setup used for the tests}
    3436\label{tab:machine}
    35 \end{figure}
     37\end{table}
    3638
    3739\section{Micro benchmarks}
     
    3941\begin{pseudo}
    4042#define BENCH(run, result)
    41         gettime();
     43        before = gettime();
    4244        run;
    43         gettime();
     45        after  = gettime();
    4446        result = (after - before) / N;
    4547\end{pseudo}
     
    4749
    4850\subsection{Context-switching}
    49 The first interesting benchmark is to measure how long context-switches take. The simplest approach to do this is to yield on a thread, which executes a 2-step context switch. In order to make the comparison fair, coroutines also execute a 2-step context-switch, which is a resume/suspend cycle instead of a yield. Listing \ref{lst:ctx-switch} shows the code for coroutines and threads. All omitted tests are functionally identical to one of these tests. The results can be shown in table \ref{tab:ctx-switch}.
     51The first interesting benchmark is to measure how long context-switches take. The simplest approach to do this is to yield on a thread, which executes a 2-step context switch. In order to make the comparison fair, coroutines also execute a 2-step context-switch (\gls{uthread} to \gls{kthread} then \gls{kthread} to \gls{uthread}), which is a resume/suspend cycle instead of a yield. Listing \ref{lst:ctx-switch} shows the code for coroutines and threads whith the results in table \ref{tab:ctx-switch}. All omitted tests are functionally identical to one of these tests.
    5052\begin{figure}
    5153\begin{multicols}{2}
     
    8890\end{cfacode}
    8991\end{multicols}
    90 \caption{\CFA benchmark code used to measure context-switches for coroutines and threads.}
    91 \label{lst:ctx-switch}
    92 \end{figure}
    93 
    94 \begin{figure}
    95 \begin{center}
    96 \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
    97 \cline{2-4}
    98 \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
    99 \hline
    100 Kernel Threads          & 239           & 242.57        & 5.54 \\
    101 \CFA Coroutines         & 38            & 38            & 0    \\
    102 \CFA Threads            & 102           & 102.39        & 1.57 \\
    103 \uC Coroutines          & 46            & 46.68 & 0.47 \\
    104 \uC Threads                     & 98            & 99.39 & 1.52 \\
     92\begin{cfacode}[caption={\CFA benchmark code used to measure context-switches for coroutines and threads.},label={lst:ctx-switch}]
     93\end{cfacode}
     94\end{figure}
     95
     96\begin{table}
     97\begin{center}
     98\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     99\cline{2-4}
     100\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
     101\hline
     102Kernel Thread   & 239           & 242.57        & 5.54 \\
     103\CFA Coroutine  & 38            & 38            & 0    \\
     104\CFA Thread             & 102           & 102.39        & 1.57 \\
     105\uC Coroutine   & 46            & 46.68 & 0.47 \\
     106\uC Thread              & 98            & 99.39 & 1.52 \\
     107Goroutine               & 148           & 148.0 & 0 \\
     108Java Thread             & 271           & 271.0 & 0 \\
    105109\hline
    106110\end{tabular}
     
    108112\caption{Context Switch comparison. All numbers are in nanoseconds(\si{\nano\second})}
    109113\label{tab:ctx-switch}
    110 \end{figure}
     114\end{table}
    111115
    112116\subsection{Mutual-exclusion}
    113 The next interesting benchmark is to measure the overhead to enter/leave a critical-section. For monitors, the simplest approach is to measure how long it takes enter and leave a monitor routine. Listing \ref{lst:mutex} shows the code for \CFA. To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a pthread mutex lock are also measured. The results can be shown in table \ref{tab:mutex}.
    114 
    115 \begin{figure}
    116 \begin{cfacode}
     117The next interesting benchmark is to measure the overhead to enter/leave a critical-section. For monitors, the simplest approach is to measure how long it takes to enter and leave a monitor routine. Listing \ref{lst:mutex} shows the code for \CFA. To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a pthread mutex lock are also measured. The results can be shown in table \ref{tab:mutex}.
     118
     119\begin{figure}
     120\begin{cfacode}[caption={\CFA benchmark code used to measure mutex routines.},label={lst:mutex}]
    117121monitor M {};
    118122void __attribute__((noinline)) call( M & mutex m /*, m2, m3, m4*/ ) {}
     
    129133}
    130134\end{cfacode}
    131 \caption{\CFA benchmark code used to measure mutex routines.}
    132 \label{lst:mutex}
    133 \end{figure}
    134 
    135 \begin{figure}
     135\end{figure}
     136
     137\begin{table}
    136138\begin{center}
    137139\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     
    140142\hline
    141143C routine                                               & 2             & 2             & 0      \\
     144FetchAdd + FetchSub                             & 2             & 2             & 0      \\
    142145Pthreads Mutex Lock                             & 31            & 31.86 & 0.99   \\
    143146\uC \code{monitor} member routine               & 30            & 30            & 0      \\
     
    145148\CFA \code{mutex} routine, 2 argument   & 82            & 83            & 1.93   \\
    146149\CFA \code{mutex} routine, 4 argument   & 165           & 161.15        & 54.04  \\
     150Java synchronized routine                       & 165           & 161.15        & 54.04  \\
    147151\hline
    148152\end{tabular}
     
    150154\caption{Mutex routine comparison. All numbers are in nanoseconds(\si{\nano\second})}
    151155\label{tab:mutex}
    152 \end{figure}
     156\end{table}
    153157
    154158\subsection{Internal scheduling}
    155 The Internal scheduling benchmark measures the cost of waiting on and signalling a condition variable. Listing \ref{lst:int-sched} shows the code for \CFA. The results can be shown in table \ref{tab:int-sched}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
    156 
    157 \begin{figure}
    158 \begin{cfacode}
     159The internal-scheduling benchmark measures the cost of waiting on and signalling a condition variable. Listing \ref{lst:int-sched} shows the code for \CFA, with results table \ref{tab:int-sched}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
     160
     161\begin{figure}
     162\begin{cfacode}[caption={Benchmark code for internal scheduling},label={lst:int-sched}]
    159163volatile int go = 0;
    160164condition c;
     
    187191}
    188192\end{cfacode}
    189 \caption{Benchmark code for internal scheduling}
    190 \label{lst:int-sched}
    191 \end{figure}
    192 
    193 \begin{figure}
     193\end{figure}
     194
     195\begin{table}
    194196\begin{center}
    195197\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     
    201203\CFA \code{signal}, 2 \code{monitor}    & 1531  & 1550.75       & 32.77 \\
    202204\CFA \code{signal}, 4 \code{monitor}    & 2288.5        & 2326.86       & 54.73 \\
     205Java \code{notify}                              & 2288.5        & 2326.86       & 54.73 \\
    203206\hline
    204207\end{tabular}
     
    206209\caption{Internal scheduling comparison. All numbers are in nanoseconds(\si{\nano\second})}
    207210\label{tab:int-sched}
    208 \end{figure}
     211\end{table}
    209212
    210213\subsection{External scheduling}
    211 The Internal scheduling benchmark measures the cost of the \code{waitfor} statement (\code{_Accept} in \uC). Listing \ref{lst:ext-sched} shows the code for \CFA. The results can be shown in table \ref{tab:ext-sched}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
    212 
    213 \begin{figure}
    214 \begin{cfacode}
     214The Internal scheduling benchmark measures the cost of the \code{waitfor} statement (\code{_Accept} in \uC). Listing \ref{lst:ext-sched} shows the code for \CFA, with results in table \ref{tab:ext-sched}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
     215
     216\begin{figure}
     217\begin{cfacode}[caption={Benchmark code for external scheduling},label={lst:ext-sched}]
    215218volatile int go = 0;
    216219monitor M {};
     
    242245}
    243246\end{cfacode}
    244 \caption{Benchmark code for external scheduling}
    245 \label{lst:ext-sched}
    246 \end{figure}
    247 
    248 \begin{figure}
     247\end{figure}
     248
     249\begin{table}
    249250\begin{center}
    250251\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     
    261262\caption{External scheduling comparison. All numbers are in nanoseconds(\si{\nano\second})}
    262263\label{tab:ext-sched}
    263 \end{figure}
     264\end{table}
    264265
    265266\subsection{Object creation}
    266 Finally, the last benchmark measured is the cost of creation for concurrent objects. Listing \ref{lst:creation} shows the code for pthreads and \CFA threads. The results can be shown in table \ref{tab:creation}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests. The only note here is that the call-stacks of \CFA coroutines are lazily created, therefore without priming the coroutine, the creation cost is very low.
    267 
    268 \begin{figure}
    269 \begin{multicols}{2}
     267Finally, the last benchmark measurs the cost of creation for concurrent objects. Listing \ref{lst:creation} shows the code for pthreads and \CFA threads, with results shown in table \ref{tab:creation}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests. The only note here is that the call-stacks of \CFA coroutines are lazily created, therefore without priming the coroutine, the creation cost is very low.
     268
     269\begin{figure}
     270\begin{center}
    270271pthread
    271 \begin{cfacode}
     272\begin{ccode}
    272273int main() {
    273274        BENCH(
    274275                for(size_t i=0; i<n; i++) {
    275276                        pthread_t thread;
    276                         if(pthread_create(
    277                                 &thread,
    278                                 NULL,
    279                                 foo,
    280                                 NULL
    281                         ) < 0) {
     277                        if(pthread_create(&thread,NULL,foo,NULL)<0) {
    282278                                perror( "failure" );
    283279                                return 1;
    284280                        }
    285281
    286                         if(pthread_join(
    287                                 thread,
    288                                 NULL
    289                         ) < 0) {
     282                        if(pthread_join(thread, NULL)<0) {
    290283                                perror( "failure" );
    291284                                return 1;
     
    296289        printf("%llu\n", result);
    297290}
    298 \end{cfacode}
    299 \columnbreak
     291\end{ccode}
     292
     293
     294
    300295\CFA Threads
    301296\begin{cfacode}
     
    307302                result
    308303        )
    309 
    310         printf("%llu\n", result);
    311 }
    312 \end{cfacode}
    313 \end{multicols}
    314 \caption{Benchmark code for pthreads and \CFA to measure object creation}
    315 \label{lst:creation}
    316 \end{figure}
    317 
    318 \begin{figure}
     304        printf("%llu\n", result);
     305}
     306\end{cfacode}
     307\end{center}
     308\begin{cfacode}[caption={Benchmark code for pthreads and \CFA to measure object creation},label={lst:creation}]
     309\end{cfacode}
     310\end{figure}
     311
     312\begin{table}
    319313\begin{center}
    320314\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     
    323317\hline
    324318Pthreads                        & 26974.5       & 26977 & 124.12 \\
    325 \CFA Coroutines Lazy    & 5             & 5             & 0      \\
    326 \CFA Coroutines Eager   & 335.0 & 357.67        & 34.2   \\
    327 \CFA Threads            & 1122.5        & 1109.86       & 36.54  \\
    328 \uC Coroutines          & 106           & 107.04        & 1.61   \\
    329 \uC Threads                     & 525.5 & 533.04        & 11.14  \\
     319\CFA Coroutine Lazy     & 5             & 5             & 0      \\
     320\CFA Coroutine Eager    & 335.0 & 357.67        & 34.2   \\
     321\CFA Thread                     & 1122.5        & 1109.86       & 36.54  \\
     322\uC Coroutine           & 106           & 107.04        & 1.61   \\
     323\uC Thread                      & 525.5 & 533.04        & 11.14  \\
     324Goroutine                       & 525.5 & 533.04        & 11.14  \\
     325Java Thread                     & 525.5 & 533.04        & 11.14  \\
    330326\hline
    331327\end{tabular}
     
    333329\caption{Creation comparison. All numbers are in nanoseconds(\si{\nano\second})}
    334330\label{tab:creation}
    335 \end{figure}
     331\end{table}
  • doc/proposals/concurrency/text/together.tex

    rf7a4f89 rcf966b5  
    77
    88\section{Threads as monitors}
    9 As it was subtly alluded in section \ref{threads}, \code{threads} in \CFA are in fact monitors, which means that all monitor features are available when using threads. For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine :
    10 \begin{cfacode}
     9As it was subtly alluded in section \ref{threads}, \code{thread}s in \CFA are in fact monitors, which means that all monitor features are available when using threads. For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine :
     10\begin{figure}[H]
     11\begin{cfacode}[caption={Toy simulator using \code{thread}s and \code{monitor}s.},label={lst:engine-v1}]
    1112// Visualization declaration
    1213thread Renderer {} renderer;
     
    3637}
    3738\end{cfacode}
     39\end{figure}
    3840One of the obvious complaints of the previous code snippet (other than its toy-like simplicity) is that it does not handle exit conditions and just goes on forever. Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner :
    39 \begin{cfacode}
     41\begin{figure}[H]
     42\begin{cfacode}[caption={Same toy simulator with proper termination condition.},label={lst:engine-v2}]
    4043// Visualization declaration
    4144thread Renderer {} renderer;
     
    7679// Call destructor for renderer to signify shutdown
    7780\end{cfacode}
     81\end{figure}
    7882
    7983\section{Fibers \& Threads}
     
    8488}
    8589\end{cfacode}
    86 This function is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice i.e. no preemption. However, once clusters are fully implemented, it will be possible to create fibers and uthreads in on the same system :
     90This function is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice, i.e., no preemption. However, once clusters are fully implemented, it will be possible to create fibers and \glspl{uthread} in the same system, as in listing \ref{lst:fiber-uthread}
    8791\begin{figure}
    88 \begin{cfacode}
     92\begin{cfacode}[caption={Using fibers and \glspl{uthread} side-by-side in \CFA},label={lst:fiber-uthread}]
    8993//Cluster forward declaration
    9094struct cluster;
  • doc/proposals/concurrency/thesis.tex

    rf7a4f89 rcf966b5  
    11% requires tex packages: texlive-base texlive-latex-base tex-common texlive-humanities texlive-latex-extra texlive-fonts-recommended
    22
    3 % inline code ... (copyright symbol) emacs: C-q M-)
    4 % red highlighting ... (registered trademark symbol) emacs: C-q M-.
    5 % blue highlighting ... (sharp s symbol) emacs: C-q M-_
    6 % green highlighting ... (cent symbol) emacs: C-q M-"
    7 % LaTex escape ... (section symbol) emacs: C-q M-'
    8 % keyword escape ... (pilcrow symbol) emacs: C-q M-^
     3% inline code �...� (copyright symbol) emacs: C-q M-)
     4% red highlighting �...� (registered trademark symbol) emacs: C-q M-.
     5% blue highlighting �...� (sharp s symbol) emacs: C-q M-_
     6% green highlighting �...� (cent symbol) emacs: C-q M-"
     7% LaTex escape �...� (section symbol) emacs: C-q M-'
     8% keyword escape �...� (pilcrow symbol) emacs: C-q M-^
    99% math escape $...$ (dollar symbol)
    1010
     
    8282\rfoot{v\input{version}}
    8383
    84 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    8584
     85
     86%======================================================================
     87%   L O G I C A L    D O C U M E N T -- the content of your thesis
     88%======================================================================
    8689\begin{document}
    87 % \linenumbers
    8890
    89 \title{Concurrency in \CFA}
    90 \author{Thierry Delisle \\
    91 School of Computer Science, University of Waterloo, \\ Waterloo, Ontario, Canada
    92 }
     91% For a large document, it is a good idea to divide your thesis
     92% into several files, each one containing one chapter.
     93% To illustrate this idea, the "front pages" (i.e., title page,
     94% declaration, borrowers' page, abstract, acknowledgements,
     95% dedication, table of contents, list of tables, list of figures,
     96% nomenclature) are contained within the file "thesis-frontpgs.tex" which is
     97% included into the document by the following statement.
     98%----------------------------------------------------------------------
     99% FRONT MATERIAL
     100%----------------------------------------------------------------------
     101\input{frontpgs}
    93102
    94 \maketitle
    95 
    96 \tableofcontents
     103%----------------------------------------------------------------------
     104% MAIN BODY
     105%----------------------------------------------------------------------
    97106
    98107\input{intro}
     
    112121\input{results}
    113122
    114 \input{conclusion}
    115 
    116123\input{future}
    117 
    118 \input{acknowledge}
    119124
    120125\clearpage
  • doc/proposals/concurrency/version

    rf7a4f89 rcf966b5  
    1 0.11.162
     10.11.278
Note: See TracChangeset for help on using the changeset viewer.