Index: doc/proposals/concurrency/text/concurrency.tex
===================================================================
--- doc/proposals/concurrency/text/concurrency.tex	(revision dcfc4b35ffe8edfe715f99da2c8a4087ae6ee86b)
+++ doc/proposals/concurrency/text/concurrency.tex	(revision 3364962e92096cfc5d05c93607d92838baa1fe51)
@@ -4,20 +4,20 @@
 % ======================================================================
 % ======================================================================
-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 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.
+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.
 
 Approaches 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}.
 
-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 general purpose language, which is why it was rejected as the core paradigm for concurrency in \CFA.
-
-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.
+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.
+
+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.
 
 \section{Basics}
-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 numerous mechanisms to establish timing relationships among threads.
+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.
 
 \subsection{Mutual-Exclusion}
-As 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.
+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.
 
 \subsection{Synchronization}
-As 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.
+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.
 
 % ======================================================================
@@ -55,102 +55,4 @@
 	void ?{}(size_t * this, counter_t & mutex cnt); //conversion
 \end{cfacode}
-
-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 an \code{size_t} is an atomic operation.
-
-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 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.
-
-
-The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
-\begin{cfacode}
-int f1(monitor & mutex m);
-int f2(const monitor & mutex m);
-int f3(monitor ** mutex m);
-int f4(monitor * mutex m []);
-int f5(graph(monitor*) & mutex m);
-\end{cfacode}
-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 can be extended to absurd limits like \code{f5}, which uses a graph of monitors. To make the issue tractable, 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:
-
-\begin{cfacode}
-int f1(monitor & mutex m);   //Okay : recommanded case
-int f2(monitor * mutex m);   //Okay : could be an array but probably not
-int f3(monitor mutex m []);  //Not Okay : Array of unkown length
-int f4(monitor ** mutex m);  //Not Okay : Could be an array
-int f5(monitor * mutex m []); //Not Okay : Array of unkown length
-\end{cfacode}
-
-Unlike 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.
-\begin{cfacode}
-int f(MonitorA & mutex a, MonitorB & mutex b);
-
-MonitorA a;
-MonitorB b;
-f(a,b);
-\end{cfacode}
-The 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:
-\begin{cfacode}
-	void foo(A & mutex a, B & mutex b) { //acquire a & b
-		...
-	}
-
-	void bar(A & mutex a, B & /*nomutex*/ b) { //acquire a
-		... foo(a, b); ... //acquire b
-	}
-
-	void baz(A & /*nomutex*/ a, B & mutex b) { //acquire b
-		... foo(a, b); ... //acquire a
-	}
-\end{cfacode}
-The 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.
-
-However, 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:
-\begin{enumerate}
-	\item Dynamically tracking of the monitor-call order.
-	\item Implement rollback semantics.
-\end{enumerate}
-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.
-
-Finally, 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:
-\begin{cfacode}
-monitor bank {
-	int money;
-	log_t usr_log;
-};
-
-void deposit( bank & mutex b, int deposit ) {
-	b.money += deposit;
-	b.usr_log | "Adding" | deposit | endl;
-}
-
-void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) {
-	deposit( mybank, -me2you );
-	deposit( yourbank, me2you );
-}
-\end{cfacode}
-
-% ======================================================================
-% ======================================================================
-\subsection{Data semantics} \label{data}
-% ======================================================================
-% ======================================================================
-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}:
-\begin{cfacode}
-monitor counter_t {
-	int value;
-};
-
-void ?{}(counter_t & this) {
-	this.cnt = 0;
-}
-
-int ?++(counter_t & mutex this) {
-	return ++this.value;
-}
-
-//need for mutex is platform dependent here
-void ?{}(int * this, counter_t & mutex cnt) {
-	*this = (int)cnt;
-}
-\end{cfacode}
-
 This counter is used as follows:
 \begin{center}
@@ -171,92 +73,113 @@
 Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting.
 
