# Changeset 6fa9e71

Ignore:
Timestamp:
Nov 8, 2017, 10:58:43 AM (5 years ago)
Branches:
aaron-thesis, arm-eh, cleanup-dtors, deferred_resn, demangler, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, pthread-emulation, qualifiedEnum, resolv-new, with_gc
Children:
8e0147a
Parents:
d06c808 (diff), b9d0fb6 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of plg.uwaterloo.ca:/u/cforall/software/cfa/cfa-cc

Files:
1 deleted
32 edited

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

 rd06c808 build/*.out build/*.ps build/*.pstex build/*.pstex_t build/*.tex build/*.toc
• ## doc/proposals/concurrency/Makefile

 rd06c808 annex/glossary \ text/intro \ text/basics \ text/cforall \ text/basics \ text/concurrency \ text/internals \ text/parallelism \ text/results \ text/together \ text/future \ }} PICTURES = ${addsuffix .pstex, \ } PICTURES =${addprefix build/, ${addsuffix .pstex, \ system \ }} PROGRAMS =${addsuffix .tex, \ build/*.out     \ build/*.ps      \ build/*.pstex   \ build/*.pstex_t \ build/*.tex     \
• ## doc/proposals/concurrency/style/cfa-format.tex


• ## doc/proposals/concurrency/text/cforall.tex

 rd06c808 % ====================================================================== % ====================================================================== \chapter{Cforall crash course} \chapter{Cforall Overview} % ====================================================================== % ====================================================================== This thesis presents the design for a set of concurrency features in \CFA. Since it is a new dialect of C, the following is a quick introduction to the language, specifically tailored to the features needed to support concurrency. The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency. \CFA is a extension of ISO-C and therefore supports all of the same paradigms as C. It is a non-object oriented system language, meaning most of the major abstractions have either no runtime overhead or can be opt-out easily. Like C, the basics of \CFA revolve around structures and routines, which are thin abstractions over machine code. The vast majority of the code produced by the \CFA translator respects memory-layouts and calling-conventions laid out by C. Interestingly, while \CFA is not an object-oriented language, lacking the concept of a received (e.g.: this), it does have some notion of objects\footnote{C defines the term objects as : [Where to I get the C11 reference manual?]}, most importantly construction and destruction of objects. Most of the following pieces of code can be found on the \CFA website \cite{www-cfa} \CFA is a extension of ISO-C and therefore supports all of the same paradigms as C. It is a non-object oriented system language, meaning most of the major abstractions have either no runtime overhead or can be opt-out easily. Like C, the basics of \CFA revolve around structures and routines, which are thin abstractions over machine code. The vast majority of the code produced by the \CFA translator respects memory-layouts and calling-conventions laid out by C. Interestingly, while \CFA is not an object-oriented language, lacking the concept of a receiver (e.g., this), it does have some notion of objects\footnote{C defines the term objects as : region of data storage in the execution environment, the contents of which can represent values''\cite[3.15]{C11}}, most importantly construction and destruction of objects. Most of the following code examples can be found on the \CFA website \cite{www-cfa} \section{References} Like \CC, \CFA introduces references as an alternative to pointers. In regards to concurrency, the semantics difference between pointers and references are not particularly relevant but since this document uses mostly references here is a quick overview of the semantics : Like \CC, \CFA introduces rebindable references providing multiple dereferecing as an alternative to pointers. In regards to concurrency, the semantic difference between pointers and references are not particularly relevant, but since this document uses mostly references, here is a quick overview of the semantics: \begin{cfacode} int x, *p1 = &x, **p2 = &p1, ***p3 = &p2, &r1 = x,    &&r2 = r1,   &&&r3 = r2; &r1 = x,    &&r2 = r1,   &&&r3 = r2; ***p3 = 3;                                                      //change x r3    = 3;                                                      //change x, ***r3 sizeof(&ar[1]) == sizeof(int *);        //is true, i.e., the size of a reference \end{cfacode} The important thing to take away from this code snippet is that references offer a handle to an object much like pointers but which is automatically derefferenced when convinient. The important take away from this code example is that references offer a handle to an object, much like pointers, but which is automatically dereferenced for convinience. \section{Overloading} Another important feature of \CFA is function overloading as in Java and \CC, where routine with the same name are selected based on the numbers and type of the arguments. As well, \CFA uses the return type as part of the selection criteria, as in Ada\cite{Ada}. For routines with multiple parameters and returns, the selection is complex. Another important feature of \CFA is function overloading as in Java and \CC, where routines with the same name are selected based on the number and type of the arguments. As well, \CFA uses the return type as part of the selection criteria, as in Ada\cite{Ada}. For routines with multiple parameters and returns, the selection is complex. \begin{cfacode} //selection based on type and number of parameters double d = f(4);                //select (2) \end{cfacode} This feature is particularly important for concurrency since the runtime system relies on creating different types to represent concurrency objects. Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions that prevent name clashes. As seen in chapter \ref{basics}, routines main is an example that benefits from overloading. This feature is particularly important for concurrency since the runtime system relies on creating different types to represent concurrency objects. Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions that prevent name clashes. As seen in chapter \ref{basics}, routine \code{main} is an example that benefits from overloading. \section{Operators} Overloading also extends to operators. The syntax for denoting operator-overloading is to name a routine with the symbol of the operator and question marks where the arguments of the operation would be, like so : Overloading also extends to operators. The syntax for denoting operator-overloading is to name a routine with the symbol of the operator and question marks where the arguments of the operation occur, e.g.: \begin{cfacode} int ++? (int op);                       //unary prefix increment \section{Parametric Polymorphism} Routines in \CFA can also be reused for multiple types. This is done using the \code{forall} clause which gives \CFA it's name. \code{forall} clauses allow seperatly compiled routines to support generic usage over multiple types. For example, the following sum function will work for any type which support construction from 0 and addition : Routines in \CFA can also be reused for multiple types. This capability is done using the \code{forall} clause which gives \CFA its name. \code{forall} clauses allow separately compiled routines to support generic usage over multiple types. For example, the following sum function works for any type that supports construction from 0 and addition : \begin{cfacode} //constraint type, 0 and + \end{cfacode} Since writing constraints on types can become cumbersome for more constrained functions, \CFA also has the concept of traits. Traits are named collection of constraints which can be used both instead and in addition to regular constraints: Since writing constraints on types can become cumbersome for more constrained functions, \CFA also has the concept of traits. Traits are named collection of constraints that can be used both instead and in addition to regular constraints: \begin{cfacode} trait sumable( otype T ) { \section{with Clause/Statement} Since \CFA lacks the concept of a receiver, certain functions end-up needing to repeat variable names often, to solve this \CFA offers the \code{with} statement which opens an aggregate scope making its fields directly accessible (like Pascal). Since \CFA lacks the concept of a receiver, certain functions end-up needing to repeat variable names often. To remove this inconvenience, \CFA provides the \code{with} statement, which opens an aggregate scope making its fields directly accessible (like Pascal). \begin{cfacode} struct S { int i, j; }; int mem(S & this) with this             //with clause int mem(S & this) with (this)           //with clause i = 1;                                          //this->i j = 2;                                          //this->j struct S1 { ... } s1; struct S2 { ... } s2; with s1                                         //with statement with (s1)                                       //with statement { //access fields of s1 //without qualification with s2                                 //nesting with (s2)                                       //nesting { //access fields of s1 and s2 } } with s1, s2                             //scopes open in parallel with (s1, s2)                           //scopes open in parallel { //access fields of s1 and s2
• ## doc/proposals/concurrency/text/concurrency.tex

 rd06c808 % ====================================================================== % ====================================================================== 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. 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\cite{CSP,Go} 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 systems language, which is why it was rejected as the core paradigm for concurrency in \CFA. An approach that is worth mentioning 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. \subsection{Synchronization} 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. 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 simpler solution to otherwise involved challenges. As mentioned above, synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}. Most of the time, synchronisation happens within a critical section, where threads must acquire mutual-exclusion 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}. The classic exmaple is the thread that finishes using a ressource and unblocks a thread waiting to use the resource, but the unblocked thread must compete again to acquire the resource. 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. % ====================================================================== \end{tabular} \end{center} Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting. 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. Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting, which is similar in usage to \CC \code{atomic} template. Here, the constructor(\code{?\{\}}) uses the \code{nomutex} keyword to signify that it does not acquire the monitor mutual-exclusion when constructing. This semantics is because an object not yet con\-structed should never be shared and therefore does not require mutual exclusion. 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 the same monitor multiple times without deadlock. For example, figure \ref{fig:search} uses recursion and \gls{multi-acq} to print values inside a binary tree. \begin{figure} \label{fig:search} \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}. Having both \code{mutex} and \code{nomutex} keywords is redundant based on the meaning of a routine having neither of these keywords. For example, given a routine without qualifiers \code{void foo(counter_t & this)}, then it is reasonable that it should default to the safest option \code{mutex}, whereas assuming \code{nomutex} is unsafe and may cause subtle errors. In fact, \code{nomutex} is the normal'' parameter behaviour, with the \code{nomutex} keyword effectively stating explicitly that this routine is not special''. Another alternative is making exactly one of these keywords mandatory, which provides the same semantics but without the ambiguity of supporting routines with neither keyword. Mandatory keywords would also have the added benefit of being self-documented but at the cost of extra typing. While there are several benefits to mandatory keywords, they do bring a few challenges. Mandatory keywords in \CFA would imply that the compiler must know without doubt whether or not a parameter is a monitor or not. Since \CFA relies heavily on traits as an abstraction mechanism, the distinction between a type that is a monitor and a type that looks like a monitor can become blurred. For this reason, \CFA only has the \code{mutex} keyword and uses no keyword to mean \code{nomutex}. The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations: 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. Note that not all array functions are actually distinct in the type system. However, even if 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 of the receiver 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); 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: While OO monitors could be extended with a mutex qualifier for multiple-monitor calls, no example of this feature could be found. 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 different routines using the same monitors as arguments. This consistent ordering means acquiring multiple monitors in the way is safe from deadlock. However, users can still 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 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: 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\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: 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. While \CFA provides only a partial solution, many system provide no solution and the \CFA partial solution handles many useful cases. For example, \gls{multi-acq} and \gls{bulk-acq} can be used together in interesting ways: \begin{cfacode} monitor bank { ... }; } \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. \subsubsection{\code{mutex} statement} \label{mutex-stmt} 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{\code{mutex} statement} \label{mutex-stmt} 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. \end{cfacode} % ====================================================================== % ====================================================================== \section{Internal scheduling} \label{insched} Like threads and coroutines, monitors are defined in terms of traits with some additional language support in the form of the \code{monitor} keyword. The monitor trait is : \begin{cfacode} trait is_monitor(dtype T) { monitor_desc * get_monitor( T & ); void ^?{}( T & mutex ); }; \end{cfacode} Note that the destructor of a monitor must be a \code{mutex} routine. This requirement ensures that the destructor has mutual-exclusion. As with any object, any call to a monitor, using \code{mutex} or otherwise, is Undefined Behaviour after the destructor has run. % ====================================================================== % ====================================================================== \section{Internal scheduling} \label{intsched} % ====================================================================== % ====================================================================== \end{cfacode} 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. There are two details to note here. First, the \code{signal} is a delayed operation, it only unblocks the waiting thread when it reaches the end of the critical section. This semantic is needed to respect mutual-exclusion. The alternative is to return immediately after the call to \code{signal}, which is significantly more restrictive. Second, in \CFA, while it is common to store a \code{condition} as a field of the monitor, a \code{condition} variable can be stored/created independently of a monitor. Here routine \code{foo} waits for the \code{signal} from \code{bar} before making further progress, effectively ensuring a basic ordering. An important aspect of the implementation is that \CFA does not allow barging, which means that once function \code{bar} releases the monitor, \code{foo} is guaranteed to resume immediately after (unless some other thread waited on the same condition). This guarantees offers the benefit of not having to loop 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. % ====================================================================== % ====================================================================== % ====================================================================== 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. 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 the implicit condition as paremeter and explicitly names the monitors (A and B) associated with the condition. Note that in \CFA, condition variables are tied to a set of monitors on first use (called branding) which means that using internal scheduling with distinct sets of monitors requires one condition variable per set of monitors. \begin{multicols}{2} \end{pseudo} \end{multicols} 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 : This version uses \gls{bulk-acq} (denoted using the {\sf\&} 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 by a thread that holds more than one monitor. For example, the following pseudo-code runs into the nested-monitor problem : \begin{multicols}{2} \begin{pseudo} \end{pseudo} \end{multicols} The \code{wait} only releases monitor \code{B} so the signalling thread cannot acquire monitor \code{A} to get to the \code{signal}. Attempting release of all acquired monitors at the \code{wait} results in another set of problems such as releasing monitor \code{C}, which has nothing to do with the \code{signal}. 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. \end{multicols} 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. % ====================================================================== % ====================================================================== \subsection{Internal Scheduling - in depth} % ====================================================================== % ====================================================================== A larger example is presented to show complex issuesfor \gls{bulk-acq} and all the implementation options are analyzed. Listing \ref{lst:int-bulk-pseudo} shows an example where \gls{bulk-acq} adds a significant layer of complexity to the internal signalling semantics, and listing \ref{lst:int-bulk-cfa} shows the corresponding \CFA code which implements the pseudo-code in listing \ref{lst:int-bulk-pseudo}. For the purpose of translating the given pseudo-code into \CFA-code any method of introducing monitor into context, other than a \code{mutex} parameter, is acceptable, e.g., global variables, pointer parameters or using locals with the \code{mutex}-statement. \begin{figure}[!b] \begin{figure}[!b] \begin{center} \begin{cfacode}[xleftmargin=.4\textwidth] monitor A a; monitor B b; condition c; \end{cfacode} \end{center} \begin{multicols}{2} Waiting thread \begin{cfacode} monitor A; monitor B; extern condition c; void foo(A & mutex a, B & b) { mutex(a) { //Code Section 1 mutex(a, b) { Signalling thread \begin{cfacode} monitor A; monitor B; extern condition c; void foo(A & mutex a, B & b) { mutex(a) { //Code Section 5 mutex(a, b) { \end{figure} 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. The complexity begins at code sections 4 and 8, which are where the existing semantics of internal scheduling need to be extended for multiple monitors. The root of the problem is that \gls{bulk-acq} is used in a context where one of the monitors is already acquired and is why it is important to define the behaviour of the previous pseudo-code. When the signaller thread reaches the location where it should release \code{A & B}'' (line 16), it must actually transfer ownership of monitor \code{B} to the waiting thread. This ownership trasnfer is required in order to prevent barging. Since the signalling thread still needs monitor \code{A}, simply waking up the waiting thread is not an option because it violates 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 objects, effectively making the existing single monitor semantic viable by simply changing monitors to monitor groups. The obvious solution to solve the problem of multi-monitor scheduling is to keep ownership of all locks until the last lock is ready to be transferred. It can be argued that that moment is when the last lock is no longer needed because this semantics fits most closely to the behaviour of single-monitor scheduling. This solution has the main benefit of transferring ownership of groups of monitors, which simplifies the semantics from 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 \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 signalling monitor A on a different condition variable: \begin{multicols}{2} Thread 1 \begin{figure} \begin{multicols}{3} Thread $\alpha$ \begin{pseudo}[numbers=left, firstnumber=1] acquire A \end{pseudo} Thread 2 \begin{pseudo}[numbers=left, firstnumber=6] acquire A wait A release A \end{pseudo} \columnbreak Thread 3 \begin{pseudo}[numbers=left, firstnumber=9] Thread $\gamma$ \begin{pseudo}[numbers=left, firstnumber=1] acquire A acquire A & B signal A & B release A & B //Secretly keep B here signal A release A //Wakeup thread 1 or 2? //Who wakes up the other thread? \end{pseudo} \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} The goal in this solution is to avoid the need to transfer ownership of a subset of the condition monitors. However, this goal is unreacheable in the previous example. Depending on the order of signals (line 12 and 15) two cases can happen. 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 and therefore invalidates the main benefit of this approach. 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 effectively precludes 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 \ref{lst:int-bulk-pseudo} 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 \code{A & B} and then the waiter transfers back ownership of \code{A} when it releases it, then the problem is solved (\code{B} is no longer in use at this point). 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} \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} \caption{Dependency graph of the statements in listing \ref{lst:dependency}} \label{fig:dependency} \caption{Dependency graph of the statements 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 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. Listing \ref{lst:dependency} is the three thread example rewritten for dependency graphs. 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 (e.g., $\alpha1$ must happen before $\alpha2$). The extra challenge is that this dependency graph is effectively post-mortem, but the runtime 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} Finally, the solution that is chosen for \CFA is to use partial signalling. Consider the following case: \begin{multicols}{2} \begin{pseudo}[numbers=left] acquire A acquire A & B wait A & B release A & B release A \end{pseudo} \columnbreak \begin{pseudo}[numbers=left, firstnumber=6] acquire A acquire A & B 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 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. Finally, the solution that is chosen for \CFA is to use partial signalling. Again using listing \ref{lst:int-bulk-pseudo}, the partial signalling solution transfers ownership of monitor B at lines 10 but does not wake the waiting thread since it is still using monitor A. Only when it reaches line 11 does it actually wakeup the waiting thread. This solution has the benefit that complexity is encapsulated into only two actions, passing monitors to the next owner when they should be release and conditionally waking threads if all conditions are met. This solution has a much simpler implementation than a dependency graph solving algorithm which is why it was chosen. Furthermore, after being fully implemented, this solution does not appear to have any downsides worth mentionning. % ====================================================================== % ====================================================================== % ====================================================================== 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}. 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|} girlPhoneNo = phoneNo; //wake boy fron chair //wake boy from chair signal(exchange); } girlPhoneNo = phoneNo; //wake boy fron chair //wake boy from chair signal(exchange); } \label{lst:datingservice} \end{figure} 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}. The example in listing \ref{lst:datingservice} highlights the difference in behaviour. As mentioned, \code{signal} only transfers ownership once the current critical section exits, this behaviour requires additional synchronisation when a two-way handshake is needed. To avoid this extraneous synchronisation, the \code{condition} type offers the \code{signal_block} routine, which handles the two-way handshake 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. % ====================================================================== % ====================================================================== % ====================================================================== An alternative to internal scheduling is to use external scheduling. An alternative to internal scheduling is external scheduling, e.g., in \uC. \begin{center} \begin{tabular}{|c|c|} Internal Scheduling & External Scheduling \\ \begin{tabular}{|c|c|c|} Internal Scheduling & External Scheduling & Go\\ \hline \begin{ucppcode} \begin{ucppcode}[tabsize=3] _Monitor Semaphore { condition c; public: void P() { if(inUse) wait(c); if(inUse) wait(c); inUse = true; } } } \end{ucppcode}&\begin{ucppcode} \end{ucppcode}&\begin{ucppcode}[tabsize=3] _Monitor Semaphore { public: void P() { if(inUse) _Accept(V); if(inUse) _Accept(V); inUse = true; } } } \end{ucppcode} \end{ucppcode}&\begin{gocode}[tabsize=3] type MySem struct { inUse bool c     chan bool } // acquire func (s MySem) P() { if s.inUse { select { case <-s.c: } } s.inUse = true } // release func (s MySem) V() { s.inUse = false //This actually deadlocks //when single thread s.c <- false } \end{gocode} \end{tabular} \end{center} 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. 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. For the \code{P} member above using internal scheduling, the call to \code{wait} only guarantees that \code{V} is the last routine to access the monitor, allowing a third routine, say \code{isInUse()}, acquire mutual exclusion several times while routine \code{P} is waiting. On the other hand, external scheduling guarantees that while routine \code{P} is waiting, no routine other than \code{V} can acquire the monitor. % ====================================================================== % ====================================================================== % ====================================================================== In \uC, monitor declarations include an exhaustive list of monitor operations. Since \CFA is not object oriented it becomes both more difficult to implement but also less clear for the user: In \uC, monitor declarations include an exhaustive list of monitor operations. Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user: \begin{cfacode} \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 is to have a picture 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. Restricted to a fixed number of mutex members, N, the accept check reduces to updating a bitmask when the acceptor queue changes, a check that executes in a single instruction even with a fairly large number (e.g., 128) of mutex members. This technique cannot be used in \CFA because it relies on the fact that the monitor type enumerates (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. It is 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 alter the implementeation like this: \begin{center} \end{center} 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. Generating a mask dynamically means that the storage for the mask information can vary between calls to \code{waitfor}, allowing for more flexibility and extensions. Storing an array of accepted function-pointers replaces the single instruction bitmask compare with dereferencing a pointer followed by a linear search. Furthermore, supporting nested external scheduling (e.g., listing \ref{lst:nest-ext}) may now require additionnal searches on calls to \code{waitfor} statement to check if a routine is already queued in. \begin{figure} \begin{cfacode} monitor M {}; void foo( M & mutex a ) {} void bar( M & mutex b ) { //Nested in the waitfor(bar, c) call waitfor(foo, b); } void baz( M & mutex c ) { waitfor(bar, c); } \end{cfacode} \caption{Example of nested external scheduling} \label{lst:nest-ext} \end{figure} Note that in the second picture, tasks need to always keep track of 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, a decision must be made 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. % ====================================================================== void f(M & mutex a); void g(M & mutex a, M & mutex b) { waitfor(f); //ambiguous, keep a pass b or other way around? void g(M & mutex b, M & mutex c) { waitfor(f); //two monitors M => unkown which to pass to f(M & mutex) } \end{cfacode} \end{cfacode} 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. This syntax is unambiguous. Both locks are acquired and kept by \code{g}. 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 \code{waitfor} statement as follows. \begin{cfacode} 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 : An important behavior to note is when a set of monitors only match partially : \begin{cfacode} \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. 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 irrelevant; \code{waitfor(f,a,b)} and \code{waitfor(f,b,a)} are indistinguishable waiting condition. % ====================================================================== % ====================================================================== 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. 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 because the compiler validates at compile time the validity of the function type and the parameters used with the \code{waitfor} statement. It checks that the set of 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. \begin{figure} \begin{cfacode} waitfor(f2, a1, a2); //Incorrect : Mutex arguments don't match waitfor(f1, 1);      //Incorrect : 1 not a mutex argument waitfor(f4, a1);     //Incorrect : f9 not a function waitfor(*fp, a1 );   //Incorrect : fp not a identifier waitfor(f9, a1);     //Incorrect : f9 function does not exist waitfor(*fp, a1 );   //Incorrect : fp not an identifier waitfor(f4, a1);     //Incorrect : f4 ambiguous \end{figure} 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. Finally, for added flexibility, \CFA supports constructing complex \code{waitfor} mask using the \code{or}, \code{timeout} and \code{else}. Indeed, multiple \code{waitfor} can be chained together using \code{or}; this chain forms a single statement that uses baton-pass to any one function that fits one of the function+monitor set passed in. To eanble users to tell which accepted function is accepted, \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 call 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. \begin{figure} \label{lst:waitfor2} \end{figure} % ====================================================================== % ====================================================================== \subsection{Waiting for the destructor} % ====================================================================== % ====================================================================== An interesting use for the \code{waitfor} statement is destructor semantics. Indeed, the \code{waitfor} statement can accept any \code{mutex} routine, which includes the destructor (see section \ref{data}). However, with the semantics discussed until now, waiting for the destructor does not make any sense since using an object after its destructor is called is undefined behaviour. The simplest approach is to disallow \code{waitfor} on a destructor. However, a more expressive approach is to flip execution ordering when waiting for the destructor, meaning that waiting for the destructor allows the destructor to run after the current \code{mutex} routine, similarly to how a condition is signalled. \begin{figure} \begin{cfacode} monitor Executer {}; struct  Action; void ^?{}   (Executer & mutex this); void execute(Executer & mutex this, const Action & ); void run    (Executer & mutex this) { while(true) { waitfor(execute, this); or waitfor(^?{}   , this) { break; } } } \end{cfacode} \caption{Example of an executor which executes action in series until the destructor is called.} \label{lst:dtor-order} \end{figure} For example, listing \ref{lst:dtor-order} shows an example of an executor with an infinite loop, which waits for the destructor to break out of this loop. Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction.

• ## doc/proposals/concurrency/text/intro.tex

 rd06c808 % ====================================================================== This thesis provides a minimal concurrency \acrshort{api} that is simple, efficient and can be reused to build higher-level features. The simplest possible concurrency system is a thread and a lock but this low-level approach is hard to master. An easier approach for users is to support higher-level constructs as the basis of concurrency. Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{HPP:Study}. Examples are task based, message passing and implicit threading. The high-level approach and its minimal \acrshort{api} are tested in a dialect of C, call \CFA. [Is there value to say that this thesis is also an early definition of the \CFA language and library in regards to concurrency?] This thesis provides a minimal concurrency \acrshort{api} that is simple, efficient and can be reused to build higher-level features. The simplest possible concurrency system is a thread and a lock but this low-level approach is hard to master. An easier approach for users is to support higher-level constructs as the basis of concurrency. Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{HPP:Study}. Examples are task based, message passing and implicit threading. The high-level approach and its minimal \acrshort{api} are tested in a dialect of C, call \CFA. Furthermore, the proposed \acrshort{api} doubles as an early definition of the \CFA language and library. This thesis also comes with an implementation of the concurrency library for \CFA as well as all the required language features added to the source-to-source translator. There are actually two problems that need to be solved in the design of concurrency for a programming language: which concurrency and which parallelism tools are available to the programmer. While these two concepts are often combined, they are in fact distinct, requiring different tools~\cite{Buhr05a}. Concurrency tools need to handle mutual exclusion and synchronization, while parallelism tools are about performance, cost and resource utilization.

• ## doc/proposals/concurrency/text/together.tex

 rd06c808 } \end{cfacode} One of the obvious complaints of the previous code snippet (other than its toy-like simplicity) is that it does not handle exit conditions and just goes on for ever. Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner : One of the obvious complaints of the previous code snippet (other than its toy-like simplicity) is that it does not handle exit conditions and just goes on forever. Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner : \begin{cfacode} // Visualization declaration
• ## doc/proposals/concurrency/thesis.tex

 rd06c808 \usepackage[pagewise]{lineno} \usepackage{fancyhdr} \usepackage{float} \renewcommand{\linenumberfont}{\scriptsize\sffamily} \usepackage{siunitx} \sisetup{ binary-units=true } \input{style}                                                   % bespoke macros used in the document \usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref} \input{together} \input{results} \input{future}
• ## doc/proposals/concurrency/version

 rd06c808 0.10.212 0.11.47
• ## src/benchmark/Makefile.am

 rd06c808 noinst_PROGRAMS = all : ctxswitch$(EXEEXT) mutex$(EXEEXT) signal$(EXEEXT) waitfor$(EXEEXT) creation$(EXEEXT) bench$(EXEEXT) : ctxswitch-pthread$(EXEEXT): @BACKEND_CC@ ctxswitch/pthreads.c -DBENCH_N=50000000 -I. -lrt -pthread${AM_CFLAGS} ${CFLAGS}${ccflags} ## ========================================================================================================= creation$(EXEEXT) :\ creation-pthread.run \ creation-cfa_coroutine.run \ creation-cfa_thread.run \ creation-upp_coroutine.run \ creation-upp_thread.run creation-cfa_coroutine$(EXEEXT): ${CC} creation/cfa_cor.c -DBENCH_N=10000000 -I. -nodebug -lrt -quiet @CFA_FLAGS@${AM_CFLAGS} ${CFLAGS}${ccflags} creation-cfa_thread$(EXEEXT):${CC}        creation/cfa_thrd.c  -DBENCH_N=10000000   -I. -nodebug -lrt -quiet @CFA_FLAGS@ ${AM_CFLAGS}${CFLAGS} ${ccflags} creation-upp_coroutine$(EXEEXT): u++          creation/upp_cor.cc  -DBENCH_N=50000000   -I. -nodebug -lrt -quiet             ${AM_CFLAGS}${CFLAGS} ${ccflags} creation-upp_thread$(EXEEXT): u++          creation/upp_thrd.cc -DBENCH_N=50000000   -I. -nodebug -lrt -quiet             ${AM_CFLAGS}${CFLAGS} ${ccflags} creation-pthread$(EXEEXT): @BACKEND_CC@ creation/pthreads.c  -DBENCH_N=250000     -I. -lrt -pthread                    ${AM_CFLAGS}${CFLAGS} ${ccflags} ## ========================================================================================================= ## ========================================================================================================= creation$(EXEEXT) :\ creation-pthread.run            \ creation-cfa_coroutine.run      \ creation-cfa_thread.run         \ creation-upp_coroutine.run      \ creation-upp_thread.run creation-cfa_coroutine$(EXEEXT):${CC}        creation/cfa_cor.c   -DBENCH_N=10000000   -I. -nodebug -lrt -quiet @CFA_FLAGS@ ${AM_CFLAGS}${CFLAGS} ${ccflags} creation-cfa_thread$(EXEEXT): ${CC} creation/cfa_thrd.c -DBENCH_N=10000000 -I. -nodebug -lrt -quiet @CFA_FLAGS@${AM_CFLAGS} ${CFLAGS}${ccflags} creation-upp_coroutine$(EXEEXT): u++ creation/upp_cor.cc -DBENCH_N=50000000 -I. -nodebug -lrt -quiet${AM_CFLAGS} ${CFLAGS}${ccflags} creation-upp_thread$(EXEEXT): u++ creation/upp_thrd.cc -DBENCH_N=50000000 -I. -nodebug -lrt -quiet${AM_CFLAGS} ${CFLAGS}${ccflags} creation-pthread$(EXEEXT): @BACKEND_CC@ creation/pthreads.c -DBENCH_N=250000 -I. -lrt -pthread${AM_CFLAGS} ${CFLAGS}${ccflags} ## ========================================================================================================= %.run : %$(EXEEXT)${REPEAT}
• ## src/benchmark/Makefile.in

 rd06c808 .NOTPARALLEL: all : ctxswitch$(EXEEXT) mutex$(EXEEXT) signal$(EXEEXT) waitfor$(EXEEXT) creation$(EXEEXT) bench$(EXEEXT) : @for ccflags in "-debug" "-nodebug"; do \ @BACKEND_CC@ ctxswitch/pthreads.c  -DBENCH_N=50000000  -I. -lrt -pthread                    ${AM_CFLAGS}${CFLAGS} ${ccflags} creation$(EXEEXT) :\ creation-pthread.run            \ creation-cfa_coroutine.run      \ creation-cfa_thread.run         \ creation-upp_coroutine.run      \ creation-upp_thread.run creation-cfa_coroutine$(EXEEXT):${CC}        creation/cfa_cor.c   -DBENCH_N=10000000   -I. -nodebug -lrt -quiet @CFA_FLAGS@ ${AM_CFLAGS}${CFLAGS} ${ccflags} creation-cfa_thread$(EXEEXT): ${CC} creation/cfa_thrd.c -DBENCH_N=10000000 -I. -nodebug -lrt -quiet @CFA_FLAGS@${AM_CFLAGS} ${CFLAGS}${ccflags} creation-upp_coroutine$(EXEEXT): u++ creation/upp_cor.cc -DBENCH_N=50000000 -I. -nodebug -lrt -quiet${AM_CFLAGS} ${CFLAGS}${ccflags} creation-upp_thread$(EXEEXT): u++ creation/upp_thrd.cc -DBENCH_N=50000000 -I. -nodebug -lrt -quiet${AM_CFLAGS} ${CFLAGS}${ccflags} creation-pthread$(EXEEXT): @BACKEND_CC@ creation/pthreads.c -DBENCH_N=250000 -I. -lrt -pthread${AM_CFLAGS} ${CFLAGS}${ccflags} mutex$(EXEEXT) :\ mutex-function.run \ waitfor-cfa4$(EXEEXT): ${CC} schedext/cfa4.c -DBENCH_N=500000 -I. -nodebug -lrt -quiet @CFA_FLAGS@${AM_CFLAGS} ${CFLAGS}${ccflags} creation$(EXEEXT) :\ creation-pthread.run \ creation-cfa_coroutine.run \ creation-cfa_thread.run \ creation-upp_coroutine.run \ creation-upp_thread.run creation-cfa_coroutine$(EXEEXT): ${CC} creation/cfa_cor.c -DBENCH_N=10000000 -I. -nodebug -lrt -quiet @CFA_FLAGS@${AM_CFLAGS} ${CFLAGS}${ccflags} creation-cfa_thread$(EXEEXT):${CC}        creation/cfa_thrd.c  -DBENCH_N=10000000   -I. -nodebug -lrt -quiet @CFA_FLAGS@ ${AM_CFLAGS}${CFLAGS} ${ccflags} creation-upp_coroutine$(EXEEXT): u++          creation/upp_cor.cc  -DBENCH_N=50000000   -I. -nodebug -lrt -quiet             ${AM_CFLAGS}${CFLAGS} ${ccflags} creation-upp_thread$(EXEEXT): u++          creation/upp_thrd.cc -DBENCH_N=50000000   -I. -nodebug -lrt -quiet             ${AM_CFLAGS}${CFLAGS} ${ccflags} creation-pthread$(EXEEXT): @BACKEND_CC@ creation/pthreads.c  -DBENCH_N=250000     -I. -lrt -pthread                    ${AM_CFLAGS}${CFLAGS} ${ccflags} %.run : %$(EXEEXT) \${REPEAT}
• ## src/benchmark/csv-data.c

 rd06c808 StartTime = Time(); for( int i = 0;; i++ ) { signal(&cond1a); if( i > N ) break; wait(&cond1b); signal(cond1a); if( i > N ) break; wait(cond1b); } EndTime = Time(); void side1B( mon_t & mutex a ) { for( int i = 0;; i++ ) { signal(&cond1b); if( i > N ) break; wait(&cond1a); signal(cond1b); if( i > N ) break; wait(cond1a); } } StartTime = Time(); for( int i = 0;; i++ ) { signal(&cond2a); if( i > N ) break; wait(&cond2b); signal(cond2a); if( i > N ) break; wait(cond2b); } EndTime = Time(); void side2B( mon_t & mutex a, mon_t & mutex b ) { for( int i = 0;; i++ ) { signal(&cond2b); if( i > N ) break; wait(&cond2a); signal(cond2b); if( i > N ) break; wait(cond2a); } }
• ## src/benchmark/schedint/cfa1.c

 rd06c808 void __attribute__((noinline)) call( M & mutex a1 ) { signal(&c); signal(c); } BENCH( for (size_t i = 0; i < n; i++) { wait(&c); wait(c); }, result
• ## src/benchmark/schedint/cfa2.c

 rd06c808 void __attribute__((noinline)) call( M & mutex a1, M & mutex a2 ) { signal(&c); signal(c); } BENCH( for (size_t i = 0; i < n; i++) { wait(&c); wait(c); }, result
• ## src/benchmark/schedint/cfa4.c

 rd06c808 void __attribute__((noinline)) call( M & mutex a1, M & mutex a2, M & mutex a3, M & mutex a4 ) { signal(&c); signal(c); } BENCH( for (size_t i = 0; i < n; i++) { wait(&c); wait(c); }, result

• ## src/libcfa/concurrency/kernel_private.h

 rd06c808 void BlockInternal(thread_desc * thrd); void BlockInternal(spinlock * lock, thread_desc * thrd); void BlockInternal(spinlock ** locks, unsigned short count); void BlockInternal(spinlock ** locks, unsigned short count, thread_desc ** thrds, unsigned short thrd_count); void BlockInternal(spinlock * locks [], unsigned short count); void BlockInternal(spinlock * locks [], unsigned short count, thread_desc * thrds [], unsigned short thrd_count); void LeaveThread(spinlock * lock, thread_desc * thrd);
• ## src/libcfa/concurrency/monitor

 rd06c808 } // static inline int ?blocked.head; } uintptr_t front( condition * this ); void wait        ( condition & this, uintptr_t user_info = 0 ); bool signal      ( condition & this ); bool signal_block( condition & this ); static inline bool is_empty    ( condition & this ) { return !this.blocked.head; } uintptr_t front       ( condition & this ); //-----------------------------------------------------------------------------

• ## src/tests/boundedBuffer.c

 rd06c808 // // // The contents of this file are covered under the licence agreement in the // file "LICENCE" distributed with Cforall. // // boundedBuffer.c -- // // // boundedBuffer.c -- // // Author           : Peter A. Buhr // Created On       : Mon Oct 30 12:45:13 2017 // Last Modified On : Mon Oct 30 23:02:46 2017 // Update Count     : 9 // // #include void insert( Buffer & mutex buffer, int elem ) { if ( buffer.count == 20 ) wait( &buffer.empty ); if ( buffer.count == 20 ) wait( buffer.empty ); buffer.elements[buffer.back] = elem; buffer.back = ( buffer.back + 1 ) % 20; buffer.count += 1; signal( &buffer.full ); signal( buffer.full ); } int remove( Buffer & mutex buffer ) { if ( buffer.count == 0 ) wait( &buffer.full ); if ( buffer.count == 0 ) wait( buffer.full ); int elem = buffer.elements[buffer.front]; buffer.front = ( buffer.front + 1 ) % 20; buffer.count -= 1; signal( &buffer.empty ); signal( buffer.empty ); return elem; }
• ## src/tests/datingService.c

 rd06c808 //                               -*- Mode: C -*- // //                               -*- Mode: C -*- // // The contents of this file are covered under the licence agreement in the // file "LICENCE" distributed with Cforall. // // datingService.c -- // // // datingService.c -- // // Author           : Peter A. Buhr // Created On       : Mon Oct 30 12:56:20 2017 // Last Modified On : Mon Oct 30 23:02:11 2017 // Update Count     : 15 // // #include                                                                                // random #include #include                                                                              // getpid bool empty( condition & c ) { return c.blocked.head == NULL; } enum { NoOfPairs = 20 }; unsigned int girl( DatingService & mutex ds, unsigned int PhoneNo, unsigned int ccode ) { if ( empty( ds.Boys[ccode] ) ) { wait( &ds.Girls[ccode] ); if ( is_empty( ds.Boys[ccode] ) ) { wait( ds.Girls[ccode] ); ds.GirlPhoneNo = PhoneNo; } else { ds.GirlPhoneNo = PhoneNo; signal_block( &ds.Boys[ccode] ); signal_block( ds.Boys[ccode] ); } // if return ds.BoyPhoneNo; unsigned int boy( DatingService & mutex ds, unsigned int PhoneNo, unsigned int ccode ) { if ( empty( ds.Girls[ccode] ) ) { wait( &ds.Boys[ccode] ); if ( is_empty( ds.Girls[ccode] ) ) { wait( ds.Boys[ccode] ); ds.BoyPhoneNo = PhoneNo; } else { ds.BoyPhoneNo = PhoneNo; signal_block( &ds.Girls[ccode] ); signal_block( ds.Girls[ccode] ); } // if return ds.GirlPhoneNo;
• ## src/tests/sched-int-barge.c

 rd06c808 if( action == c.do_wait1 || action == c.do_wait2 ) { c.state = WAIT; wait( &cond ); wait( cond ); if(c.state != SIGNAL) { c.state = SIGNAL; signal( &cond ); signal( &cond ); signal( cond ); signal( cond ); } else {
• ## src/tests/sched-int-block.c

 rd06c808 //------------------------------------------------------------------------------ void wait_op( global_data_t & mutex a, global_data_t & mutex b, unsigned i ) { wait( &cond, (uintptr_t)this_thread ); wait( cond, (uintptr_t)this_thread ); yield( random( 10 ) ); [a.last_thread, b.last_thread, a.last_signaller, b.last_signaller] = this_thread; if( !is_empty( &cond ) ) { if( !is_empty( cond ) ) { thread_desc * next = front( &cond ); thread_desc * next = front( cond ); if( ! signal_block( &cond ) ) { if( ! signal_block( cond ) ) { sout | "ERROR expected to be able to signal" | endl; abort();
• ## src/tests/sched-int-disjoint.c

 rd06c808 // Waiting logic bool wait( global_t & mutex m, global_data_t & mutex d ) { wait( &cond ); wait( cond ); if( d.state != SIGNAL ) { sout | "ERROR barging!" | endl; //------------------------------------------------------------------------------ // Signalling logic void signal( condition * cond, global_t & mutex a, global_data_t & mutex b ) { void signal( condition & cond, global_t & mutex a, global_data_t & mutex b ) { b.state = SIGNAL; signal( cond ); void logic( global_t & mutex a ) { signal( &cond, a, data ); signal( cond, a, data ); yield( random( 10 ) );
• ## src/tests/sched-int-wait.c

 rd06c808 //---------------------------------------------------------------------------------------------------- // Tools void signal( condition * cond, global_t & mutex a, global_t & mutex b ) { void signal( condition & cond, global_t & mutex a, global_t & mutex b ) { signal( cond ); } void signal( condition * cond, global_t & mutex a, global_t & mutex b, global_t & mutex c ) { void signal( condition & cond, global_t & mutex a, global_t & mutex b, global_t & mutex c ) { signal( cond ); } void wait( condition * cond, global_t & mutex a, global_t & mutex b ) { void wait( condition & cond, global_t & mutex a, global_t & mutex b ) { wait( cond ); } void wait( condition * cond, global_t & mutex a, global_t & mutex b, global_t & mutex c ) { void wait( condition & cond, global_t & mutex a, global_t & mutex b, global_t & mutex c ) { wait( cond ); } switch( action ) { case 0: signal( &condABC, globalA, globalB, globalC ); signal( condABC, globalA, globalB, globalC ); break; case 1: signal( &condAB , globalA, globalB ); signal( condAB , globalA, globalB ); break; case 2: signal( &condBC , globalB, globalC ); signal( condBC , globalB, globalC ); break; case 3: signal( &condAC , globalA, globalC ); signal( condAC , globalA, globalC ); break; default: void main( WaiterABC & this ) { for( int i = 0; i < N; i++ ) { wait( &condABC, globalA, globalB, globalC ); wait( condABC, globalA, globalB, globalC ); } void main( WaiterAB & this ) { for( int i = 0; i < N; i++ ) { wait( &condAB , globalA, globalB ); wait( condAB , globalA, globalB ); } void main( WaiterAC & this ) { for( int i = 0; i < N; i++ ) { wait( &condAC , globalA, globalC ); wait( condAC , globalA, globalC ); } void main( WaiterBC & this ) { for( int i = 0; i < N; i++ ) { wait( &condBC , globalB, globalC ); wait( condBC , globalB, globalC ); }