% requires tex packages: texlive-base texlive-latex-base tex-common texlive-humanities texlive-latex-extra texlive-fonts-recommended % inline code �...� (copyright symbol) emacs: C-q M-) % red highlighting �...� (registered trademark symbol) emacs: C-q M-. % blue highlighting �...� (sharp s symbol) emacs: C-q M-_ % green highlighting �...� (cent symbol) emacs: C-q M-" % LaTex escape �...� (section symbol) emacs: C-q M-' % keyword escape �...� (pilcrow symbol) emacs: C-q M-^ % math escape $...$ (dollar symbol) \documentclass[twoside,11pt]{article} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Latex packages used in the document. \usepackage[T1]{fontenc} % allow Latin1 (extended ASCII) characters \usepackage{textcomp} \usepackage[latin1]{inputenc} \usepackage{fullpage,times,comment} \usepackage{epic,eepic} \usepackage{upquote} % switch curled `'" to straight \usepackage{calc} \usepackage{xspace} \usepackage{graphicx} \usepackage{tabularx} \usepackage[acronym]{glossaries} \usepackage{varioref} % extended references \usepackage{inconsolata} \usepackage{listings} % format program code \usepackage[flushmargin]{footmisc} % support label/reference in footnote \usepackage{latexsym} % \Box glyph \usepackage{mathptmx} % better math font with "times" \usepackage[usenames]{color} \usepackage[pagewise]{lineno} \usepackage{fancyhdr} \renewcommand{\linenumberfont}{\scriptsize\sffamily} \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} \usepackage{breakurl} \usepackage{tikz} \def\checkmark{\tikz\fill[scale=0.4](0,.35) -- (.25,0) -- (1,.7) -- (.25,.15) -- cycle;} \renewcommand{\UrlFont}{\small\sf} \setlength{\topmargin}{-0.45in} % move running title into header \setlength{\headsep}{0.25in} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Names used in the document. \newcommand{\Version}{1.0.0} \newcommand{\CS}{C\raisebox{-0.9ex}{\large$^\sharp$}\xspace} \newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}} \newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}} \newcommand{\R}[1]{\Textbf{#1}} \newcommand{\B}[1]{{\Textbf[blue]{#1}}} \newcommand{\G}[1]{{\Textbf[OliveGreen]{#1}}} \newcommand{\uC}{$\mu$\CC} \newcommand{\cit}{\textsuperscript{[Citation Needed]}\xspace} \newcommand{\code}[1]{\lstinline{#1}} \newcommand{\pseudo}[1]{\lstinline[language=Pseudo]{#1}} \input{glossary} \newsavebox{\LstBox} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \setcounter{secnumdepth}{3} % number subsubsections \setcounter{tocdepth}{3} % subsubsections in table of contents % \linenumbers % comment out to turn off line numbering \makeindex \pagestyle{fancy} \fancyhf{} \cfoot{\thepage} \rfoot{v\input{version}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{document} % \linenumbers \title{Concurrency in \CFA} \author{Thierry Delisle \\ School of Computer Science, University of Waterloo, \\ Waterloo, Ontario, Canada } \maketitle % ### # # ####### ###### ####### % # ## # # # # # # % # # # # # # # # # % # # # # # ###### # # % # # # # # # # # # % # # ## # # # # # % ### # # # # # ####### \section{Introduction} This proposal provides a minimal core concurrency API that is both simple, efficient and can be reused to build higher-level features. The simplest possible concurrency core 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 the concurrency in \CFA. Indeed, for highly productive parallel programming, high-level approaches are much more popular~\cite{HPP:Study}. Examples are task based parallelism, message passing and implicit threading. There are actually two problems that need to be solved in the design of the concurrency for a programming language. Which concurrency tools are available to the users and which parallelism tools are available. While these two concepts are often seen together, they are in fact distinct concepts that require different sorts of tools~\cite{Buhr05a}. Concurrency tools need to handle mutual exclusion and synchronization, while parallelism tools are more about performance, cost and resource utilization. % ##### ####### # # ##### # # ###### ###### ####### # # ##### # # % # # # # ## # # # # # # # # # # ## # # # # # % # # # # # # # # # # # # # # # # # # # # % # # # # # # # # # ###### ###### ##### # # # # # % # # # # # # # # # # # # # # # # # # # % # # # # # ## # # # # # # # # # # ## # # # % ##### ####### # # ##### ##### # # # # ####### # # ##### # \section{Concurrency} Several tool can be used to solve concurrency challenges. Since these challenges always 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. 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). Which in turn means that, in order to be effective, programmers need to learn two sets of designs patterns. This distinction can be hidden away in library code, but effective use of the librairy will still have to take both paradigms into account. Approaches based on shared memory are more closely related to non-concurrent paradigms since they often rely on non-concurrent constructs like routine calls and objects. At a lower level these can be implemented as locks and atomic operations. 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 to 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 possible to add such a paradigm to a language like C or \CC\cit, 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{Monitors} A monitor is a set of routines that ensure mutual exclusion when accessing shared state. This concept is generally associated with Object-Oriented Languages like Java~\cite{Java} or \uC~\cite{uC++book} but does not strictly require OOP semantics. The only requirements is the ability to declare a handle to a shared object and a set of routines that act on it : \begin{lstlisting} typedef /*some monitor type*/ monitor; int f(monitor & m); int main() { monitor m; f(m); } \end{lstlisting} % ##### # # # % # # # # # # % # # # # # % # # # # # % # ####### # # % # # # # # # % ##### # # ####### ####### \subsubsection{Call semantics} \label{call} The above monitor example displays some of their intrinsic characteristics. Indeed, it is necessary to use pass-by-reference over pass-by-value for monitor routines. This semantics is important because at their core, monitors are implicit mutual-exclusion objects (locks), and these objects cannot be copied. Therefore, monitors are implicitly non-copyable. Another aspect to consider is when a monitor acquires its mutual exclusion. For example, a monitor may need to be passed through multiple helper routines that do not acquire the monitor mutual exclusion on entry. Pass through can be both generic helper routines (\code{swap}, \code{sort}, etc.) or specific helper routines like the following to implement an atomic large counter : \begin{lstlisting} mutex struct counter_t { /*...*/ }; void ?{}(counter_t & nomutex this); size_t ++?(counter_t & mutex this); //need for mutex is platform dependent here void ?{}(size_t * this, counter_t & mutex cnt); \end{lstlisting} *semantics of the declaration of \code{mutex struct counter_t} are discussed in details in section \ref{data} 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 object not yet constructed should never be shared and therefore do 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} key word depending on whether or not reading an \code{size_t} is an atomic operation or not. Having both \code{mutex} and \code{nomutex} keywords could be argued to be redundant based on the meaning of a routine having neither of these keywords. If there were a meaning to routine \code{void foo(counter_t & this)} then one could argue that it should default to the safest option : \code{mutex}. On the other hand, the option of having routine \code{void foo(counter_t & this)} mean \code{nomutex} is unsafe by default and may easily cause subtle errors. It can be argued that this is the more "normal" behavior, \code{nomutex} effectively stating explicitly that "this routine has nothing 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 routine \code{void foo(counter_t & this)}. Mandatory keywords would also have the added benefice of being self-documented but at the cost of extra typing. In the end, which solution should be picked is still up for debate. For the reminder of this proposal, the explicit approach is used for clarity. Regardless of which keyword is kept, it is important to establish when mutex/nomutex may be used as a type qualifier. Consider : \begin{lstlisting} 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{lstlisting} The problem is to indentify which object(s) should be acquired. Furthermore, each object needs to be acquired only once. In case of simple routines like \code{f1} and \code{f2} it is easy to identify an exhaustive list of objects to acquire on entering. 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 we only acquire objects once becomes also none trivial. This can be extended to absurd limits like \code{f5}, which uses a graph of monitors. To keep everyone as sane as possible~\cite{Chicken}, this projects imposes the requirement that a routine may only acquire one monitor per parameter and it must be the type of the parameter (ignoring potential qualifiers and indirections). Also note that while routine \code{f3} can be supported, meaning that monitor \code{**m} will be acquired, passing an array to this routine would be type safe and result in undefined behavior. For this reason, it would also be reasonnable to disallow mutex in the context where arrays may be passed. % ###### # ####### # % # # # # # # # % # # # # # # # % # # # # # # # % # # ####### # ####### % # # # # # # # % ###### # # # # # \subsubsection{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 contian shared data. This data should be intrinsic to the monitor declaration to prevent any accidental use of data without its appripriate protection. For example here is a more fleshed-out version of the counter showed in \ref{call}: \begin{lstlisting} mutex struct counter_t { int value; }; void ?{}(counter_t & nomutex 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{lstlisting} This simple counter offers an example of monitor usage. Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting : \begin{center} \begin{tabular}{c @{\hskip 0.35in} c @{\hskip 0.35in} c} \begin{lstlisting} counter_t cnt; thread 1 : cnt++; thread 2 : cnt++; thread 3 : cnt++; ... thread N : cnt++; \end{lstlisting} \end{tabular} \end{center} These simple mutual exclusion semantics also naturally expand to multi-monitor calls. \begin{lstlisting} int f(MonitorA & mutex a, MonitorB & mutex b); MonitorA a; MonitorB b; f(a,b); \end{lstlisting} This code acquires both locks before entering the critical section (Referenced as \gls{group-acquire} from now on). In practice, writing multi-locking routines that can not lead to deadlocks can be 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 will be consistent across calls to routines using the same monitors as arguments. However, since \CFA monitors use multi-acquiring 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{lstlisting} void foo(A & mutex a, B & mutex a) { //... } void bar(A & mutex a, B & nomutex a) //... foo(a, b); //... } void baz(A & nomutex a, B & mutex a) //... foo(a, b); //... } \end{lstlisting} Such a use will lead to nested monitor call problems~\cite{Lister77}, which are a specific implementation of 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 deadlocks, depending on the implicit ordering matching the explicit ordering. As shown on several occasion\cit, solving this problems requires to : \begin{enumerate} \item Dynamically track 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. % ###### ####### ####### # ### # ##### % # # # # # # # # # # % # # # # # # # # # % # # ##### # # # # # ##### % # # # # ####### # # # % # # # # # # # # # # % ###### ####### # # # ### ####### ##### % % ###### ####### # # # # # ####### ###### # # % # # # # # # # ## ## # # # # # # % # # # # # # # # # # # # # # # # # % ##### ###### # # # # # # # # # ###### ####### % # # # # # # # # # # # # # % # # # # # # # # # # # # # % # ####### ####### # # # ####### # # # # \subsubsection{Implementation Details: Interaction with polymorphism} At first glance, interaction between monitors and \CFA's concept of polymorphism seem complex to support. However, it can be reasoned that entry-point locking can solve most of the issues that could be present with polymorphism. 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. \Gls{callsite-locking}\footnotemark would require a significant amount of work, 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}\footnotemark[\value{footnote}] calling a monitor routine becomes exactly the same as calling it from anywhere else. \footnotetext{See glossary for a definition of \gls{callsite-locking} and \gls{entry-point-locking}} % ### # # ####### ##### ##### # # ####### ###### % # ## # # # # # # # # # # # % # # # # # # # # # # # # % # # # # # ##### # ####### ##### # # % # # # # # ### # # # # # # # % # # ## # ### # # # # # # # # # % ### # # # ### ##### ##### # # ####### ###### \subsection{Internal scheduling} \label{insched} Monitors also need to schedule waiting threads within it as a mean of synchronization. Internal scheduling is one of the simple examples of such a feature. It allows users to declare condition variables and have threads wait and signaled from them. Here is a simple example of such a technique : \begin{lstlisting} mutex struct A { condition e; } void foo(A & mutex a) { //... wait(a.e); //... } void bar(A & mutex a) { signal(a.e); } \end{lstlisting} Here routine \code{foo} waits for the \code{signal} from \code{bar} before making further progress, effectively ensuring a basic ordering. This semantic can easily be extended to multi-monitor calls by offering the same guarantee. \begin{center} \begin{tabular}{ c @{\hskip 0.65in} c } Thread 1 & Thread 2 \\ \begin{lstlisting} void foo(monitor & mutex a, monitor & mutex b) { //... wait(a.e); //... } foo(a, b); \end{lstlisting} &\begin{lstlisting} void bar(monitor & mutex a, monitor & mutex b) { signal(a.e); } bar(a, b); \end{lstlisting} \end{tabular} \end{center} A direct extension of the single monitor semantics is to release all locks when waiting and transferring ownership of all locks when signalling. However, for the purpose of synchronization it may be usefull to only release some of the locks but keep others. It is possible to support internal scheduling and \gls{group-acquire} without any extra syntax by relying on order of acquisition. Here is an example of the different contexts in which internal scheduling can be used. (Note that here the use of helper routines is irrelevant, only routines acquire mutual exclusion have an impact on internal scheduling): \begin{center} \begin{tabular}{|c|c|c|} Context 1 & Context 2 & Context 3 \\ \hline \begin{lstlisting} condition e; void foo(monitor & mutex a, monitor & mutex b) { wait(e); } foo(a,b); \end{lstlisting} &\begin{lstlisting} condition e; void bar(monitor & mutex a, monitor & nomutex b) { foo(a,b); } void foo(monitor & mutex a, monitor & mutex b) { wait(e); } bar(a, b); \end{lstlisting} &\begin{lstlisting} condition e; void bar(monitor & mutex a, monitor & nomutex b) { baz(a,b); } void baz(monitor & nomutex a, monitor & mutex b) { wait(e); } bar(a, b); \end{lstlisting} \end{tabular} \end{center} Note that in \CFA, \code{condition} have no particular need to be stored inside a monitor, beyond any software engineering reasons. Context 1 is the simplest way of acquiring more than one monitor (\gls{group-acquire}), using a routine wiht multiple parameters having the \code{mutex} keyword. Context 2 also uses \gls{group-acquire} as well in routine \code{foo}. However, the routine is called by routine \code{bar} which only acquires monitor \code{a}. Since monitors can be acquired multiple times this will not cause a deadlock by itself but it does force the acquiring order to \code{a} then \code{b}. Context 3 also forces the acquiring order to be \code{a} then \code{b} but does not use \gls{group-acquire}. The previous example tries to illustrate the semantics that must be established to support releasing monitors in a \code{wait} statement. In all cases the behavior of the wait statment is to release all the locks that were acquired my the inner-most monitor call. That is \code{a & b} in context 1 and 2 and \code{b} only in context 3. Here are a few other examples of this behavior. \begin{center} \begin{tabular}{|c|c|c|} \begin{lstlisting} condition e; //acquire a void foo(monitor & nomutex a, monitor & mutex b) { bar(a,b); } //acquire a void bar(monitor & mutex a, monitor & nomutex b) { //release a //keep b wait(e); } foo(a, b); \end{lstlisting} &\begin{lstlisting} condition e; //acquire a & b void foo(monitor & mutex a, monitor & mutex b) { bar(a,b); } //acquire b void bar(monitor & mutex a, monitor & nomutex b) { //release b //keep a wait(e); } foo(a, b); \end{lstlisting} &\begin{lstlisting} condition e; //acquire a & b void foo(monitor & mutex a, monitor & mutex b) { bar(a,b); } //acquire none void bar(monitor & nomutex a, monitor & nomutex b) { //release a & b //keep none wait(e); } foo(a, b); \end{lstlisting} \end{tabular} \end{center} Note the right-most example which uses a helper routine and therefore is not relevant to find which monitors will be released. These semantics imply that in order to release of subset of the monitors currently held, users must write (and name) a routine that only acquires the desired subset and simply calls wait. While users can use this method, \CFA offers the \code{wait_release}\footnote{Not sure if an overload of \code{wait} would work...} which will release only the specified monitors. Regardless of the context in which the \code{wait} statement is used, \code{signal} must used holding the same set of monitors. In all cases, signal only needs a single parameter, the condition variable that needs to be signalled. But \code{signal} needs to be called from the same monitor(s) that call to \code{wait}. Otherwise, mutual exclusion cannot be properly transferred back to the waiting monitor. Finally, an additional semantic which can be very usefull is the \code{signal_block} routine. This routine behaves like signal for all of the semantics discussed above, but with the subtelty that mutual exclusion is transferred to the waiting task immediately rather than wating for the end of the critical section. \\ % ####### # # ####### ##### ##### # # ####### ###### % # # # # # # # # # # # # # % # # # # # # # # # # # % ##### # # ##### # ####### ##### # # % # # # # ### # # # # # # # % # # # # ### # # # # # # # # # % ####### # # # ### ##### ##### # # ####### ###### \newpage \subsection{External scheduling} \label{extsched} As one might expect, the alternative to Internal scheduling is to use External scheduling instead. This method is somewhat more robust to deadlocks since one of the threads keeps a relatively tight control on scheduling. Indeed, as the following examples will demonstrate, 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 (ex: \uC) or in terms of data (ex: Go). Of course, both of these paradigms have their own strenghts and weaknesses but for this project control flow semantics where 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 following example shows what a simple use \code{accept} versus \code{wait}/\code{signal} and its advantages. \begin{center} \begin{tabular}{|c|c|} Internal Scheduling & External Scheduling \\ \hline \begin{lstlisting} _Monitor blarg { condition c; public: void f() { signal(c)} void g() { wait(c); } private: } \end{lstlisting}&\begin{lstlisting} _Monitor blarg { public: void f(); void g() { _Accept(f); } private: } \end{lstlisting} \end{tabular} \end{center} In the case of internal scheduling, the call to \code{wait} only guarantees that \code{g} was the last routine to access the monitor. This intails that the routine \code{f} may have acquired mutual exclusion several times while routine \code{h} was waiting. On the other hand, external scheduling guarantees that while routine \code{h} was waiting, no routine other than \code{g} could acquire the monitor. \\ % # ####### ####### ##### ####### ####### ###### # ##### % # # # # # # # # # # # # # # # % # # # # # # # # # # # # # % # # # # # ##### ##### # # ###### # ##### % # # # # # # # # # # # # # # % # # # # # # # # # # # # # # # # % ####### ####### ####### ##### ####### ####### ###### ##### ##### \subsubsection{Loose object definitions} 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 : \begin{lstlisting} mutex struct A {}; void f(A & mutex a); void g(A & mutex a) { accept(f); } \end{lstlisting} However, external scheduling is an example where implementation constraints become visible from the interface. Indeed, ince there is no hard limit to the number of threads trying to acquire a monitor concurrently, performance is a significant concern. Here is the pseudo code for the entering phase of a monitor : \begin{center} \begin{tabular}{l} \begin{lstlisting}[language=Pseudo] if monitor is free : enter elif monitor accepts me : enter else : block \end{lstlisting} \end{tabular} \end{center} For the \pseudo{monitor is free} condition it is easy to implement a check that can evaluate the condition in a few instruction. However, a fast check for \pseudo{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} {\resizebox{0.4\textwidth}{!}{\input{monitor}}} \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 of acceptor. However, this relies on the fact that all the acceptable routines are declared with the monitor type. For OO languages this doesn't compromise much since monitors already have an exhaustive list of member routines. However, for \CFA this isn't 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: \begin{center} {\resizebox{0.4\textwidth}{!}{\input{ext_monitor}}} \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 accept 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 either cases here are a few alternatives for the different syntaxes this syntax : \\ \begin{center} {\renewcommand{\arraystretch}{1.5} \begin{tabular}[t]{l @{\hskip 0.35in} l} \hline \multicolumn{2}{ c }{\code{accept} on type}\\ \hline Alternative 1 & Alternative 2 \\ \begin{lstlisting} mutex struct A accept( void f(A & mutex a) ) {}; \end{lstlisting} &\begin{lstlisting} mutex struct A {} accept( void f(A & mutex a) ); \end{lstlisting} \\ Alternative 3 & Alternative 4 \\ \begin{lstlisting} mutex struct A { accept( void f(A & mutex a) ) }; \end{lstlisting} &\begin{lstlisting} mutex struct A { accept : void f(A & mutex a) ); }; \end{lstlisting}\\ \hline \multicolumn{2}{ c }{\code{accept} on routine}\\ \hline \begin{lstlisting} mutex struct A {}; void f(A & mutex a) accept( void f(A & mutex a) ) void g(A & mutex a) { /*...*/ } \end{lstlisting}&\\ \end{tabular} } \end{center} An other 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 should be scheduled regardless of the overload used. However, this could easily be extended in the future. % # # # # # ####### ### # # ####### # # % ## ## # # # # # ## ## # # ## # % # # # # # # # # # # # # # # # # # # % # # # # # # # # # # # # # # # # % # # # # # # # # # # # # # # % # # # # # # # # # # # # ## % # # ##### ####### # ### # # ####### # # \subsubsection{Multi-monitor scheduling} 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{lstlisting} accept( void f(mutex struct A & mutex this)) mutex struct A {}; mutex struct B {}; void g(A & mutex a, B & mutex b) { accept(f); //ambiguous, which monitor } \end{lstlisting} The obvious solution is to specify the correct monitor as follows : \begin{lstlisting} accept( void f(mutex struct A & mutex this)) mutex struct A {}; mutex struct B {}; void g(A & mutex a, B & mutex b) { accept( f, b ); } \end{lstlisting} This is unambiguous. Both locks will be acquired and kept, when routine \code{f} is called the lock for monitor \code{a} will be temporarily transferred from \code{g} to \code{f} (while \code{g} still holds lock \code{b}). This behavior can be extended to multi-monitor accept statment as follows. \begin{lstlisting} accept( void f(mutex struct A & mutex, mutex struct A & mutex)) mutex struct A {}; mutex struct B {}; void g(A & mutex a, B & mutex b) { accept( f, b, a ); } \end{lstlisting} Note that the set of monitors passed to the \code{accept} statement must be entirely contained in the set of monitor already acquired in the routine. \code{accept} used in any other context is Undefined Behaviour. % ###### ####### ####### # ### # ##### % # # # # # # # # # # % # # # # # # # # # % # # ##### # # # # # ##### % # # # # ####### # # # % # # # # # # # # # # % ###### ####### # # # ### ####### ##### % % ##### # # ####### # # ####### ##### % # # # # # # # # # # % # # # # # # # # # % ##### # # # # ##### # # ##### ##### % # # # # # # # # # # % # # # # # # # # # # % #### # ##### ####### ##### ####### ##### \subsubsection{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 reasonnable 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{Other concurrency tools} TO BE CONTINUED... \newpage % ###### # ###### # # # ####### # ### ##### # # % # # # # # # # # # # # # # # # ## ## % # # # # # # # # # # # # # # # # # # % ###### # # ###### # # # # ##### # # ##### # # # % # ####### # # ####### # # # # # # # # % # # # # # # # # # # # # # # # # % # # # # # # # ####### ####### ####### ####### ### ##### # # \section{Parallelism} Historically, computer performance was about processor speeds and instructions count. However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}. In this decade, it is not longer reasonnable to create high-performance application without caring about parallelism. Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization. The lowest level approach of parallelism is to use \glspl{kthread} in combination with semantics like \code{fork}, \code{join}, etc. However, since these have significant costs and limitations \glspl{kthread} are now mostly used as an implementation tool rather than a user oriented one. There are several alternatives to solve these issues that all have strengths and weaknesses. While there are many variations of the presented paradigms, most of these variations do not actually change the guarantees or the semantics, they simply move costs in order to achieve better performance for certain workloads. \subsection{User-level threads} A direct improvement on the \gls{kthread} approach is to use \glspl{uthread}. These threads offer most of the same features that the operating system already provide but can be used on a much larger scale. This approach is the most powerfull solution as it allows all the features of multi-threading while removing several of the more expensives costs of using kernel threads. The down side is that almost none of the low-level threading problems are hidden, users still have to think about data races, deadlocks and synchronization issues. These issues can be somewhat alleviated by a concurrency toolkit with strong garantees but the parallelism toolkit offers very little to reduce complexity in itself. Examples of languages that support are Erlang~\cite{Erlang} and \uC~\cite{uC++book}. \subsection{Fibers : user-level threads without preemption} In the middle of the flexibility versus complexity spectrum lay \glspl{fiber} which offer \glspl{uthread} without the complexity of preemption by using cooperative scheduling. On a single core machine this means users need not worry about concurrency. On multi-core machines, while concurrency is still a concern, it is only a problem for fibers across cores but not while on the same core. This extra guarantee plus the fact that creating and destroying fibers are implicit synchronizing points means preventing mutable shared ressources still leaves many control flow options. However, multi-core processors can still execute fibers in parallel. This means users either need to worry about mutual exclusion, deadlocks and race conditions, or limit themselves to subset of concurrency primitives, raising the complexity in both cases. In this aspect, fibers can be seen as a more powerfull alternative to \glspl{job}. An example of a language that uses fibers is Go~\cite{Go} \subsection{Jobs and thread pools} The approach on the opposite end of the spectrum is to base parallelism on \glspl{pool}. Indeed, \glspl{pool} offer limited flexibility but at the benefit of a simpler user interface. In \gls{pool} based systems, users express parallelism as units of work and the dependency graph (either explicit or implicit) that tie them together. This approach means users need not worry about concurrency but significantly limits the interaction that can occur between different jobs. Indeed, any \gls{job} that blocks also blocks the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably. It can be argued that a solution to this problem is to use more workers than available cores. However, unless the number of jobs and the number of workers are comparable, having a significant amount of blocked jobs will always results in idles cores. The gold standard of this implementation is Intel's TBB library~\cite{TBB}. \subsection{Paradigm performance} While the choice between the three paradigms listed above may have significant performance implication, it is difficult to pindown the performance implications of chosing a model at the language level. Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload. Having a large amount of mostly independent units of work to execute almost guarantess that the \gls{pool} based system has the best performance thanks to the lower memory overhead. However, interactions between jobs can easily exacerbate contention. User-level threads may allows fine grain context switching which may result in better resource utilisation but context switches will be more expansive and it is also harder for users to get perfect tunning. As with every example, fibers sit somewhat in the middle of the spectrum. Furthermore, if the units of uninterrupted work are large enough the paradigm choice will be largely amorticised by the actual work done. % ##### ####### # ####### ###### ###### % # # # # # # # # # # % # # # # # # # # # % # ##### # # ##### # ###### ###### % # # ####### # # # # # % # # # # # # # # # # % ##### # # # # ###### ###### \section{\CFA 's Thread Building Blocks} As a system level language, \CFA should offer both performance and flexibilty as its primary goals, simplicity and user-friendliness being a secondary concern. Therefore, the core of parallelism in \CFA should prioritize power and efficiency. With this said, it is possible to deconstruct the three paradigms details aboved in order to get simple building blocks. Here is a table showing the core caracteristics of the mentionned paradigms : \begin{center} \begin{tabular}[t]{| r | c | c |} \cline{2-3} \multicolumn{1}{ c| }{} & Has a stack & Preemptive \\ \hline \Glspl{pool} & X & X \\ \hline \Glspl{fiber} & \checkmark & X \\ \hline \Glspl{uthread} & \checkmark & \checkmark \\ \hline \end{tabular} \end{center} This table is missing several variations (for example jobs on \glspl{uthread} or \glspl{fiber}), but these variation affect mostly performance and do not effect the guarantees as the presented paradigm do. As shown in section \ref{cfaparadigms} these different blocks being available in \CFA it is trivial to reproduce any of these paradigm. % ####### # # ###### ####### # ###### ##### % # # # # # # # # # # # # % # # # # # # # # # # # % # ####### ###### ##### # # # # ##### % # # # # # # ####### # # # % # # # # # # # # # # # # % # # # # # ####### # # ###### ##### \subsection{Thread Interface} The basic building blocks of \CFA are \glspl{cfathread}. By default these are implemented as \glspl{uthread} and as such offer a flexible and lightweight threading interface (lightweight comparatievely to \glspl{kthread}). A thread can be declared using a struct declaration with prefix \code{thread} as follows : \begin{lstlisting} thread struct foo {}; \end{lstlisting} Obviously, for this thread implementation to be usefull it must run some user code. Several other threading interfaces use some function pointer representation as the interface of threads (for example : \Csharp~\cite{Csharp} and Scala~\cite{Scala}). However, this proposal considers that statically tying a \code{main} routine to a thread superseeds this approach. Since the \code{main} routine is definitely a special routine in \CFA, the existing syntax for declaring routines with unordinary name can be extended, i.e. operator overloading. As such the \code{main} routine of a thread can be defined as : \begin{lstlisting} thread struct foo {}; void ?main(thread foo* this) { /*... Some useful code ...*/ } \end{lstlisting} With these semantics it is trivial to write a thread type that takes a function pointer as parameter and executes it on its stack asynchronously : \begin{lstlisting} typedef void (*voidFunc)(void); thread struct FuncRunner { voidFunc func; }; //ctor void ?{}(thread FuncRunner* this, voidFunc inFunc) { func = inFunc; } //main void ?main(thread FuncRunner* this) { this->func(); } \end{lstlisting} % In this example \code{func} is a function pointer stored in \acrfull{tls}, which is \CFA is both easy to use and completly typesafe. Of course for threads to be useful, it must be possible to start and stop threads and wait for them to complete execution. While using an \acrshort{api} such as \code{fork} and \code{join} is relatively common in the literature, such an interface is not needed. Indeed, the simplest approach is to use \acrshort{raii} principles and have threads \code{fork} once the constructor has completed and \code{join} before the destructor runs. \begin{lstlisting} thread struct FuncRunner; //FuncRunner declared above void world() { sout | "World!" | endl; } void main() { FuncRunner run = {world}; //Thread run forks here //Print to "Hello " and "World!" will be run concurrently sout | "Hello " | endl; //Implicit join at end of scope } \end{lstlisting} This semantic has several advantages over explicit semantics : typesafety is guaranteed, a thread is always started and stopped exaclty once and users cannot make any progamming errors. Furthermore it naturally follows the memory allocation semantics, which means users do not need to learn multiple semantics. These semantics also naturally scale to multiple threads meaning basic synchronisation is very simple : \begin{lstlisting} thread struct MyThread { //... }; //ctor void ?{}(thread MyThread* this) {} //main void ?main(thread MyThread* this) { //... } void foo() { MyThread thrds[10]; //Start 10 threads at the beginning of the scope DoStuff(); //Wait for the 10 threads to finish } void bar() { MyThread* thrds = new MyThread[10]; //Start 10 threads at the beginning of the scope DoStuff(); //Wait for the 10 threads to finish delete MyThread; } \end{lstlisting} \newpage \large{\textbf{WORK IN PROGRESS}} \subsection{The \CFA Kernel : Processors, Clusters and Threads}\label{kernel} \subsection{Paradigms}\label{cfaparadigms} Given these building blocks we can then reproduce the all three of the popular paradigms. Indeed, we get \glspl{uthread} as the default paradigm in \CFA. However, disabling \glspl{preemption} on the \gls{cfacluster} means \glspl{cfathread} effectively become \glspl{fiber}. Since several \glspl{cfacluster} with different scheduling policy can coexist in the same application, this allows \glspl{fiber} and \glspl{uthread} to coexist in the runtime of an application. % \subsection{High-level options}\label{tasks} % % \subsubsection{Thread interface} % constructors destructors % initializer lists % monitors % % \subsubsection{Futures} % % \subsubsection{Implicit threading} % Finally, simpler applications can benefit greatly from having implicit parallelism. That is, parallelism that does not rely on the user to write concurrency. This type of parallelism can be achieved both at the language level and at the system level. % % \begin{center} % \begin{tabular}[t]{|c|c|c|} % Sequential & System Parallel & Language Parallel \\ % \begin{lstlisting} % void big_sum(int* a, int* b, % int* out, % size_t length) % { % for(int i = 0; i < length; ++i ) { % out[i] = a[i] + b[i]; % } % } % % % % % % int* a[10000]; % int* b[10000]; % int* c[10000]; % //... fill in a and b ... % big_sum(a, b, c, 10000); % \end{lstlisting} &\begin{lstlisting} % void big_sum(int* a, int* b, % int* out, % size_t length) % { % range ar(a, a + length); % range br(b, b + length); % range or(out, out + length); % parfor( ai, bi, oi, % [](int* ai, int* bi, int* oi) { % oi = ai + bi; % }); % } % % int* a[10000]; % int* b[10000]; % int* c[10000]; % //... fill in a and b ... % big_sum(a, b, c, 10000); % \end{lstlisting}&\begin{lstlisting} % void big_sum(int* a, int* b, % int* out, % size_t length) % { % for (ai, bi, oi) in (a, b, out) { % oi = ai + bi; % } % } % % % % % % int* a[10000]; % int* b[10000]; % int* c[10000]; % //... fill in a and b ... % big_sum(a, b, c, 10000); % \end{lstlisting} % \end{tabular} % \end{center} % % \subsection{Machine setup}\label{machine} % Threads are all good and well but wee still some OS support to fully utilize available hardware. % % \textbf{\large{Work in progress...}} Do wee need something beyond specifying the number of kernel threads? % # # # % # # # # % # # # # % # # # # % ####### # # % # # # # % # # ####### ####### \section{Putting it all together} % ####### # # ####### # # ###### ####### % # # # # # # # # # % # # # # # # # # # % ##### # # # # # ###### ##### % # # # # # # # # # % # # # # # # # # # % # ##### # ##### # # ###### \section{Future work} Concurrency and parallelism is still a very active field that strongly benefits from hardware advances. As such certain features that aren't necessarily mature enough in their current state could become relevant in the lifetime of \CFA. \subsection{Transactions} % ####### # # ###### % # ## # # # % # # # # # # % ##### # # # # # % # # # # # # % # # ## # # % ####### # # ###### \section*{Acknowledgements} \clearpage \printglossary[type=\acronymtype] \printglossary \clearpage \bibliographystyle{plain} \bibliography{cw92,distSharedMem,lfp92,mlw92,parallel,parallelIO,partheory,pl,pldi92,ps,realtime,techreportsPAB,visual,local} \end{document}