-% ======================================================================
-% ======================================================================
-\subsection{Implementation Details: Interaction with polymorphism}
-% ======================================================================
-% ======================================================================
-Depending 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.
-
-First of all, interaction between \code{otype} polymorphism and monitors is impossible since monitors do not support copying. Therefore, the main question is how to support \code{dtype} polymorphism. 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.
-
-Before 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:
-\begin{center}
-\setlength\tabcolsep{1.5pt}
-\begin{tabular}{|c|c|c|}
-Code & \gls{callsite-locking} & \gls{entry-point-locking} \\
-\CFA & pseudo-code & pseudo-code \\
-\hline
-\begin{cfacode}[tabsize=3]
-void foo(monitor& mutex a){
-
-
-
-	//Do Work
-	//...
-
-}
-
-void main() {
-	monitor a;
-
-
-
-	foo(a);
-
-}
-\end{cfacode} & \begin{pseudo}[tabsize=3]
-foo(& a) {
-
-
-
-	//Do Work
-	//...
-
-}
-
-main() {
-	monitor a;
-	//calling routine
-	//handles concurrency
-	acquire(a);
-	foo(a);
-	release(a);
-}
-\end{pseudo} & \begin{pseudo}[tabsize=3]
-foo(& a) {
-	//called routine
-	//handles concurrency
-	acquire(a);
-	//Do Work
-	//...
-	release(a);
-}
-
-main() {
-	monitor a;
-
-
-
-	foo(a);
-
-}
-\end{pseudo}
-\end{tabular}
-\end{center}
-
-\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.
-
-Note 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:
-\begin{cfacode}
-//Incorrect
-//T is not a monitor
-forall(dtype T)
-void foo(T * mutex t);
-
-//Correct
-//this function only works on monitors
-//(any monitor)
-forall(dtype T | is_monitor(T))
-void bar(T * mutex t));
+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.
+
+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.
+\begin{figure}
+\label{fig:search}
+\begin{cfacode}
+monitor printer { ... };
+struct tree {
+	tree * left, right;
+	char * value;
+};
+void print(printer & mutex p, char * v);
+
+void print(printer & mutex p, tree * t) {
+	print(p, t->value);
+	print(p, t->left );
+	print(p, t->right);
+}
+\end{cfacode}
+\caption{Recursive printing algorithm using \gls{multi-acq}.}
+\end{figure}
+
+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}.
+
+The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
+\begin{cfacode}
+int f1(monitor & mutex m);
+int f2(const monitor & mutex m);
+int f3(monitor ** mutex m);
+int f4(monitor * mutex m []);
+int f5(graph(monitor*) & mutex m);
+\end{cfacode}
+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:
+\begin{cfacode}
+int f1(monitor & mutex m);   //Okay : recommanded case
+int f2(monitor * mutex m);   //Okay : could be an array but probably not
+int f3(monitor mutex m []);  //Not Okay : Array of unkown length
+int f4(monitor ** mutex m);  //Not Okay : Could be an array
+int f5(monitor * mutex m []); //Not Okay : Array of unkown length
+\end{cfacode}
+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.
+
+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.
+\begin{cfacode}
+int f(MonitorA & mutex a, MonitorB & mutex b);
+
+MonitorA a;
+MonitorB b;
+f(a,b);
+\end{cfacode}
+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:
+\begin{cfacode}
+	void foo(A & mutex a, B & mutex b) { //acquire a & b
+		...
+	}
+
+	void bar(A & mutex a, B & /*nomutex*/ b) { //acquire a
+		... foo(a, b); ... //acquire b
+	}
+
+	void baz(A & /*nomutex*/ a, B & mutex b) { //acquire b
+		... foo(a, b); ... //acquire a
+	}
+\end{cfacode}
+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.
+
+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:
+\begin{enumerate}
+	\item Dynamically tracking of the monitor-call order.
+	\item Implement rollback semantics.
+\end{enumerate}
+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.
+
+\Gls{multi-acq} and \gls{bulk-acq} can be used together in interesting ways, for example:
+\begin{cfacode}
+monitor bank { ... };
+
+void deposit( bank & mutex b, int deposit );
+
+void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) {
+	deposit( mybank, -me2you );
+	deposit( yourbank, me2you );
+}
+\end{cfacode}
+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.
+
+% ======================================================================
+% ======================================================================
+\subsection{Data semantics} \label{data}
+% ======================================================================
+% ======================================================================
+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}:
+\begin{cfacode}
+monitor counter_t {
+	int value;
+};
+
+void ?{}(counter_t & this) {
+	this.cnt = 0;
+}
+
+int ?++(counter_t & mutex this) {
+	return ++this.value;
+}
+
+//need for mutex is platform dependent here
+void ?{}(int * this, counter_t & mutex cnt) {
+	*this = (int)cnt;
+}
 \end{cfacode}
 
