Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • doc/proposals/concurrency/text/concurrency.tex

    rfb31cb8 r21a1efb  
    44% ======================================================================
    55% ======================================================================
    6 Several tool can be used to solve concurrency challenges. Since many of these challenges appear with the use of mutable shared-state, some languages and libraries simply disallow mutable shared-state (Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, Akka (Scala)~\cite{Akka}). In these paradigms, interaction among concurrent objects relies on message passing~\cite{Thoth,Harmony,V-Kernel} or other paradigms closely relate to networking concepts (channels\cit for example). However, in languages that use routine calls as their core abstraction-mechanism, these approaches force a clear distinction between concurrent and non-concurrent paradigms (i.e., message passing versus routine call). This distinction in turn means that, in order to be effective, programmers need to learn two sets of designs patterns. While this distinction can be hidden away in library code, effective use of the librairy still has to take both paradigms into account.
     6Several tool can be used to solve concurrency challenges. Since many of these challenges appear with the use of mutable shared-state, some languages and libraries simply disallow mutable shared-state (Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, Akka (Scala)~\cite{Akka}). In these paradigms, interaction among concurrent objects relies on message passing~\cite{Thoth,Harmony,V-Kernel} or other paradigms that closely relate to networking concepts (channels\cit for example). However, in languages that use routine calls as their core abstraction-mechanism, these approaches force a clear distinction between concurrent and non-concurrent paradigms (i.e., message passing versus routine call). This distinction in turn means that, in order to be effective, programmers need to learn two sets of designs patterns. While this distinction can be hidden away in library code, effective use of the librairy still has to take both paradigms into account.
    77
    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 desireable to have a higher-level construct be the core concurrency paradigm~\cite{HPP:Study}.
    99
    10 An approach that is worth mentionning because it is gaining in popularity is transactionnal memory~\cite{Dice10}[Check citation]. While this approach is even pursued by system languages like \CC\cit, 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.
    11 
    12 One 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.
     10An approach that is worth mentionning because it is gaining in popularity is transactionnal memory~\cite{Dice10}[Check citation]. While this approach is even pursued by system languages like \CC\cit, the performance and feature set is currently too restrictive to be the main concurrency paradigm for general purpose language, which is why it was rejected as the core paradigm for concurrency in \CFA.
     11
     12One 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.
    1313
    1414\section{Basics}
    15 Non-determinism requires concurrent systems to offer support for mutual-exclusion and synchronisation. Mutual-exclusion is the concept that only a fixed number of threads can access a critical section at any given time, where a critical section is a group of instructions on an associated portion of data that requires the restricted access. On the other hand, synchronization enforces relative ordering of execution and synchronization tools provide numerous mechanisms to establish timing relationships among threads.
     15Non-determinism requires concurrent systems to offer support for mutual-exclusion and synchronisation. Mutual-exclusion is the concept that only a fixed number of threads can access a critical section at any given time, where a critical section is a group of instructions on an associated portion of data that requires the restricted access. On the other hand, synchronization enforces relative ordering of execution and synchronization tools numerous mechanisms to establish timing relationships among threads.
    1616
    1717\subsection{Mutual-Exclusion}
    18 As mentionned above, mutual-exclusion is the guarantee that only a fix number of threads can enter a critical section at once. However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use. Methods range from low-level locks, which are fast and flexible but require significant attention to be correct, to  higher-level mutual-exclusion methods, which sacrifice some performance in order to improve ease of use. Ease of use comes by either guaranteeing some problems cannot occur (e.g., being deadlock free) or by offering a more explicit coupling between data and corresponding critical section. For example, the \CC \code{std::atomic<T>} offers an easy way to express mutual-exclusion on a restricted set of operations (e.g.: reading/writing large types atomically). Another challenge with low-level locks is composability. Locks have restricted composability because it takes careful organising for multiple locks to be used while preventing deadlocks. Easing composability is another feature higher-level mutual-exclusion mechanisms often offer.
     18As mentionned above, mutual-exclusion is the guarantee that only a fix number of threads can enter a critical section at once. However, many solution exists for mutual exclusion which vary in terms of performance, flexibility and ease of use. Methods range from low-level locks, which are fast and flexible but require significant attention to be correct, to  higher-level mutual-exclusion methods, which sacrifice some performance in order to improve ease of use. Ease of use comes by either guaranteeing some problems cannot occur (e.g., being deadlock free) or by offering a more explicit coupling between data and corresponding critical section. For example, the \CC \code{std::atomic<T>} which offer an easy way to express mutual-exclusion on a restricted set of operations (.e.g: reading/writing large types atomically). Another challenge with low-level locks is composability. Locks are not composable because it takes careful organising for multiple locks to be used while preventing deadlocks. Easing composability is another feature higher-level mutual-exclusion mechanisms often offer.
    1919
    2020\subsection{Synchronization}
    21 As for mutual-exclusion, low-level synchronisation primitives often offer good performance and good flexibility at the cost of ease of use. Again, higher-level mechanism often simplify usage by adding better coupling between synchronization and data, e.g.: message passing, or offering simple solution to otherwise involved challenges. An example is barging. As mentioned above, synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}. Most of the time, synchronisation happens around a critical section, where threads must acquire critical sections in a certain order. However, it may also be desirable to guarantee that event \textit{Z} does not occur between \textit{X} and \textit{Y}. Not satisfying this property called barging. For example, where event \textit{X} tries to effect event \textit{Y} but another thread acquires the critical section and emits \textit{Z} before \textit{Y}. Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs. This challenge is often split into two different methods, barging avoidance and barging prevention. Algorithms that use status flags and other flag variables to detect barging threads are said to be using barging avoidance while algorithms that baton-passing locks between threads instead of releasing the locks are said to be using barging prevention.
     21As for mutual-exclusion, low level synchronisation primitive often offer good performance and good flexibility at the cost of ease of use. Again, higher-level mechanism often simplify usage by adding better coupling between synchronization and data, .eg., message passing, or offering simple solution to otherwise involved challenges. An example of this is barging. As mentionned above synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}. Most of the time synchronisation happens around a critical section, where threads most acquire said critical section in a certain order. However, it may also be desired to be able to guarantee that event \textit{Z} does not occur between \textit{X} and \textit{Y}. This is called barging, where event \textit{X} tries to effect event \textit{Y} but anoter thread races to grab the critical section and emits \textit{Z} before \textit{Y}. Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
    2222
    2323% ======================================================================
     
    2828A monitor is a set of routines that ensure mutual exclusion when accessing shared state. This concept is generally associated with Object-Oriented Languages like Java~\cite{Java} or \uC~\cite{uC++book} but does not strictly require OO semantics. The only requirements is the ability to declare a handle to a shared object and a set of routines that act on it :
    2929\begin{cfacode}
    30 typedef /*some monitor type*/ monitor;
    31 int f(monitor & m);
    32 
    33 int main() {
    34         monitor m;  //Handle m
    35         f(m);       //Routine using handle
    36 }
     30        typedef /*some monitor type*/ monitor;
     31        int f(monitor & m);
     32
     33        int main() {
     34                monitor m;  //Handle m
     35                f(m);       //Routine using handle
     36        }
    3737\end{cfacode}
    3838
     
    4747
    4848\begin{cfacode}
    49 monitor counter_t { /*...see section $\ref{data}$...*/ };
    50 
    51 void ?{}(counter_t & nomutex this); //constructor
    52 size_t ++?(counter_t & mutex this); //increment
    53 
    54 //need for mutex is platform dependent
    55 void ?{}(size_t * this, counter_t & mutex cnt); //conversion
    56 \end{cfacode}
     49        monitor counter_t { /*...see section $\ref{data}$...*/ };
     50
     51        void ?{}(counter_t & nomutex this); //constructor
     52        size_t ++?(counter_t & mutex this); //increment
     53
     54        //need for mutex is platform dependent
     55        void ?{}(size_t * this, counter_t & mutex cnt); //conversion
     56\end{cfacode}
     57
     58Here, 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 constructed should never be shared and therefore does not require mutual exclusion. 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 an \code{size_t} is an atomic operation.
     59
     60Having 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 to make having exactly one of these keywords mandatory, which would provide the same semantics but without the ambiguity of supporting routines 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 a doubt wheter 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.
     61
     62
     63The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
     64\begin{cfacode}
     65int f1(monitor & mutex m);
     66int f2(const monitor & mutex m);
     67int f3(monitor ** mutex m);
     68int f4(monitor * mutex m []);
     69int f5(graph(monitor*) & mutex m);
     70\end{cfacode}
     71The problem is to indentify which object(s) should be acquired. Furthermore, each object needs to be acquired only once. In the case of simple routines like \code{f1} and \code{f2} it is easy to identify an exhaustive list of objects to acquire on entry. Adding indirections (\code{f3}) still allows the compiler and programmer to indentify which object is acquired. However, adding in arrays (\code{f4}) makes it much harder. Array lengths are not necessarily known in C, and even then making sure objects are only acquired once becomes none-trivial. This can be extended to absurd limits like \code{f5}, which uses a graph of monitors. To keep everyone as sane as possible~\cite{Chicken}, this projects imposes the requirement that a routine may only acquire one monitor per parameter and it must be the type of the parameter with one level of indirection (ignoring potential qualifiers). Also note that while routine \code{f3} can be supported, meaning that monitor \code{**m} is be acquired, passing an array to this routine would be type safe and yet result in undefined behavior because only the first element of the array is acquired. This is specially true for non-copyable objects like monitors, where an array of pointers is simplest way to express a group of monitors. However, this ambiguity is part of the C type-system with respects to arrays. For this reason, \code{mutex} is disallowed in the context where arrays may be passed:
     72
     73\begin{cfacode}
     74int f1(monitor & mutex m);   //Okay : recommanded case
     75int f2(monitor * mutex m);   //Okay : could be an array but probably not
     76int f3(monitor mutex m []);  //Not Okay : Array of unkown length
     77int f4(monitor ** mutex m);  //Not Okay : Could be an array
     78int f5(monitor * mutex m []); //Not Okay : Array of unkown length
     79\end{cfacode}
     80
     81Unlike object-oriented monitors, where calling a mutex member \emph{implicitly} acquires mutual-exclusion, \CFA uses an explicit mechanism to acquire mutual-exclusion. A consequence of this approach is that it extends naturally to multi-monitor calls.
     82\begin{cfacode}
     83int f(MonitorA & mutex a, MonitorB & mutex b);
     84
     85MonitorA a;
     86MonitorB b;
     87f(a,b);
     88\end{cfacode}
     89The capacity to acquire multiple locks before entering a critical section is called \emph{\gls{group-acquire}}. In practice, writing multi-locking routines that do not lead to deadlocks is tricky. Having language support for such a feature is therefore a significant asset for \CFA. In the case presented above, \CFA guarantees that the order of aquisition is consistent across calls to routines using the same monitors as arguments. However, since \CFA monitors use multi-acquisition locks, users can effectively force the acquiring order. For example, notice which routines use \code{mutex}/\code{nomutex} and how this affects aquiring order:
     90\begin{cfacode}
     91        void foo(A & mutex a, B & mutex b) { //acquire a & b
     92                ...
     93        }
     94
     95        void bar(A & mutex a, B & /*nomutex*/ b) { //acquire a
     96                ... foo(a, b); ... //acquire b
     97        }
     98
     99        void baz(A & /*nomutex*/ a, B & mutex b) { //acquire b
     100                ... foo(a, b); ... //acquire a
     101        }
     102\end{cfacode}
     103The multi-acquisition monitor lock allows a monitor lock to be acquired by both \code{bar} or \code{baz} and acquired again in \code{foo}. In the calls to \code{bar} and \code{baz} the monitors are acquired in opposite order.
     104
     105However, such use leads the lock acquiring order problem. In the example above, the user uses implicit ordering in the case of function \code{foo} but explicit ordering in the case of \code{bar} and \code{baz}. This subtle mistake means that calling these routines concurrently may lead to deadlock and is therefore undefined behavior. As shown on several occasion\cit, solving this problem requires:
     106\begin{enumerate}
     107        \item Dynamically tracking of the monitor-call order.
     108        \item Implement rollback semantics.
     109\end{enumerate}
     110While the first requirement is already a significant constraint on the system, implementing a general rollback semantics in a C-like language is prohibitively complex \cit. In \CFA, users simply need to be carefull when acquiring multiple monitors at the same time.
     111
     112Finally, for convenience, monitors support multiple acquiring, that is acquiring a monitor while already holding it does not cause a deadlock. It simply increments an internal counter which is then used to release the monitor after the number of acquires and releases match up. This is particularly usefull when monitor routines use other monitor routines as helpers or for recursions. For example:
     113\begin{cfacode}
     114monitor bank {
     115        int money;
     116        log_t usr_log;
     117};
     118
     119void deposit( bank & mutex b, int deposit ) {
     120        b.money += deposit;
     121        b.usr_log | "Adding" | deposit | endl;
     122}
     123
     124void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) {
     125        deposit( mybank, -me2you );
     126        deposit( yourbank, me2you );
     127}
     128\end{cfacode}
     129
     130% ======================================================================
     131% ======================================================================
     132\subsection{Data semantics} \label{data}
     133% ======================================================================
     134% ======================================================================
     135Once the call semantics are established, the next step is to establish data semantics. Indeed, until now a monitor is used simply as a generic handle but in most cases monitors contain shared data. This data should be intrinsic to the monitor declaration to prevent any accidental use of data without its appropriate protection. For example, here is a complete version of the counter showed in section \ref{call}:
     136\begin{cfacode}
     137monitor counter_t {
     138        int value;
     139};
     140
     141void ?{}(counter_t & this) {
     142        this.cnt = 0;
     143}
     144
     145int ?++(counter_t & mutex this) {
     146        return ++this.value;
     147}
     148
     149//need for mutex is platform dependent here
     150void ?{}(int * this, counter_t & mutex cnt) {
     151        *this = (int)cnt;
     152}
     153\end{cfacode}
     154
    57155This counter is used as follows:
    58156\begin{center}
     
    73171Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting.
    74172
    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 constructed should never be shared and therefore does not require mutual exclusion. 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 multiple times the same monitor without deadlock. For example, figure \ref{fig:search} uses recursion and \gls{multi-acq} to print values inside a binary tree.
    78 \begin{figure}
    79 \label{fig:search}
    80 \begin{cfacode}
    81 monitor printer { ... };
    82 struct tree {
    83         tree * left, right;
    84         char * value;
    85 };
    86 void print(printer & mutex p, char * v);
    87 
    88 void print(printer & mutex p, tree * t) {
    89         print(p, t->value);
    90         print(p, t->left );
    91         print(p, t->right);
    92 }
    93 \end{cfacode}
    94 \caption{Recursive printing algorithm using \gls{multi-acq}.}
    95 \end{figure}
    96 
    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 would provide 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}.
    98 
    99 The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
    100 \begin{cfacode}
    101 int f1(monitor & mutex m);
    102 int f2(const monitor & mutex m);
    103 int f3(monitor ** mutex m);
    104 int f4(monitor * mutex m []);
    105 int f5(graph(monitor*) & mutex m);
    106 \end{cfacode}
    107 The problem is to indentify which object(s) should be acquired. Furthermore, each object needs to be acquired only once. In the case of simple routines like \code{f1} and \code{f2} it is easy to identify an exhaustive list of objects to acquire on entry. Adding indirections (\code{f3}) still allows the compiler and programmer to indentify which object is acquired. However, adding in arrays (\code{f4}) makes it much harder. Array lengths are not necessarily known in C, and even then making sure objects are only acquired once becomes none-trivial. This problem can be extended to absurd limits like \code{f5}, which uses a graph of monitors. To make the issue tractable, this project imposes the requirement that a routine may only acquire one monitor per parameter and it must be the type of the parameter with at most one level of indirection (ignoring potential qualifiers). Also note that while routine \code{f3} can be supported, meaning that monitor \code{**m} is be acquired, passing an array to this routine would be type safe and yet result in undefined behavior because only the first element of the array is acquired. However, this ambiguity is part of the C type-system with respects to arrays. For this reason, \code{mutex} is disallowed in the context where arrays may be passed:
    108 \begin{cfacode}
    109 int f1(monitor & mutex m);   //Okay : recommanded case
    110 int f2(monitor * mutex m);   //Okay : could be an array but probably not
    111 int f3(monitor mutex m []);  //Not Okay : Array of unkown length
    112 int f4(monitor ** mutex m);  //Not Okay : Could be an array
    113 int f5(monitor * mutex m []); //Not Okay : Array of unkown length
    114 \end{cfacode}
    115 Note that not all array functions are actually distinct in the type system sense. However, even the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
    116 
    117 Unlike object-oriented monitors, where calling a mutex member \emph{implicitly} acquires mutual-exclusion often receives an object, \CFA uses an explicit mechanism to acquire mutual-exclusion. A consequence of this approach is that it extends naturally to multi-monitor calls.
    118 \begin{cfacode}
    119 int f(MonitorA & mutex a, MonitorB & mutex b);
    120 
    121 MonitorA a;
    122 MonitorB b;
    123 f(a,b);
    124 \end{cfacode}
    125 The capacity to acquire multiple locks before entering a critical section is called \emph{\gls{bulk-acq}}. In practice, writing multi-locking routines that do not lead to deadlocks is tricky. Having language support for such a feature is therefore a significant asset for \CFA. In the case presented above, \CFA guarantees that the order of aquisition is consistent across calls to routines using the same monitors as arguments. However, since \CFA monitors use \gls{multi-acq} locks, users can effectively force the acquiring order. For example, notice which routines use \code{mutex}/\code{nomutex} and how this affects aquiring order:
    126 \begin{cfacode}
    127 void foo(A & mutex a, B & mutex b) { //acquire a & b
    128         ...
    129 }
    130 
    131 void bar(A & mutex a, B & /*nomutex*/ b) { //acquire a
    132         ... foo(a, b); ... //acquire b
    133 }
    134 
    135 void baz(A & /*nomutex*/ a, B & mutex b) { //acquire b
    136         ... foo(a, b); ... //acquire a
    137 }
    138 \end{cfacode}
    139 The \gls{multi-acq} monitor lock allows a monitor lock to be acquired by both \code{bar} or \code{baz} and acquired again in \code{foo}. In the calls to \code{bar} and \code{baz} the monitors are acquired in opposite order.
    140 
    141 However, such use leads to the lock acquiring order problem. In the example above, the user uses implicit ordering in the case of function \code{foo} but explicit ordering in the case of \code{bar} and \code{baz}. This subtle mistake means that calling these routines concurrently may lead to deadlock and is therefore undefined behavior. As shown on several occasion\cit, solving this problem requires:
    142 \begin{enumerate}
    143         \item Dynamically tracking of the monitor-call order.
    144         \item Implement rollback semantics.
    145 \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 prohibitively complex \cit. In \CFA, users simply need to be carefull when acquiring multiple monitors at the same time or only use \gls{bulk-acq} of all the monitors.
    147 
    148 \Gls{multi-acq} and \gls{bulk-acq} can be used together in interesting ways, for example:
    149 \begin{cfacode}
    150 monitor bank { ... };
    151 
    152 void deposit( bank & mutex b, int deposit );
    153 
    154 void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) {
    155         deposit( mybank, -me2you );
    156         deposit( yourbank, me2you );
    157 }
    158 \end{cfacode}
    159 This example shows a trivial solution to the bank account transfer problem\cit. Without \gls{multi-acq} and \gls{bulk-acq}, the solution to this problem is much more involved and requires carefull engineering.
    160 
    161 \subsubsection{\code{mutex} statement} \label{mutex-stmt}
    162 
    163 The call semantics discussed aboved 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\cit. 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}
    166 \begin{center}
    167 \begin{tabular}{|c|c|}
    168 function call & \code{mutex} statement \\
     173% ======================================================================
     174% ======================================================================
     175\subsection{Implementation Details: Interaction with polymorphism}
     176% ======================================================================
     177% ======================================================================
     178Depending on the choice of semantics for when monitor locks are acquired, interaction between monitors and \CFA's concept of polymorphism can be complex to support. However, it is shown that entry-point locking solves most of the issues.
     179
     180First 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. Since a monitor's main purpose is to ensure mutual exclusion when accessing shared data, this implies that mutual exclusion is only required for routines that do in fact access shared data. However, since \code{dtype} polymorphism always handles incomplete types (by definition), no \code{dtype} polymorphic routine can access shared data since the data requires knowledge about the type. Therefore, the only concern when combining \code{dtype} polymorphism and monitors is to protect access to routines.
     181
     182Before looking into complex control-flow, it is important to present the difference between the two acquiring options : callsite 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:
     183\begin{center}
     184\setlength\tabcolsep{1.5pt}
     185\begin{tabular}{|c|c|c|}
     186Code & \gls{callsite-locking} & \gls{entry-point-locking} \\
     187\CFA & pseudo-code & pseudo-code \\
    169188\hline
    170189\begin{cfacode}[tabsize=3]
    171 monitor M {};
    172 void foo( M & mutex m ) {
    173         //critical section
    174 }
    175 
    176 void bar( M & m ) {
    177         foo( m );
    178 }
    179 \end{cfacode}&\begin{cfacode}[tabsize=3]
    180 monitor M {};
    181 void bar( M & m ) {
    182         mutex(m) {
    183                 //critical section
    184         }
    185 }
    186 
    187 
    188 \end{cfacode}
     190void foo(monitor& mutex a){
     191
     192
     193
     194        //Do Work
     195        //...
     196
     197}
     198
     199void main() {
     200        monitor a;
     201
     202
     203
     204        foo(a);
     205
     206}
     207\end{cfacode} & \begin{pseudo}[tabsize=3]
     208foo(& a) {
     209
     210
     211
     212        //Do Work
     213        //...
     214
     215}
     216
     217main() {
     218        monitor a;
     219        //calling routine
     220        //handles concurrency
     221        acquire(a);
     222        foo(a);
     223        release(a);
     224}
     225\end{pseudo} & \begin{pseudo}[tabsize=3]
     226foo(& a) {
     227        //called routine
     228        //handles concurrency
     229        acquire(a);
     230        //Do Work
     231        //...
     232        release(a);
     233}
     234
     235main() {
     236        monitor a;
     237
     238
     239
     240        foo(a);
     241
     242}
     243\end{pseudo}
    189244\end{tabular}
    190245\end{center}
    191 \caption{Regular call semantics vs. \code{mutex} statement}
    192 \label{lst:mutex-stmt}
    193 \end{figure}
    194 
    195 % ======================================================================
    196 % ======================================================================
    197 \subsection{Data semantics} \label{data}
    198 % ======================================================================
    199 % ======================================================================
    200 Once the call semantics are established, the next step is to establish data semantics. Indeed, until now a monitor is used simply as a generic handle but in most cases monitors contain shared data. This data should be intrinsic to the monitor declaration to prevent any accidental use of data without its appropriate protection. For example, here is a complete version of the counter showed in section \ref{call}:
    201 \begin{cfacode}
    202 monitor counter_t {
    203         int value;
    204 };
    205 
    206 void ?{}(counter_t & this) {
    207         this.cnt = 0;
    208 }
    209 
    210 int ?++(counter_t & mutex this) {
    211         return ++this.value;
    212 }
    213 
    214 //need for mutex is platform dependent here
    215 void ?{}(int * this, counter_t & mutex cnt) {
    216         *this = (int)cnt;
    217 }
     246
     247\Gls{callsite-locking} is inefficient, since any \code{dtype} routine may have to obtain some lock before calling a routine, depending on whether or not the type passed is a monitor. However, with \gls{entry-point-locking} calling a monitor routine becomes exactly the same as calling it from anywhere else.
     248
     249Note the \code{mutex} keyword relies on the resolver, which means that in cases where a generic monitor routine is actually desired, writing a mutex routine is possible with the proper trait. This is possible because monitors are designed in terms a trait. For example:
     250\begin{cfacode}
     251//Incorrect
     252//T is not a monitor
     253forall(dtype T)
     254void foo(T * mutex t);
     255
     256//Correct
     257//this function only works on monitors
     258//(any monitor)
     259forall(dtype T | is_monitor(T))
     260void bar(T * mutex t));
    218261\end{cfacode}
    219262
     
    224267% ======================================================================
    225268% ======================================================================
    226 In addition to mutual exclusion, the monitors at the core of \CFA's concurrency can also be used to achieve synchronisation. With monitors, this capability is generally achieved with internal or external scheduling as in\cit. Since internal scheduling within a single monitor is mostly a solved problem, this thesis concentrates on extending internal scheduling to multiple monitors. Indeed, like the \gls{bulk-acq} semantics, internal scheduling extends to multiple monitors in a way that is natural to the user but requires additional complexity on the implementation side.
     269In addition to mutual exclusion, the monitors at the core of \CFA's concurrency can also be used to achieve synchronisation. With monitors, this is generally achieved with internal or external scheduling as in\cit. Since internal scheduling of single monitors is mostly a solved problem, this proposal concentraits on extending internal scheduling to multiple monitors at once. Indeed, like the \gls{group-acquire} semantics, internal scheduling extends to multiple monitors at once in a way that is natural to the user but requires additional complexity on the implementation side.
    227270
    228271First, here is a simple example of such a technique:
    229272
    230273\begin{cfacode}
    231 monitor A {
    232         condition e;
    233 }
    234 
    235 void foo(A & mutex a) {
    236         ...
    237         //Wait for cooperation from bar()
    238         wait(a.e);
    239         ...
    240 }
    241 
    242 void bar(A & mutex a) {
    243         //Provide cooperation for foo()
    244         ...
    245         //Unblock foo
    246         signal(a.e);
    247 }
    248 \end{cfacode}
    249 
    250 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. Second, in \CFA, 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.
    251 
    252 An important aspect of the implementation is that \CFA does not allow barging, which means that once function \code{bar} releases the monitor, 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 arount 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.
     274        monitor A {
     275                condition e;
     276        }
     277
     278        void foo(A & mutex a) {
     279                ...
     280                // Wait for cooperation from bar()
     281                wait(a.e);
     282                ...
     283        }
     284
     285        void bar(A & mutex a) {
     286                // Provide cooperation for foo()
     287                ...
     288                // Unblock foo at scope exit
     289                signal(a.e);
     290        }
     291\end{cfacode}
     292
     293There are two details to note here. First, there \code{signal} is a delayed operation, it only unblocks the waiting thread when it reaches the end of the critical section. This is needed to respect mutual-exclusion. Second, in \CFA, \code{condition} have no particular need to be stored inside a monitor, beyond any software engineering reasons. Here routine \code{foo} waits for the \code{signal} from \code{bar} before making further progress, effectively ensuring a basic ordering.
     294
     295An important aspect to take into account here is that \CFA does not allow barging, which means that once function \code{bar} releases the monitor, 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 arount 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.
    253296
    254297% ======================================================================
     
    257300% ======================================================================
    258301% ======================================================================
    259 It is easier to understand the problem of multi-monitor scheduling using a series of pseudo-code. 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 a single condition as paremeter and waits on the monitors associated with the condition.
     302It is easier to understand the problem of multi-monitor scheduling using a series of pseudo-code. 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.
    260303
    261304\begin{multicols}{2}
     
    276319\end{pseudo}
    277320\end{multicols}
    278 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.
    279 
    280 A direct extension of the previous example is a \gls{bulk-acq} version:
     321The 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. There is an important thing to note here, both \code{wait} and \code{signal} must be called with the proper monitor(s) already acquired. This restriction is hidden on the user side in \uC, as it is a logical requirement for barging prevention.
     322
     323A direct extension of the previous example is the \gls{group-acquire} version:
    281324
    282325\begin{multicols}{2}
     
    295338\end{pseudo}
    296339\end{multicols}
    297 This version uses \gls{bulk-acq} (denoted using the \& symbol), but the presence of multiple monitors does not add a particularly new meaning. Synchronization happens between the two threads in exactly the same way and order. The only difference is that mutual exclusion covers more monitors. On the implementation side, handling multiple monitors does add a degree of complexity as the next few examples demonstrate.
    298 
    299 While deadlock issues can occur when nesting monitors, these issues are only a symptom of the fact that locks, and by extension monitors, are not perfectly composable. For monitors, a well known deadlock problem is the Nested Monitor Problem\cit, which occurs when a \code{wait} is made on a thread that holds more than one monitor. For example, the following pseudo-code will run into the nested monitor problem :
     340This version uses \gls{group-acquire} (denoted using the \& symbol), but the presence of multiple monitors does not add a particularly new meaning. Synchronization happens between the two threads in exactly the same way and order. The only difference is that mutual exclusion covers more monitors. On the implementation side, handling multiple monitors does add a degree of complexity as the next few examples demonstrate.
     341
     342While deadlock issues can occur when nesting monitors, these issues are only a symptom of the fact that locks, and by extension monitors, are not perfectly composable. However, for monitors as for locks, it is possible to write a program using nesting without encountering any problems if nested is done correctly. For example, the next pseudo-code snippet acquires monitors A then B before waiting while only acquiring B when signalling, effectively avoiding the nested monitor problem.
     343
    300344\begin{multicols}{2}
    301345\begin{pseudo}
     
    310354
    311355\begin{pseudo}
    312 acquire A
    313         acquire B
    314                 signal B
    315         release B
    316 release A
    317 \end{pseudo}
    318 \end{multicols}
    319 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.
    320 
    321 \begin{multicols}{2}
    322 \begin{pseudo}
    323 acquire A
    324         acquire B
    325                 wait B
    326         release B
    327 release A
    328 \end{pseudo}
    329 
    330 \columnbreak
    331 
    332 \begin{pseudo}
    333356
    334357acquire B
     
    339362\end{multicols}
    340363
    341 Listing \ref{lst:int-bulk-pseudo} shows an example where \gls{bulk-acq} adds a significant layer of complexity to the internal signalling semantics. Listing \ref{lst:int-bulk-cfa} shows the corresponding \CFA code which implements the pseudo-code in listing \ref{lst:int-bulk-pseudo}. Note that listing \ref{lst:int-bulk-cfa} uses non-\code{mutex} parameter to introduce monitor \code{b} into context. However, for the purpose of translating the given pseudo-code into \CFA-code any method of introducing new monitors into context, other than a \code{mutex} parameter, is acceptable, e.g. global variables, pointer parameters or using locals with the \code{mutex}-statement.
    342 
    343 \begin{figure}[!b]
     364The next example is where \gls{group-acquire} adds a significant layer of complexity to the internal signalling semantics.
     365
    344366\begin{multicols}{2}
    345367Waiting thread
    346368\begin{pseudo}[numbers=left]
    347369acquire A
    348         //Code Section 1
     370        // Code Section 1
    349371        acquire A & B
    350                 //Code Section 2
     372                // Code Section 2
    351373                wait A & B
    352                 //Code Section 3
     374                // Code Section 3
    353375        release A & B
    354         //Code Section 4
     376        // Code Section 4
    355377release A
    356378\end{pseudo}
     
    361383\begin{pseudo}[numbers=left, firstnumber=10]
    362384acquire A
    363         //Code Section 5
     385        // Code Section 5
    364386        acquire A & B
    365                 //Code Section 6
     387                // Code Section 6
    366388                signal A & B
    367                 //Code Section 7
     389                // Code Section 7
    368390        release A & B
    369         //Code Section 8
     391        // Code Section 8
    370392release A
    371393\end{pseudo}
    372394\end{multicols}
    373 \caption{Internal scheduling with \gls{bulk-acq}}
    374 \label{lst:int-bulk-pseudo}
    375 \end{figure}
    376 
    377 \begin{figure}[!b]
    378 \begin{multicols}{2}
    379 Waiting thread
    380 \begin{cfacode}
    381 monitor A;
    382 monitor B;
    383 extern condition c;
    384 void foo(A & mutex a, B & b) {
    385         //Code Section 1
    386         mutex(a, b) {
    387                 //Code Section 2
    388                 wait(c);
    389                 //Code Section 3
    390         }
    391         //Code Section 4
    392 }
    393 \end{cfacode}
    394 
    395 \columnbreak
    396 
    397 Signalling thread
    398 \begin{cfacode}
    399 monitor A;
    400 monitor B;
    401 extern condition c;
    402 void foo(A & mutex a, B & b) {
    403         //Code Section 5
    404         mutex(a, b) {
    405                 //Code Section 6
    406                 signal(c);
    407                 //Code Section 7
    408         }
    409         //Code Section 8
    410 }
    411 \end{cfacode}
    412 \end{multicols}
    413 \caption{Equivalent \CFA code for listing \ref{lst:int-bulk-pseudo}}
    414 \label{lst:int-bulk-cfa}
    415 \end{figure}
    416 
    417 It is particularly important to pay attention to 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 A \& B" (line 16), it must actually transfer ownership of monitor B to the waiting thread. This ownership trasnfer is required in order to prevent barging. Since the signalling thread still needs monitor A, simply waking up the waiting thread is not an option because it would violate mutual exclusion. There are three options.
     395\begin{center}
     396Listing 1
     397\end{center}
     398
     399It is particularly important to pay attention to code sections 8 and 4, which are where the existing semantics of internal scheduling need to be extended for multiple monitors. The root of the problem is that \gls{group-acquire} 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 A \& B" (line 16), it must actually transfer ownership of monitor B to the waiting thread. This ownership trasnfer is required in order to prevent barging. Since the signalling thread still needs the monitor A, simply waking up the waiting thread is not an option because it would violate mutual exclusion. There are three options:
    418400
    419401\subsubsection{Delaying signals}
    420 The first more 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 the correct time to transfer ownership 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 mutiple objects to a single group of objects, effectively making the existing single monitor semantic viable by simply changing monitors to monitor groups.
     402The first more 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 the correct time to transfer ownership 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 mutiple objects to a single group of object, effectively making the existing single monitor semantic viable by simply changing monitors to monitor collections.
    421403\begin{multicols}{2}
    422404Waiter
     
    442424\end{pseudo}
    443425\end{multicols}
    444 However, this solution can become much more complicated depending on what is executed while secretly holding B (at line 10). Indeed, nothing prevents signalling monitor A on a different condition variable:
     426However, this solution can become much more complicated depending on what is executed while secretly holding B (at line 10). Indeed, nothing prevents a user from signalling monitor A on a different condition variable:
     427\newpage
    445428\begin{multicols}{2}
    446429Thread 1
     
    463446
    464447Thread 3
    465 \begin{pseudo}[numbers=left, firstnumber=9]
     448\begin{pseudo}[numbers=left, firstnumber=10]
    466449acquire A
    467450        acquire A & B
     
    484467Note 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 15 before line 11 and get the reverse effect.
    485468
    486 In 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 homogenous group and therefore invalidates the main benefit of this approach.
     469In 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 homogenous group.
    487470
    488471\subsubsection{Dependency graphs}
    489 In the Listing 1 pseudo-code, there is a solution which statisfies both barging prevention and mutual exclusion. If ownership of both monitors is transferred to the waiter when the signaller releases A and then the waiter transfers back ownership of A when it releases it, then the problem is solved. Dynamically finding the correct order is therefore the second possible solution. The problem it encounters is that it effectively boils down to resolving a dependency graph of ownership requirements. Here even the simplest of code snippets requires two transfers and it seems to increase in a manner closer to polynomial. For example, the following code, which is just a direct extension to three monitors, requires at least three ownership transfer and has multiple solutions:
     472In the Listing 1 pseudo-code, there is a solution which statisfies both barging prevention and mutual exclusion. If ownership of both monitors is transferred to the waiter when the signaller releases A and then the waiter transfers back ownership of A when it releases it then the problem is solved. Dynamically finding the correct order is therefore the second possible solution. The problem it encounters is that it effectively boils down to resolving a dependency graph of ownership requirements. Here even the simplest of code snippets requires two transfers and it seems to increase in a manner closer to polynomial. For example, the following code, which is just a direct extension to three monitors, requires at least three ownership transfer and has multiple solutions:
    490473
    491474\begin{multicols}{2}
     
    512495\end{pseudo}
    513496\end{multicols}
    514 
    515 \begin{figure}
    516 \begin{multicols}{3}
    517 Thread $\alpha$
    518 \begin{pseudo}[numbers=left, firstnumber=1]
     497Resolving dependency graph being a complex and expensive endeavour, this solution is not the preffered one.
     498
     499\subsubsection{Partial signalling} \label{partial-sig}
     500Finally, the solution that is chosen for \CFA is to use partial signalling. Consider the following case:
     501
     502\begin{multicols}{2}
     503\begin{pseudo}[numbers=left]
    519504acquire A
    520505        acquire A & B
     
    526511\columnbreak
    527512
    528 Thread $\gamma$
    529 \begin{pseudo}[numbers=left, firstnumber=1]
     513\begin{pseudo}[numbers=left, firstnumber=6]
    530514acquire A
    531515        acquire A & B
    532516                signal A & B
    533517        release A & B
    534         signal A
    535 release A
    536 \end{pseudo}
    537 
    538 \columnbreak
    539 
    540 Thread $\beta$
    541 \begin{pseudo}[numbers=left, firstnumber=1]
    542 acquire A
    543         wait A
    544 release A
    545 \end{pseudo}
    546 
     518        // ... More code
     519release A
     520\end{pseudo}
    547521\end{multicols}
    548 \caption{Dependency graph}
    549 \label{lst:dependency}
    550 \end{figure}
    551 
    552 \begin{figure}
    553 \begin{center}
    554 \input{dependency}
    555 \end{center}
    556 \label{fig:dependency}
    557 \caption{Dependency graph of the statements in listing \ref{lst:dependency}}
    558 \end{figure}
    559 
    560 Listing \ref{lst:dependency} is the three thread example rewritten for dependency graphs as well as the corresponding dependency graph. Figure \ref{fig:dependency} shows the corresponding dependency graph that results, where every node is a statement of one of the three threads, and the arrows the dependency of that statement. The extra challenge is that this dependency graph is effectively post-mortem, but the run time system needs to be able to build and solve these graphs as the dependency unfolds. Resolving dependency graph being a complex and expensive endeavour, this solution is not the preffered one.
    561 
    562 \subsubsection{Partial signalling} \label{partial-sig}
    563 Finally, the solution that is chosen for \CFA is to use partial signalling. Consider the following case:
    564 
    565 \begin{multicols}{2}
    566 \begin{pseudo}[numbers=left]
    567 acquire A
    568         acquire A & B
    569                 wait A & B
    570         release A & B
    571 release A
    572 \end{pseudo}
    573 
    574 \columnbreak
    575 
    576 \begin{pseudo}[numbers=left, firstnumber=6]
    577 acquire A
    578         acquire A & B
    579                 signal A & B
    580         release A & B
    581         //... More code
    582 release A
    583 \end{pseudo}
    584 \end{multicols}
    585 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.
     522The 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 conditionnaly waking threads if all conditions are met. Contrary to the other solutions, this solution quickly hits an upper bound on complexity of implementation.
    586523
    587524% ======================================================================
     
    592529An 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}.
    593530
    594 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 cause the need for additional synchronisation when a two-way handshake is needed. To avoid this extraneous synchronisation, the \code{condition} type offers the \code{signal_block} routine which handle two-way handshakes as shown in the example. This 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 neither before nor after the call.
    595 \begin{figure}
     531For example here is an example highlighting the difference in behaviour:
     532\begin{center}
    596533\begin{tabular}{|c|c|}
    597534\code{signal} & \code{signal_block} \\
    598535\hline
    599 \begin{cfacode}[tabsize=3]
    600 monitor DatingService
    601 {
    602         //compatibility codes
    603         enum{ CCodes = 20 };
    604 
    605         int girlPhoneNo
    606         int boyPhoneNo;
    607 };
    608 
    609 condition girls[CCodes];
    610 condition boys [CCodes];
    611 condition exchange;
    612 
    613 int girl(int phoneNo, int ccode)
    614 {
    615         //no compatible boy ?
    616         if(empty(boys[ccode]))
    617         {
    618                 //wait for boy
    619                 wait(girls[ccode]);
    620 
    621                 //make phone number available
    622                 girlPhoneNo = phoneNo;
    623 
    624                 //wake boy fron chair
    625                 signal(exchange);
    626         }
    627         else
    628         {
    629                 //make phone number available
    630                 girlPhoneNo = phoneNo;
    631 
    632                 //wake boy
    633                 signal(boys[ccode]);
    634 
    635                 //sit in chair
    636                 wait(exchange);
    637         }
    638         return boyPhoneNo;
    639 }
    640 
    641 int boy(int phoneNo, int ccode)
    642 {
    643         //same as above
    644         //with boy/girl interchanged
    645 }
    646 \end{cfacode}&\begin{cfacode}[tabsize=3]
    647 monitor DatingService
    648 {
    649         //compatibility codes
    650         enum{ CCodes = 20 };
    651 
    652         int girlPhoneNo;
    653         int boyPhoneNo;
    654 };
    655 
    656 condition girls[CCodes];
    657 condition boys [CCodes];
    658 //exchange is not needed
    659 
    660 int girl(int phoneNo, int ccode)
    661 {
    662         //no compatible boy ?
    663         if(empty(boys[ccode]))
    664         {
    665                 //wait for boy
    666                 wait(girls[ccode]);
    667 
    668                 //make phone number available
    669                 girlPhoneNo = phoneNo;
    670 
    671                 //wake boy fron chair
    672                 signal(exchange);
    673         }
    674         else
    675         {
    676                 //make phone number available
    677                 girlPhoneNo = phoneNo;
    678 
    679                 //wake boy
    680                 signal_block(boys[ccode]);
    681 
    682                 //second handshake unnecessary
    683 
    684         }
    685         return boyPhoneNo;
    686 }
    687 
    688 int boy(int phoneNo, int ccode)
    689 {
    690         //same as above
    691         //with boy/girl interchanged
     536\begin{cfacode}
     537monitor M { int val; };
     538
     539void foo(M & mutex m ) {
     540        m.val++;
     541        sout| "Foo:" | m.val |endl;
     542
     543        wait( c );
     544
     545        m.val++;
     546        sout| "Foo:" | m.val |endl;
     547}
     548
     549void bar(M & mutex m ) {
     550        m.val++;
     551        sout| "Bar:" | m.val |endl;
     552
     553        signal( c );
     554
     555        m.val++;
     556        sout| "Bar:" | m.val |endl;
     557}
     558\end{cfacode}&\begin{cfacode}
     559monitor M { int val; };
     560
     561void foo(M & mutex m ) {
     562        m.val++;
     563        sout| "Foo:" | m.val |endl;
     564
     565        wait( c );
     566
     567        m.val++;
     568        sout| "Foo:" | m.val |endl;
     569}
     570
     571void bar(M & mutex m ) {
     572        m.val++;
     573        sout| "Bar:" | m.val |endl;
     574
     575        signal_block( c );
     576
     577        m.val++;
     578        sout| "Bar:" | m.val |endl;
    692579}
    693580\end{cfacode}
    694581\end{tabular}
    695 \caption{Dating service example using \code{signal} and \code{signal_block}. }
    696 \label{lst:datingservice}
    697 \end{figure}
     582\end{center}
     583Assuming that \code{val} is initialized at 0, that each routine are called from seperate thread and that \code{foo} is always called first. The previous code would yield the following output:
     584
     585\begin{center}
     586\begin{tabular}{|c|c|}
     587\code{signal} & \code{signal_block} \\
     588\hline
     589\begin{pseudo}
     590Foo: 0
     591Bar: 1
     592Bar: 2
     593Foo: 3
     594\end{pseudo}&\begin{pseudo}
     595Foo: 0
     596Bar: 1
     597Foo: 2
     598Bar: 3
     599\end{pseudo}
     600\end{tabular}
     601\end{center}
     602
     603As mentionned, \code{signal} only transfers ownership once the current critical section exits, resulting in the second "Bar" line to be printed before the second "Foo" line. On the other hand, \code{signal_block} immediately transfers ownership to \code{bar}, causing an inversion of output. Obviously this means that \code{signal_block} is a blocking call, which will only be resumed once the signalled function exits the critical section.
     604
     605% ======================================================================
     606% ======================================================================
     607\subsection{Internal scheduling: Implementation} \label{inschedimpl}
     608% ======================================================================
     609% ======================================================================
     610There are several challenges specific to \CFA when implementing internal scheduling. These challenges are direct results of \gls{group-acquire} and loose object definitions. These two constraints are to root cause of most design decisions in the implementation of internal scheduling. Furthermore, to avoid the head-aches of dynamically allocating memory in a concurrent environment, the internal-scheduling design is entirely free of mallocs and other dynamic memory allocation scheme. This is to avoid the chicken and egg problem 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.
     611
     612The main memory concern for concurrency is queues. All blocking operations are made by parking threads onto queues. These queues need to be intrinsic\cit to avoid the need memory allocation. This entails that all the fields needed to keep track of all needed information. Since internal scheduling can use an unbound amount of memory (depending on \gls{group-acquire}) statically defining information information in the intrusive fields of threads is insufficient. The only variable sized container that does not require memory allocation is the callstack, which is heavily used in the implementation of internal scheduling. Particularly the GCC extension variable length arrays which is used extensively.
     613
     614Since 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. In the case of external scheduling, 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 adding too much to the mutex routine stack size can become expansive faster).
     615
     616The following figure is the traditionnal illustration of a monitor :
     617
     618\begin{center}
     619{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
     620\end{center}
     621
     622For \CFA, the previous picture does not have support for blocking multiple monitors on a single condition. To support \gls{group-acquire} two changes to this picture are required. First, it doesn't make sense to tie the condition to a single monitor since blocking two monitors as one would require arbitrarily picking a monitor to hold the condition. Secondly, the object waiting on the conditions and AS-stack cannot simply contain the waiting thread since a single thread can potentially wait on multiple monitors. As mentionned in section \ref{inschedimpl}, the handling in multiple monitors is done by partially passing, which entails that each concerned monitor needs to have a node object. However, for waiting on the condition, since all threads need to wait together, a single object needs to be queued in the condition. Moving out the condition and updating the node types yields :
     623
     624\begin{center}
     625{\resizebox{0.8\textwidth}{!}{\input{int_monitor}}}
     626\end{center}
     627
     628\newpage
     629
     630This picture and the proper entry and leave algorithms is the fundamental implementation of internal scheduling.
     631
     632\begin{multicols}{2}
     633Entry
     634\begin{pseudo}[numbers=left]
     635if monitor is free
     636        enter
     637elif I already own the monitor
     638        continue
     639else
     640        block
     641increment recursion
     642
     643\end{pseudo}
     644\columnbreak
     645Exit
     646\begin{pseudo}[numbers=left, firstnumber=8]
     647decrement recursion
     648if recursion == 0
     649        if signal_stack not empty
     650                set_owner to thread
     651                if all monitors ready
     652                        wake-up thread
     653
     654        if entry queue not empty
     655                wake-up thread
     656\end{pseudo}
     657\end{multicols}
     658
     659Some important things to notice about the exit routine. The solution discussed in \ref{inschedimpl} can be seen on line 11 of the previous pseudo code. Basically, the solution boils down to having a seperate data structure for the condition queue and the AS-stack, and unconditionally transferring ownership of the monitors but only unblocking the thread when the last monitor has trasnferred ownership. This solution is safe as well as preventing any potential barging.
    698660
    699661% ======================================================================
     
    738700\end{tabular}
    739701\end{center}
    740 This method is more constrained and explicit, which helps users tone down the undeterministic nature of concurrency. Indeed, as the following examples demonstrates, external scheduling allows users to wait for events from other threads without the concern of unrelated events occuring. External scheduling can generally be done either in terms of control flow (e.g., \uC with \code{_Accept}) or in terms of data (e.g. Go with channels). Of course, both of these paradigms have their own strenghts and weaknesses but for this project control-flow semantics were chosen to stay consistent with the rest of the languages semantics. Two challenges specific to \CFA arise when trying to add external scheduling with loose object definitions and multi-monitor routines. The previous example shows a simple use \code{_Accept} versus \code{wait}/\code{signal} and its advantages. Note that while other languages often use \code{accept}/\code{select} as the core external scheduling keyword, \CFA uses \code{waitfor} to prevent name collisions with existing socket \acrshort{api}s.
    741 
    742 In the case of internal scheduling, the call to \code{wait} only guarantees that \code{V} is the last routine to access the monitor. This entails that a third routine, say \code{isInUse()}, may have acquired mutual exclusion several times while routine \code{P} was waiting. On the other hand, external scheduling guarantees that while routine \code{P} was waiting, no routine other than \code{V} could acquire the monitor.
     702This method is more constrained and explicit, which may help users tone down the undeterministic nature of concurrency. Indeed, as the following examples demonstrates, external scheduling allows users to wait for events from other threads without the concern of unrelated events occuring. External scheduling can generally be done either in terms of control flow (e.g., \uC) or in terms of data (e.g. Go). Of course, both of these paradigms have their own strenghts and weaknesses but for this project control-flow semantics were chosen to stay consistent with the rest of the languages semantics. Two challenges specific to \CFA arise when trying to add external scheduling with loose object definitions and multi-monitor routines. The previous example shows a simple use \code{_Accept} versus \code{wait}/\code{signal} and its advantages. Note that while other languages often use \code{accept} as the core external scheduling keyword, \CFA uses \code{waitfor} to prevent name collisions with existing socket APIs.
     703
     704In the case of internal scheduling, the call to \code{wait} only guarantees that \code{V} is the last routine to access the monitor. This entails that the routine \code{V} may have acquired mutual exclusion several times while routine \code{P} was waiting. On the other hand, external scheduling guarantees that while routine \code{P} was waiting, no routine other than \code{V} could acquire the monitor.
    743705
    744706% ======================================================================
     
    750712
    751713\begin{cfacode}
    752 monitor A {};
    753 
    754 void f(A & mutex a);
    755 void g(A & mutex a) {
    756         waitfor(f); //Obvious which f() to wait for
    757 }
    758 
    759 void f(A & mutex a, int); //New different F added in scope
    760 void h(A & mutex a) {
    761         waitfor(f); //Less obvious which f() to wait for
    762 }
     714        monitor A {};
     715
     716        void f(A & mutex a);
     717        void f(int a, float b);
     718        void g(A & mutex a) {
     719                waitfor(f); // Less obvious which f() to wait for
     720        }
    763721\end{cfacode}
    764722
     
    770728        if monitor is free
    771729                enter
    772         elif already own the monitor
     730        elif I already own the monitor
    773731                continue
    774732        elif monitor accepts me
     
    780738\end{center}
    781739
    782 For 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:
     740For the fist 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:
    783741
    784742\begin{center}
     
    786744\end{center}
    787745
    788 There are other alternatives to these pictures, but in the case of this picture, implementing a fast accept check is relatively easy. Indeed simply updating a bitmask when the acceptor queue changes is enough to have a check that executes in a single instruction, even with a fairly large number (e.g. 128) of mutex members. This technique cannot be used in \CFA because it relies on the fact that the monitor type declares all the acceptable routines. For OO languages this does not compromise much since monitors already have an exhaustive list of member routines. However, for \CFA this is not the case; routines can be added to a type anywhere after its declaration. Its important to note that the bitmask approach does not actually require an exhaustive list of routines, but it requires a dense unique ordering of routines with an upper-bound and that ordering must be consistent across translation units.
    789 The alternative is to have a picture like this one:
     746There are other alternatives to these pictures but in the case of this picture implementing a fast accept check is relatively easy. Indeed simply updating a bitmask when the acceptor queue changes is enough to have a check that executes in a single instruction, even with a fairly large number (e.g. 128) of mutex members. This technique cannot be used in \CFA because it relies on the fact that the monitor type declares all the acceptable routines. For OO languages this does not compromise much since monitors already have an exhaustive list of member routines. However, for \CFA this is not the case; routines can be added to a type anywhere after its declaration. Its important to note that the bitmask approach does not actually require an exhaustive list of routines, but it requires a dense unique ordering of routines with an upper-bound and that ordering must be consistent across translation units.
     747The alternative would be to have a picture more like this one:
    790748
    791749\begin{center}
     
    793751\end{center}
    794752
    795 Not storing the mask inside the monitor 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 function-pointers would solve the issue of uniquely identifying acceptable routines. However, the single instruction bitmask compare has been replaced by dereferencing a pointer followed by a linear search. Furthermore, supporting nested external scheduling may now require additionnal searches on calls to waitfor to check if a routine is already queued in.
    796 
    797 Note that in the second picture, tasks need to always keep track of through which routine they are attempting to acquire the monitor and the routine mask needs to have both a function pointer and a set of monitors, as will be discussed in the next section. These details where omitted from the picture for the sake of simplifying the representation.
    798 
    799 At this point we must make a decision between flexibility and performance. Many design decisions in \CFA achieve both flexibility and performance, for example polymorphic routines add significant flexibility but inlining them means the optimizer can easily remove any runtime cost. Here however, the cost of flexibility cannot be trivially removed. In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be prohibitively hard to write. This decision is based on the assumption that writing fast but inflexible locks is closer to a solved problems than writing locks that are as flexible as external scheduling in \CFA.
     753Not storing the queues inside the monitor means that the storage can vary between routines, allowing for more flexibility and extensions. Storing an array of function-pointers would solve the issue of uniquely identifying acceptable routines. However, the single instruction bitmask compare has been replaced by dereferencing a pointer followed by a linear search. Furthermore, supporting nested external scheduling may now require additionnal searches on calls to waitfor to check if a routine is already queued in.
     754
     755At this point we must make a decision between flexibility and performance. Many design decisions in \CFA achieve both flexibility and performance, for example polymorphic routines add significant flexibility but inlining them means the optimizer can easily remove any runtime cost. Here however, the cost of flexibility cannot be trivially removed. In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be prohibitively hard to write. This is based on the assumption that writing fast but inflexible locks is closer to a solved problems than writing locks that are as flexible as external scheduling in \CFA.
     756
     757Another aspect to consider is what happens if multiple overloads of the same routine are used. For the time being it is assumed that multiple overloads of the same routine are considered as distinct routines. However, this could easily be extended in the future.
    800758
    801759% ======================================================================
     
    805763% ======================================================================
    806764
    807 External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax. Even in the simplest possible case, some new semantics need to be established:
    808 \begin{cfacode}
    809 monitor M {};
    810 
    811 void f(M & mutex a);
    812 
    813 void g(M & mutex a, M & mutex b) {
    814         waitfor(f); //ambiguous, keep a pass b or other way around?
    815 }
     765External scheduling, like internal scheduling, becomes orders of magnitude more complex when we start introducing multi-monitor syntax. Even in the simplest possible case some new semantics need to be established:
     766\begin{cfacode}
     767        mutex struct A {};
     768
     769        mutex struct B {};
     770
     771        void g(A & mutex a, B & mutex b) {
     772                waitfor(f); //ambiguous, which monitor
     773        }
    816774\end{cfacode}
    817775
     
    819777
    820778\begin{cfacode}
    821 monitor M {};
    822 
    823 void f(M & mutex a);
    824 
    825 void g(M & mutex a, M & mutex b) {
    826         waitfor( f, b );
    827 }
    828 \end{cfacode}
    829 
    830 This syntax is unambiguous. Both locks are acquired and kept. When routine \code{f} is called, the lock for monitor \code{b} is temporarily transferred from \code{g} to \code{f} (while \code{g} still holds lock \code{a}). This behavior can be extended to multi-monitor waitfor statement as follows.
    831 
    832 \begin{cfacode}
    833 monitor M {};
    834 
    835 void f(M & mutex a, M & mutex b);
    836 
    837 void g(M & mutex a, M & mutex b) {
    838         waitfor( f, a, b);
    839 }
    840 \end{cfacode}
    841 
    842 Note that the set of monitors passed to the \code{waitfor} statement must be entirely contained in the set of monitors already acquired in the routine. \code{waitfor} used in any other context is Undefined Behaviour.
    843 
    844 An important behavior to note is that what happens when a set of monitors only match partially :
    845 
    846 \begin{cfacode}
    847 mutex struct A {};
    848 
    849 mutex struct B {};
    850 
    851 void g(A & mutex a, B & mutex b) {
    852         waitfor(f, a, b);
    853 }
    854 
    855 A a1, a2;
    856 B b;
    857 
    858 void foo() {
    859         g(a1, b); //block on accept
    860 }
    861 
    862 void bar() {
    863         f(a2, b); //fufill cooperation
    864 }
    865 \end{cfacode}
    866 
    867 While the equivalent can happen when using internal scheduling, the fact that conditions are specific to a set of monitors means that users have to use two different condition variables. In both cases, partially matching monitor sets does not wake-up the waiting thread. It is also important to note that in the case of external scheduling, as for routine calls, the order of parameters is important; \code{waitfor(f,a,b)} and \code{waitfor(f,b,a)} are to distinct waiting condition.
    868 
    869 % ======================================================================
    870 % ======================================================================
    871 \subsection{\code{waitfor} semantics}
    872 % ======================================================================
    873 % ======================================================================
    874 
    875 Syntactically, 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. This is because the compiler validates at compile time the validity of the waitfor statement. It checks that the set of monitor 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.
    876 \begin{figure}
    877 \begin{cfacode}
    878 monitor A{};
    879 monitor B{};
    880 
    881 void f1( A & mutex );
    882 void f2( A & mutex, B & mutex );
    883 void f3( A & mutex, int );
    884 void f4( A & mutex, int );
    885 void f4( A & mutex, double );
    886 
    887 void foo( A & mutex a1, A & mutex a2, B & mutex b1, B & b2 ) {
    888         A * ap = & a1;
    889         void (*fp)( A & mutex ) = f1;
    890 
    891         waitfor(f1, a1);     //Correct : 1 monitor case
    892         waitfor(f2, a1, b1); //Correct : 2 monitor case
    893         waitfor(f3, a1);     //Correct : non-mutex arguments are ignored
    894         waitfor(f1, *ap);    //Correct : expression as argument
    895 
    896         waitfor(f1, a1, b1); //Incorrect : Too many mutex arguments
    897         waitfor(f2, a1);     //Incorrect : Too few mutex arguments
    898         waitfor(f2, a1, a2); //Incorrect : Mutex arguments don't match
    899         waitfor(f1, 1);      //Incorrect : 1 not a mutex argument
    900         waitfor(f4, a1);     //Incorrect : f9 not a function
    901         waitfor(*fp, a1 );   //Incorrect : fp not a identifier
    902         waitfor(f4, a1);     //Incorrect : f4 ambiguous
    903 
    904         waitfor(f2, a1, b2); //Undefined Behaviour : b2 may not acquired
    905 }
    906 \end{cfacode}
    907 \caption{Various correct and incorrect uses of the waitfor statement}
    908 \label{lst:waitfor}
    909 \end{figure}
    910 
    911 Finally, for added flexibility, \CFA supports constructing complex waitfor mask using the \code{or}, \code{timeout} and \code{else}. Indeed, multiple \code{waitfor} can be chained together using \code{or}; this chain will form a single statement which will baton-pass to any one function that fits one of the function+monitor set which was passed in. To eanble users to tell which was the accepted function, \code{waitfor}s are followed by a statement (including the null statement \code{;}) or a compound statement. When multiple \code{waitfor} are chained together, only the statement corresponding to the accepted function is executed. A \code{waitfor} chain can also be followed by a \code{timeout}, to signify an upper bound on the wait, or an \code{else}, to signify that the call should be non-blocking, that is only check of a matching function already arrived and return immediately otherwise. Any and all of these clauses can be preceded by a \code{when} condition to dynamically construct the mask based on some current state. Listing \ref{lst:waitfor2}, demonstrates several complex masks and some incorrect ones.
    912 
    913 \begin{figure}
    914 \begin{cfacode}
    915 monitor A{};
    916 
    917 void f1( A & mutex );
    918 void f2( A & mutex );
    919 
    920 void foo( A & mutex a, bool b, int t ) {
    921         //Correct : blocking case
    922         waitfor(f1, a);
    923 
    924         //Correct : block with statement
    925         waitfor(f1, a) {
    926                 sout | "f1" | endl;
    927         }
    928 
    929         //Correct : block waiting for f1 or f2
    930         waitfor(f1, a) {
    931                 sout | "f1" | endl;
    932         } or waitfor(f2, a) {
    933                 sout | "f2" | endl;
    934         }
    935 
    936         //Correct : non-blocking case
    937         waitfor(f1, a); or else;
    938 
    939         //Correct : non-blocking case
    940         waitfor(f1, a) {
    941                 sout | "blocked" | endl;
    942         } or else {
    943                 sout | "didn't block" | endl;
    944         }
    945 
    946         //Correct : block at most 10 seconds
    947         waitfor(f1, a) {
    948                 sout | "blocked" | endl;
    949         } or timeout( 10`s) {
    950                 sout | "didn't block" | endl;
    951         }
    952 
    953         //Correct : block only if b == true
    954         //if b == false, don't even make the call
    955         when(b) waitfor(f1, a);
    956 
    957         //Correct : block only if b == true
    958         //if b == false, make non-blocking call
    959         waitfor(f1, a); or when(!b) else;
    960 
    961         //Correct : block only of t > 1
    962         waitfor(f1, a); or when(t > 1) timeout(t); or else;
    963 
    964         //Incorrect : timeout clause is dead code
    965         waitfor(f1, a); or timeout(t); or else;
    966 
    967         //Incorrect : order must be
    968         //waitfor [or waitfor... [or timeout] [or else]]
    969         timeout(t); or waitfor(f1, a); or else;
    970 }
    971 \end{cfacode}
    972 \caption{Various correct and incorrect uses of the or, else, and timeout clause around a waitfor statement}
    973 \label{lst:waitfor2}
    974 \end{figure}
     779        mutex struct A {};
     780
     781        mutex struct B {};
     782
     783        void g(A & mutex a, B & mutex b) {
     784                waitfor( f, b );
     785        }
     786\end{cfacode}
     787
     788This is unambiguous. Both locks will be acquired and kept, when routine \code{f} is called the lock for monitor \code{b} will be temporarily transferred from \code{g} to \code{f} (while \code{g} still holds lock \code{a}). This behavior can be extended to multi-monitor waitfor statment as follows.
     789
     790\begin{cfacode}
     791        mutex struct A {};
     792
     793        mutex struct B {};
     794
     795        void g(A & mutex a, B & mutex b) {
     796                waitfor( f, a, b);
     797        }
     798\end{cfacode}
     799
     800Note that the set of monitors passed to the \code{waitfor} statement must be entirely contained in the set of monitor already acquired in the routine. \code{waitfor} used in any other context is Undefined Behaviour.
     801
     802An important behavior to note is that what happens when set of monitors only match partially :
     803
     804\begin{cfacode}
     805        mutex struct A {};
     806
     807        mutex struct B {};
     808
     809        void g(A & mutex a, B & mutex b) {
     810                waitfor(f, a, b);
     811        }
     812
     813        A a1, a2;
     814        B b;
     815
     816        void foo() {
     817                g(a1, b);
     818        }
     819
     820        void bar() {
     821                f(a2, b);
     822        }
     823\end{cfacode}
     824
     825While the equivalent can happen when using internal scheduling, the fact that conditions are branded on first use means that users have to use two different condition variables. In both cases, partially matching monitor sets will not wake-up the waiting thread. It is also important to note that in the case of external scheduling, as for routine calls, the order of parameters is important; \code{waitfor(f,a,b)} and \code{waitfor(f,b,a)} are to distinct waiting condition.
     826
     827% ======================================================================
     828% ======================================================================
     829\subsection{Implementation Details: External scheduling queues}
     830% ======================================================================
     831% ======================================================================
     832To support multi-monitor external scheduling means that some kind of entry-queues must be used that is aware of both monitors. However, acceptable routines must be aware of the entry queues which means they must be stored inside at least one of the monitors that will be acquired. This in turn adds the requirement a systematic algorithm of disambiguating which queue is relavant regardless of user ordering. The proposed algorithm is to fall back on monitors lock ordering and specify that the monitor that is acquired first is the lock with the relevant entry queue. This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint. This algorithm choice has two consequences, the entry queue of the highest priority monitor is no longer a true FIFO queue and the queue of the lowest priority monitor is both required and probably unused. The queue can no longer be a FIFO queue because instead of simply containing the waiting threads in order arrival, they also contain the second mutex. Therefore, another thread with the same highest priority monitor but a different lowest priority monitor may arrive first but enter the critical section after a thread with the correct pairing. Secondly, since it may not be known at compile time which monitor will be the lowest priority monitor, every monitor needs to have the correct queues even though it is probable that half the multi-monitor queues will go unused for the entire duration of the program.
     833
     834% ======================================================================
     835% ======================================================================
     836\section{Other concurrency tools}
     837% ======================================================================
     838% ======================================================================
     839% \TODO
Note: See TracChangeset for help on using the changeset viewer.