@@ -267,5 +190,5 @@
 % ======================================================================
 % ======================================================================
-In 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.
+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.
 
 First, here is a simple example of such a technique:
@@ -278,5 +201,5 @@
 	void foo(A & mutex a) {
 		...
-		// Wait for cooperation from bar()
+		//Wait for cooperation from bar()
 		wait(a.e);
 		...
@@ -284,14 +207,14 @@
 
 	void bar(A & mutex a) {
-		// Provide cooperation for foo()
+		//Provide cooperation for foo()
 		...
-		// Unblock foo at scope exit
+		//Unblock foo
 		signal(a.e);
 	}
 \end{cfacode}
 
-There 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.
-
-An 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.
+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.
+
+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.
 
 % ======================================================================
@@ -319,7 +242,7 @@
 \end{pseudo}
 \end{multicols}
-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. 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.
-
-A direct extension of the previous example is the \gls{group-acquire} version:
+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.
+
+A direct extension of the previous example is a \gls{bulk-acq} version:
 
 \begin{multicols}{2}
@@ -338,8 +261,7 @@
 \end{pseudo}
 \end{multicols}
-This 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.
-
-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. 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.
-
+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.
+
+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 :
 \begin{multicols}{2}
 \begin{pseudo}
@@ -354,4 +276,25 @@
 
 \begin{pseudo}
+acquire A
+	acquire B
+		signal B
+	release B
+release A
+\end{pseudo}
+\end{multicols}
+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.
+
+\begin{multicols}{2}
+\begin{pseudo}
+acquire A
+	acquire B
+		wait B
+	release B
+release A
+\end{pseudo}
+
+\columnbreak
+
+\begin{pseudo}
 
 acquire B
@@ -362,5 +305,5 @@
 \end{multicols}
 
-The next example is where \gls{group-acquire} adds a significant layer of complexity to the internal signalling semantics.
+The next example is where \gls{bulk-acq} adds a significant layer of complexity to the internal signalling semantics.
 
 \begin{multicols}{2}
@@ -368,11 +311,11 @@
 \begin{pseudo}[numbers=left]
 acquire A
-	// Code Section 1
-	acquire A & B
-		// Code Section 2
+	//Code Section 1
+	acquire A & B
+		//Code Section 2
 		wait A & B
-		// Code Section 3
-	release A & B
-	// Code Section 4
+		//Code Section 3
+	release A & B
+	//Code Section 4
 release A
 \end{pseudo}
@@ -383,11 +326,11 @@
 \begin{pseudo}[numbers=left, firstnumber=10]
 acquire A
-	// Code Section 5
-	acquire A & B
-		// Code Section 6
+	//Code Section 5
+	acquire A & B
+		//Code Section 6
 		signal A & B
-		// Code Section 7
-	release A & B
-	// Code Section 8
+		//Code Section 7
+	release A & B
+	//Code Section 8
 release A
 \end{pseudo}
@@ -397,8 +340,8 @@
 \end{center}
 
-It 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:
+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.
 
 \subsubsection{Delaying signals}
-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 object, effectively making the existing single monitor semantic viable by simply changing monitors to monitor collections.
+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.
 \begin{multicols}{2}
 Waiter
@@ -424,6 +367,5 @@
 \end{pseudo}
 \end{multicols}
-However, 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:
-\newpage
+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:
 \begin{multicols}{2}
 Thread 1
@@ -467,8 +409,8 @@
 Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order. However, regardless of the answer, users can move line 15 before line 11 and get the reverse effect.
 
-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.
+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.
 
 \subsubsection{Dependency graphs}
-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:
+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:
 
 \begin{multicols}{2}
@@ -495,5 +437,51 @@
 \end{pseudo}
 \end{multicols}
-Resolving dependency graph being a complex and expensive endeavour, this solution is not the preffered one.
+
+\begin{figure}
+\begin{multicols}{3}
+Thread $\alpha$
+\begin{pseudo}[numbers=left, firstnumber=1]
+acquire A
+	acquire A & B
+		wait A & B
+	release A & B
+release A
+\end{pseudo}
+
+\columnbreak
+
+Thread $\gamma$
+\begin{pseudo}[numbers=left, firstnumber=1]
+acquire A
+	acquire A & B
+		signal A & B
+	release A & B
+	signal A
+release A
+\end{pseudo}
+
+\columnbreak
+
+Thread $\beta$
+\begin{pseudo}[numbers=left, firstnumber=1]
+acquire A
+	wait A
+release A
+\end{pseudo}
+
+\end{multicols}
+\caption{Dependency graph}
+\label{lst:dependency}
+\end{figure}
+
+\begin{figure}
+\begin{center}
+\input{dependency}
+\end{center}
+\label{fig:dependency}
+\caption{Dependency graph of the statments in listing \ref{lst:dependency}}
+\end{figure}
+
+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 statment of one of the three threads, and the arrows the dependency of that statment. 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.
 
 \subsubsection{Partial signalling} \label{partial-sig}
@@ -516,9 +504,9 @@
 		signal A & B
 	release A & B
-	// ... More code
-release A
-\end{pseudo}
-\end{multicols}
-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 conditionnaly waking threads if all conditions are met. Contrary to the other solutions, this solution quickly hits an upper bound on complexity of implementation.
+	//... More code
+release A
+\end{pseudo}
+\end{multicols}
+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.
 
 % ======================================================================
@@ -529,133 +517,108 @@
 An important note is that, until now, signalling a monitor was a delayed operation. The ownership of the monitor is transferred only when the monitor would have otherwise been released, not at the point of the \code{signal} statement. However, in some cases, it may be more convenient for users to immediately transfer ownership to the thread that is waiting for cooperation, which is achieved using the \code{signal_block} routine\footnote{name to be discussed}.
 
-For example here is an example highlighting the difference in behaviour:
-\begin{center}
+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.
+\begin{figure}
 \begin{tabular}{|c|c|}
 \code{signal} & \code{signal_block} \\
 \hline
-\begin{cfacode}
-monitor M { int val; };
-
-void foo(M & mutex m ) {
-	m.val++;
-	sout| "Foo:" | m.val |endl;
-
-	wait( c );
-
-	m.val++;
-	sout| "Foo:" | m.val |endl;
-}
-
-void bar(M & mutex m ) {
-	m.val++;
-	sout| "Bar:" | m.val |endl;
-
-	signal( c );
-
-	m.val++;
-	sout| "Bar:" | m.val |endl;
-}
-\end{cfacode}&\begin{cfacode}
-monitor M { int val; };
-
-void foo(M & mutex m ) {
-	m.val++;
-	sout| "Foo:" | m.val |endl;
-
-	wait( c );
-
-	m.val++;
-	sout| "Foo:" | m.val |endl;
-}
-
-void bar(M & mutex m ) {
-	m.val++;
-	sout| "Bar:" | m.val |endl;
-
-	signal_block( c );
-
-	m.val++;
-	sout| "Bar:" | m.val |endl;
+\begin{cfacode}[tabsize=3]
+monitor DatingService
+{
+	//compatibility codes
+	enum{ CCodes = 20 };
+
+	int girlPhoneNo
+	int boyPhoneNo;
+};
+
+condition girls[CCodes];
+condition boys [CCodes];
+condition exchange;
+
+int girl(int phoneNo, int ccode)
+{
+	//no compatible boy ?
+	if(empty(boys[ccode]))
+	{
+		//wait for boy
+		wait(girls[ccode]);
+
+		//make phone number available
+		girlPhoneNo = phoneNo;
+
+		//wake boy fron chair
+		signal(exchange);
+	}
+	else
+	{
+		//make phone number available
+		girlPhoneNo = phoneNo;
+
+		//wake boy
+		signal(boys[ccode]);
+
+		//sit in chair
+		wait(exchange);
+	}
+	return boyPhoneNo;
+}
+
+int boy(int phoneNo, int ccode)
+{
+	//same as above
+	//with boy/girl interchanged
+}
+\end{cfacode}&\begin{cfacode}[tabsize=3]
+monitor DatingService
+{
+	//compatibility codes
+	enum{ CCodes = 20 };
+
+	int girlPhoneNo;
+	int boyPhoneNo;
+};
+
+condition girls[CCodes];
+condition boys [CCodes];
+//exchange is not needed
+
+int girl(int phoneNo, int ccode)
+{
+	//no compatible boy ?
+	if(empty(boys[ccode]))
+	{
+		//wait for boy
+		wait(girls[ccode]);
+
+		//make phone number available
+		girlPhoneNo = phoneNo;
+
+		//wake boy fron chair
+		signal(exchange);
+	}
+	else
+	{
+		//make phone number available
+		girlPhoneNo = phoneNo;
+
+		//wake boy
+		signal_block(boys[ccode]);
+
+		//second handshake unnecessary
+
+	}
+	return boyPhoneNo;
+}
+
+int boy(int phoneNo, int ccode)
+{
+	//same as above
+	//with boy/girl interchanged
 }
 \end{cfacode}
 \end{tabular}
-\end{center}
-Assuming 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:
-
-\begin{center}
-\begin{tabular}{|c|c|}
-\code{signal} & \code{signal_block} \\
-\hline
-\begin{pseudo}
-Foo: 0
-Bar: 1
-Bar: 2
-Foo: 3
-\end{pseudo}&\begin{pseudo}
-Foo: 0
-Bar: 1
-Foo: 2
-Bar: 3
-\end{pseudo}
-\end{tabular}
-\end{center}
-
-As 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.
-
-% ======================================================================
-% ======================================================================
-\subsection{Internal scheduling: Implementation} \label{inschedimpl}
-% ======================================================================
-% ======================================================================
-There 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 \cite{Chicken} of having a memory allocator that relies on the threading system and a threading system that relies on the runtime. This extra goal, means that memory management is a constant concern in the design of the system.
-
-The 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.
-
-Since stack allocation is based around scope, the first step of the implementation is to identify the scopes that are available to store the information, and which of these can have a variable length. 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).
-
-The following figure is the traditionnal illustration of a monitor :
-
-\begin{center}
-{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
-\end{center}
-
-For \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 :
-
-\begin{center}
-{\resizebox{0.8\textwidth}{!}{\input{int_monitor}}}
-\end{center}
-
-\newpage
-
-This picture and the proper entry and leave algorithms is the fundamental implementation of internal scheduling.
-
-\begin{multicols}{2}
-Entry
-\begin{pseudo}[numbers=left]
-if monitor is free
-	enter
-elif I already own the monitor
-	continue
-else
-	block
-increment recursion
-
-\end{pseudo}
-\columnbreak
-Exit
-\begin{pseudo}[numbers=left, firstnumber=8]
-decrement recursion
-if recursion == 0
-	if signal_stack not empty
-		set_owner to thread
-		if all monitors ready
-			wake-up thread
-
-	if entry queue not empty
-		wake-up thread
-\end{pseudo}
-\end{multicols}
-
-Some 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.
+\caption{Dating service example using \code{signal} and \code{signal_block}. }
+\label{lst:datingservice}
+\end{figure}
 
 % ======================================================================
@@ -700,7 +663,7 @@
 \end{tabular}
 \end{center}
-This 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 \acrshort{api}s.
-
-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 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.
+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.
+
+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.
 
 % ======================================================================
@@ -715,7 +678,11 @@
 
 	void f(A & mutex a);
-	void f(int a, float b);
 	void g(A & mutex a) {
-		waitfor(f); // Less obvious which f() to wait for
+		waitfor(f); //Obvious which f() to wait for
+	}
+
+	void f(A & mutex a, int); // New different F added in scope
+	void h(A & mutex a) {
+		waitfor(f); //Less obvious which f() to wait for
 	}
 \end{cfacode}
@@ -728,5 +695,5 @@
 	if monitor is free
 		enter
-	elif I already own the monitor
+	elif already own the monitor
 		continue
 	elif monitor accepts me
@@ -738,5 +705,5 @@
 \end{center}
 
-For 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:
+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:
 
 \begin{center}
@@ -744,6 +711,6 @@
 \end{center}
 
-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.
-The alternative would be to have a picture more like this one:
+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.
+The alternative is to have a picture like this one:
 
 \begin{center}
@@ -751,9 +718,9 @@
 \end{center}
 
-Not 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.
-
-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 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.
-
-Another 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.
+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.
+
+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.
+
+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.
 
 % ======================================================================
@@ -763,12 +730,12 @@
 % ======================================================================
 
-External 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:
-\begin{cfacode}
-	mutex struct A {};
-
-	mutex struct B {};
-
-	void g(A & mutex a, B & mutex b) {
-		waitfor(f); //ambiguous, which monitor
+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:
+\begin{cfacode}
+	monitor M {};
+
+	void f(M & mutex a);
+
+	void g(M & mutex a, M & mutex b) {
+		waitfor(f); //ambiguous, keep a pass b or other way around?
 	}
 \end{cfacode}
@@ -777,28 +744,28 @@
 
 \begin{cfacode}
-	mutex struct A {};
-
-	mutex struct B {};
-
-	void g(A & mutex a, B & mutex b) {
+	monitor M {};
+
+	void f(M & mutex a);
+
+	void g(M & mutex a, M & mutex b) {
 		waitfor( f, b );
 	}
 \end{cfacode}
 
-This 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.
-
-\begin{cfacode}
-	mutex struct A {};
-
-	mutex struct B {};
-
-	void g(A & mutex a, B & mutex b) {
+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 statment as follows.
+
+\begin{cfacode}
+	monitor M {};
+
+	void f(M & mutex a, M & mutex b);
+
+	void g(M & mutex a, M & mutex b) {
 		waitfor( f, a, b);
 	}
 \end{cfacode}
 
-Note 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.
-
-An important behavior to note is that what happens when set of monitors only match partially :
+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.
+
+An important behavior to note is that what happens when a set of monitors only match partially :
 
 \begin{cfacode}
@@ -815,22 +782,17 @@
 
 	void foo() {
-		g(a1, b);
+		g(a1, b); //block on accept
 	}
 
 	void bar() {
-		f(a2, b);
-	}
-\end{cfacode}
-
-While 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.
-
-% ======================================================================
-% ======================================================================
-\subsection{Implementation Details: External scheduling queues}
-% ======================================================================
-% ======================================================================
-To 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.
-
-
-\subsection{Internals}
-The complete mask can be pushed to any one, we are in a context where we already have full ownership of (at least) every concerned monitor and therefore monitors will refuse all calls no matter what.
+		f(a2, b); //fufill cooperation
+	}
+\end{cfacode}
+
+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.
+
+% ======================================================================
+% ======================================================================
+\subsection{Waitfor semantics}
+% ======================================================================
+% ======================================================================
