Ignore:
Timestamp:
Oct 26, 2016, 11:03:01 AM (7 years ago)
Author:
Rob Schluntz <rschlunt@…>
Branches:
ADT, aaron-thesis, arm-eh, ast-experimental, cleanup-dtors, deferred_resn, demangler, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, pthread-emulation, qualifiedEnum, resolv-new, with_gc
Children:
77971f6
Parents:
f0121d7 (diff), fe7b281 (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' into tuples

Conflicts:

src/Parser/parser.cc
src/Parser/parser.yy

File:
1 edited

Legend:

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

    rf0121d7 ra1e67dd  
    11% requires tex packages: texlive-base texlive-latex-base tex-common texlive-humanities texlive-latex-extra texlive-fonts-recommended
    22
    3 % inline code �...� (copyright symbol) emacs: C-q M-)
    4 % red highlighting �...� (registered trademark symbol) emacs: C-q M-.
    5 % blue highlighting �...� (sharp s symbol) emacs: C-q M-_
    6 % green highlighting �...� (cent symbol) emacs: C-q M-"
    7 % LaTex escape �...� (section symbol) emacs: C-q M-'
    8 % keyword escape �...� (pilcrow symbol) emacs: C-q M-^
     3% inline code ©...© (copyright symbol) emacs: C-q M-)
     4% red highlighting ®...® (registered trademark symbol) emacs: C-q M-.
     5% blue highlighting ß...ß (sharp s symbol) emacs: C-q M-_
     6% green highlighting ¢...¢ (cent symbol) emacs: C-q M-"
     7% LaTex escape §...§ (section symbol) emacs: C-q M-'
     8% keyword escape ¶...¶ (pilcrow symbol) emacs: C-q M-^
    99% math escape $...$ (dollar symbol)
    1010
     
    2424\usepackage{graphicx}
    2525\usepackage{tabularx}
    26 \usepackage{glossaries}
     26\usepackage[acronym]{glossaries}
    2727\usepackage{varioref}                                                           % extended references
    2828\usepackage{inconsolata}
     
    3333\usepackage[usenames]{color}
    3434\usepackage[pagewise]{lineno}
     35\usepackage{fancyhdr}
    3536\renewcommand{\linenumberfont}{\scriptsize\sffamily}
    3637\input{common}                                          % bespoke macros used in the document
    3738\usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
    3839\usepackage{breakurl}
     40
     41\usepackage{tikz}
     42\def\checkmark{\tikz\fill[scale=0.4](0,.35) -- (.25,0) -- (1,.7) -- (.25,.15) -- cycle;}
    3943
    4044\renewcommand{\UrlFont}{\small\sf}
     
    5862\newcommand{\cit}{\textsuperscript{[Citation Needed]}\xspace}
    5963\newcommand{\code}[1]{\lstinline{#1}}
     64\newcommand{\pseudo}[1]{\lstinline[language=Pseudo]{#1}}
    6065
    6166\input{glossary}
     
    6772\setcounter{secnumdepth}{3}                             % number subsubsections
    6873\setcounter{tocdepth}{3}                                % subsubsections in table of contents
     74% \linenumbers                                            % comment out to turn off line numbering
    6975\makeindex
     76\pagestyle{fancy}
     77\fancyhf{}
     78\cfoot{\thepage}
     79\rfoot{v\input{version}}
    7080
    7181%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     
    8191\maketitle
    8292\section{Introduction}
    83 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 core is a thread and a lock but this low level approach is hard to master. An easier approach for users is be to support higher level construct as the basis of the concurrency in \CFA.
    84 Indeed, for higly productive parallel programming high-level approaches are much more popular\cite{HPP:Study}. Examples are task based parallelism, message passing, implicit threading.
    85 
    86 There are actually two problems that need to be solved in the design of the concurrency for a 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 ressource utilisation.
     93This proposal provides a minimal core concurrency API that is both simple, efficient and can be reused to build higher-level features. The simplest possible 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 construct as the basis of the concurrency in \CFA.
     94Indeed, for highly productive parallel programming high-level approaches are much more popular\cite{HPP:Study}. Examples are task based parallelism, message passing, implicit threading.
     95
     96There are actually two problems that need to be solved in the design of the concurrency for a 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.
    8797
    8898\section{Concurrency}
    89 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 completely (Erlang\cite{Erlang}, Haskell\cite{Haskell}, Akka (Scala)\cit). In the paradigms, interaction between concurrent objects rely on message passing or other paradigms that often closely relate to networking concepts. However, in imperative or OO languages these approaches entail a clear distinction between concurrent and non concurrent paradigms. Which in turns mean that programmers need to learn two sets of designs patterns in order to be effective at their jobs. 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. However for productivity reasons it is desireable to have a higher-level construct to be the core concurrency paradigm\cite{HPP:Study}. This paper proposes Monitors\cit as the core concurrency construct.
     99Several 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 rely on message passing or other paradigms that often closely relate to networking concepts. However, in imperative or OO languages, these approaches entail a clear distinction between concurrent and non-concurrent paradigms (i.e. message passing versus routine call). Which in turns mean that programmers need to learn two sets of designs patterns in order to be effective. 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. However, for productivity reasons it is desireable to have a higher-level construct to be the core concurrency paradigm\cite{HPP:Study}. This project proposes Monitors\cite{Hoare74} as the core concurrency construct.
     100\\
    90101
    91102Finally, an approach that is worth mentionning because it is gaining in popularity is transactionnal memory\cite{Dice10}. However, 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.
    92103
    93 \section{Monitors}
    94 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 to be able to declare a handle to a shared object and a set of routines that act on it :
     104\subsection{Monitors}
     105A 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 :
    95106\begin{lstlisting}
    96107        typedef /*some monitor type*/ monitor;
     
    103114\end{lstlisting}
    104115
    105 \subsection{Call semantics} \label{call}
    106 The above example of monitors already displays some of their intrinsic caracteristics. Indeed, it is necessary to use pass-by-reference over pass-by-value for monitor routines. This semantics is important because since at their core, monitors are simply implicit mutual exclusion objects (locks) and copying semantics of these is ill defined. Therefore, monitors are implicitly non-copyable.
    107 
    108 Another aspect to consider is when a monitor acquires its mutual exclusion. Indeed, a monitor may need to be passed to helper routines that do not acquire the monitor mutual exclusion on entry. Examples of this can be both generic helper routines (\code{swap}, \code{sort}, etc.) or specific helper routines like the following example :
     116\subsubsection{Call semantics} \label{call}
     117The above example of monitors already displays some of their intrinsic caracteristics. 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.
     118\\
     119
     120Another aspect to consider is when a monitor acquires its mutual exclusion. Indeed, a monitor may need to be passed through multiple helper routines that do not acquire the monitor mutual exclusion on entry. Examples of this can be both generic helper routines (\code{swap}, \code{sort}, etc.) or specific helper routines like the following example :
    109121
    110122\begin{lstlisting}
    111123        mutex struct counter_t { /*...*/ };
    112124
    113         void ?{}(counter_t & mutex this);
     125        void ?{}(counter_t & nomutex this);
    114126        int ++?(counter_t & mutex this);
    115         void ?{}(int * this, counter_t & mutex cnt);
    116 
    117         bool is_zero(counter_t & nomutex this) {
    118                 int val = this;
    119                 return val == 0;
    120         }
    121 \end{lstlisting}
    122 *semantics of the declaration of \code{mutex struct counter_t} will be discussed in details in \ref{data}
    123 
    124 This is an example of a monitor used as safe(ish) counter for concurrency. This API, which offers the prefix increment operator and a conversion operator to \code{int}, guarantees that reading the value (by converting it to \code{int}) and incrementing it are mutually exclusive. Note that the \code{is_zero} routine uses the \code{nomutex} keyword. Indeed, since reading the value is already atomic, there is no point in maintaining the mutual exclusion once the value is copied locally (in the variable \code{val} ).
     127        void ?{}(Int * this, counter_t & mutex cnt);
     128\end{lstlisting}
     129*semantics of the declaration of \code{mutex struct counter_t} are discussed in details in section \ref{data}
     130\\
     131
     132This example is of a monitor implementing an atomic counter. Here, the constructor uses the \code{nomutex} keyword to signify that it does not acquire the coroutine mutual exclusion when constructing. This is because object not yet constructed should never be shared and therefore do not require mutual exclusion. The prefix increment operator
     133uses \code{mutex} to protect the incrementing process from race conditions. Finally, we have a conversion operator from \code{counter_t} to \code{Int}. This conversion may or may not require the \code{mutex} key word depending whether or not reading an \code{Int} is an atomic operation or not.
     134\\
    125135
    126136Having 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 be to 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". An other alternative is to make 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 more clearly 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 will be used for the sake of clarity.
     137\\
    127138
    128139Regardless of which keyword is kept, it is important to establish when mutex/nomutex may be used depending on type parameters.
    129140\begin{lstlisting}
    130         int f01(monitor & mutex m);
    131         int f02(const monitor & mutex m);
    132         int f03(monitor * mutex m);
    133         int f04(monitor * mutex * m);
    134         int f05(monitor ** mutex m);
    135         int f06(monitor[10] mutex m);
    136         int f07(monitor[] mutex m);
    137         int f08(vector(monitor) & mutex m);
    138         int f09(list(monitor) & mutex m);
    139         int f10([monitor*, int] & mutex m);
    140         int f11(graph(monitor*) & mutex m);
    141 \end{lstlisting}
    142 
    143 For the first few routines it seems to make sense to support the mutex keyword for such small variations. The difference between pointers and reference (\code{f01} vs \code{f03}) or const and non-const (\code{f01} vs \code{f02}) has no significance to mutual exclusion. It may not always make sense to acquire the monitor when extra dereferences (\code{f04}, \code{f05}) are added but it is still technically feasible and the present of the explicit mutex keywork does make it very clear of the user's intentions. Passing in a known-sized array(\code{f06}) is also technically feasible but is close to the limits. Indeed, the size of the array is not actually enforced by the compiler and if replaced by a variable-sized array (\code{f07}) or a higher-level container (\code{f08}, \code{f09}) it becomes much more complex to properly acquire all the locks needed for such a complex critical section. This implicit acquisition also poses the question of what qualifies as a container. If the mutex keyword is supported on monitors stored inside of other types it can quickly become complex and unclear which monitor should be acquired and when. The extreme example of this is \code{f11} which takes a possibly cyclic graph of pointers to monitors. With such a routine signature the intuition of which monitors will be acquired on entry is lost\cite{Chicken}. Where to draw the lines is up for debate but it seems reasonnable to consider \code{f03} as accepted and \code{f06} as rejected.
    144 
    145 \subsection{Data semantics} \label{data}
     141        int f1(monitor & mutex m);
     142        int f2(const monitor & mutex m);
     143        int f3(monitor ** mutex m);
     144        int f4(monitor *[] mutex m);
     145        int f5(graph(monitor*) & mutex m);
     146\end{lstlisting}
     147
     148The problem is to indentify which object(s) should be acquired. Furthermore we also need to acquire each objects 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 will be acquired. However, adding in arrays (\code{f4}) makes it much harder. Array lengths aren't 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 custom 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).
     149
     150\subsubsection{Data semantics} \label{data}
    146151Once 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}:
    147152\begin{lstlisting}
     
    150155        };
    151156
    152         void ?{}(counter_t & mutex this) {
     157        void ?{}(counter_t & nomutex this) {
    153158                this.cnt = 0;
    154159        }
     
    165170Thread 1 & Thread 2 \\
    166171\begin{lstlisting}
    167         void main(counter_t & mutex c) {
     172        void f(counter_t & mutex c) {
    168173                for(;;) {
    169                         int count = c;
    170                         sout | count | endl;
     174                        sout | (int)c | endl;
    171175                }
    172176        }
    173177\end{lstlisting} &\begin{lstlisting}
    174         void main(counter_t & mutex c) {
     178        void g(counter_t & mutex c) {
    175179                for(;;) {
    176180                        ++c;
     
    194198\end{lstlisting}
    195199
    196 This code acquires both locks before entering the critical section. In practice, writing multi-locking routines that can lead to deadlocks can be very tricky. Having language level support for such feature is therefore a significant asset for \CFA. However, as the this proposal shows, this does have significant repercussions relating to scheduling (see \ref{insched} and \ref{extsched}). The ability to acquire multiple monitors at the same time does incur a significant pitfall even without looking into scheduling. For example :
     200This code acquires both locks before entering the critical section. In practice, writing multi-locking routines that can not lead to deadlocks can be very tricky. Having language level support for such feature is therefore a significant asset for \CFA. However, this does have significant repercussions relating to scheduling (see \ref{insched} and \ref{extsched}). Furthermore, the ability to acquire multiple monitors at the same time does incur a significant pitfall even without looking into scheduling. For example :
    197201\begin{lstlisting}
    198202        void foo(A & mutex a, B & mutex a) {
     
    213217\end{lstlisting}
    214218
    215 TODO: dig further into monitor order aquiring
    216 
    217 Thoughs : calls to \code{baz} and \code{bar} are definitely incompatible because they explicitly acquire locks in reverse order and therefore are explicitly asking for a deadlock. The best that can be done in this situatuin is to detect the deadlock. The case of implicit ordering is less clear because in the case of monitors the runtime system \textit{may} be smart enough to figure out that someone is waiting with explicit ordering... maybe.
    218 
    219 \subsubsection{Internal scheduling} \label{insched}
     219Recursive mutex routine calls are allowed in \CFA but if not done carefully it can lead to nested monitor call problems\cite{Lister77}. These problems 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{bar} but explicit ordering in the case of \code{baz}. This subtle mistake can mean that calling these two functions concurrently will lead to deadlocks, depending on the implicit ordering matching the explicit ordering. As shown on several occasion\cit, there isn't really any solutions to this problem, users simply need to be carefull when acquiring multiple monitors at the same time.
     220
     221\subsubsection{Implementation Details: Interaction with polymorphism}
     222At first glance, interaction between monitors and \CFA's concept of polymorphism seem complexe to support. However, it can be reasoned that entry-point locking can solve most of the issues that could be present with polymorphism.
     223
     224First 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. We must remember that monitors' 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 handle incomplete types (by definition) no \code{dtype} polymorphic routine can access shared data since the data would require knowledge about the type. Therefore the only concern when combining \code{dtype} polymorphism and monitors is to protect access to routines. With callsite-locking, this would require significant amount of work since any \code{dtype} routine could have to obtain some lock before calling a routine. However, with entry-point-locking calling a monitor routine becomes exactly the same as calling it from anywhere else.
     225
     226\subsection{Internal scheduling} \label{insched}
    220227Monitors should also be able to schedule what threads access 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 wait for them to be signaled. Here is a simple example of such a technique :
    221228
     
    236243\end{lstlisting}
    237244
    238 Here routine \code{foo} waits on the \code{signal} from \code{bar} before making further progress, effectively ensuring a basic ordering. This can easily be extended to multi-monitor calls by offering the same guarantee.
     245Here routine \code{foo} waits on 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.
    239246
    240247\begin{center}
     
    263270\end{center}
    264271
    265 A direct extension of the single monitor semantics would be 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. On the technical side, partially releasing lock is feasible but from the user perspective a choice must be made for the syntax of this feature. It is possible to do without any extra syntax by relying on order of acquisition :
     272A direct extension of the single monitor semantics would be 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. On the technical side, partially releasing lock is feasible but from the user perspective a choice must be made for the syntax of this feature. It is possible to do without any extra syntax by relying on order of acquisition (Note that here the use of helper routines is irrelevant, only routines the acquire mutual exclusion have an impact on internal scheduling):
    266273
    267274\begin{center}
     
    270277\hline
    271278\begin{lstlisting}
     279condition e;
     280
    272281void foo(monitor & mutex a,
    273282         monitor & mutex b) {
    274         wait(a.e);
     283        wait(e);
    275284}
    276285
     
    282291foo(a,b);
    283292\end{lstlisting} &\begin{lstlisting}
     293condition e;
     294
    284295void bar(monitor & mutex a,
    285296         monitor & nomutex b) {
     
    289300void foo(monitor & mutex a,
    290301         monitor & mutex b) {
    291         wait(a.e);
     302        wait(e);
    292303}
    293304
    294305bar(a, b);
    295306\end{lstlisting} &\begin{lstlisting}
     307condition e;
     308
    296309void bar(monitor & mutex a,
    297310         monitor & nomutex b) {
     
    301314void baz(monitor & nomutex a,
    302315         monitor & mutex b) {
    303         wait(a.e);
     316        wait(e);
    304317}
    305318
     
    310323
    311324This can be interpreted in two different ways :
     325\begin{flushleft}
    312326\begin{enumerate}
    313         \item \code{wait} atomically releases the monitors \underline{theoretically} acquired by the inner-most mutex routine.
    314         \item \code{wait} atomically releases the monitors \underline{actually} acquired by the inner-most mutex routine.
     327        \item \code{wait} atomically releases the monitors acquired by the inner-most routine, \underline{ignoring} nested calls.
     328        \item \code{wait} atomically releases the monitors acquired by the inner-most routine, \underline{considering} nested calls.
    315329\end{enumerate}
    316 While the difference between these two is subtle, it has a significant impact. In the first case it means that the calls to \code{foo} would behave the same in Context 1 and 2. This semantic would also mean that the call to \code{wait} in routine \code{baz} would only release \code{monitor b}. While this may seem intuitive with these examples, it does have one significant implication, it creates a strong distinction between acquiring multiple monitors in sequence and acquiring the same monitors simulatenously.
     330\end{flushleft}
     331While the difference between these two is subtle, it has a significant impact. In the first case it means that the calls to \code{foo} would behave the same in Context 1 and 2. This semantic would also mean that the call to \code{wait} in routine \code{baz} would only release \code{monitor b}. While this may seem intuitive with these examples, it does have one significant implication, it creates a strong distinction between acquiring multiple monitors in sequence and acquiring the same monitors simulatenously, i.e. :
    317332
    318333\begin{center}
     
    334349\end{center}
    335350
    336 This is not intuitive because even if both methods will display the same monitors state both inside and outside the critical section respectively, the behavior is different. Furthermore, the actual acquiring order will be exaclty the same since acquiring a monitor from inside its mutual exclusion is a no-op. This means that even if the data and the actual control flow are the same using both methods, the behavior of the \code{wait} will be different. The alternative is option 2, that is releasing \underline{actually} acquired monitors. This solves the issue of having the two acquiring method differ at the cost of making routine \code{foo} behave differently depending on from which context it is called (Context 1 or 2). Indeed in Context 2, routine \code{foo} will actually behave like routine \code{baz} rather than having the same behavior than in context 1. The fact that both implicit approaches can be unintuitive depending on the perspective may be a sign that the explicit approach is superior.
     351This is not intuitive because even if both methods display the same monitors state both inside and outside the critical section respectively, the behavior is different. Furthermore, the actual acquiring order will be exaclty the same since acquiring a monitor from inside its mutual exclusion is a no-op. This means that even if the data and the actual control flow are the same using both methods, the behavior of the \code{wait} will be different. The alternative is option 2, that is releasing acquired monitors, \underline{considering} nesting. This solves the issue of having the two acquiring method differ at the cost of making routine \code{foo} behave differently depending on from which context it is called (Context 1 or 2). Indeed in Context 2, routine \code{foo} actually behaves like routine \code{baz} rather than having the same behavior than in Context 1. The fact that both implicit approaches can be unintuitive depending on the perspective may be a sign that the explicit approach is superior. For this reason this \CFA does not support implicit monitor releasing and uses explicit semantics.
    337352\\
    338353
     
    411426\\
    412427
    413 All these cases have there pros and cons. Case 1 is more distinct because it means programmers need to be carefull about where the condition was initialized as well as where it is used. On the other hand, it is very clear and explicit which monitor will be released and which monitor will stay acquired. This is similar to Case 2, which releases only the monitors explictly listed. However, in Case 2, calling the \code{wait} routine instead of the \code{waitRelease} routine will release all the acquired monitor. The Case 3 is an improvement on that since it releases all the monitors except those specified. The result is that the \code{wait} routine can be written as follows :
     428All these cases have their pros and cons. Case 1 is more distinct because it means programmers need to be carefull about where the condition is initialized as well as where it is used. On the other hand, it is very clear and explicitly states which monitor is released and which monitor stays acquired. This is similar to Case 2, which releases only the monitors explictly listed. However, in Case 2, calling the \code{wait} routine instead of the \code{waitRelease} routine releases all the acquired monitor. The Case 3 is an improvement on that since it releases all the monitors except those specified. The result is that the \code{wait} routine can be written as follows :
    414429\begin{lstlisting}
    415430void wait(condition & cond) {
     
    419434This alternative offers nice and consistent behavior between \code{wait} and \code{waitHold}. However, one large pitfall is that mutual exclusion can now be violated by calls to library code. Indeed, even if the following example seems benign there is one significant problem :
    420435\begin{lstlisting}
    421 extern void doStuff();
     436monitor global;
     437
     438extern void doStuff(); //uses global
    422439
    423440void foo(monitor & mutex m) {
     
    426443        //...
    427444}
    428 \end{lstlisting}
    429 
    430 Indeed, if Case 2 or 3 are chosen it any code can violate the mutual exclusion of calling code by issuing calls to \code{wait} or \code{waitHold} in a nested monitor context. Case 2 can be salvaged by removing the \code{wait} routine from the API but Case 3 cannot prevent users from calling \code{waitHold(someCondition, [])}. For this reason the syntax proposed in Case 3 is rejected. Note that syntaxes proposed in case 1 and 2 are not exclusive. Indeed, by supporting two types of condition as follows both cases can be supported :
     445
     446foo(global);
     447\end{lstlisting}
     448
     449Indeed, if Case 2 or 3 are chosen it any code can violate the mutual exclusion of the calling code by issuing calls to \code{wait} or \code{waitHold} in a nested monitor context. Case 2 can be salvaged by removing the \code{wait} routine from the API but Case 3 cannot prevent users from calling \code{waitHold(someCondition, [])}. For this reason the syntax proposed in Case 3 is rejected. Note that the syntax proposed in case 1 and 2 are not exclusive. Indeed, by supporting two types of condition both cases can be supported :
    431450\begin{lstlisting}
    432451struct condition { /*...*/ };
     
    443462\end{lstlisting}
    444463
    445 Regardless of the option chosen for wait semantics, signal must be symmetrical. 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) than the call to \code{wait}. Otherwise, mutual exclusion cannot be properly transferred back to the waiting monitor.
     464Regardless of the option chosen for wait semantics, signal must be symmetrical. 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.
    446465
    447466Finally, an additionnal semantic which can be very usefull is the \code{signalBlock} 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.
     467\\
    448468
    449469\subsection{External scheduling} \label{extsched}
    450 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 demontrate, 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 (see \uC) or in terms of data (see 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 reset of the languages semantics. Two challenges specific to \CFA arise when trying to add external scheduling which is 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.
     470As 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.
    451471
    452472\begin{center}
     
    458478                condition c;
    459479        public:
    460                 void f();
    461                 void g() { signal}
    462                 void h() { wait(c); }
     480                void f() { signal(c)}
     481                void g() { wait(c); }
    463482        private:
    464483        }
     
    468487        public:
    469488                void f();
    470                 void g();
    471                 void h() { _Accept(g); }
     489                void g() { _Accept(f); }
    472490        private:
    473491        }
     
    477495
    478496In 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.
     497\\
    479498
    480499\subsubsection{Loose object definitions}
    481 In \uC monitor definitions include an exhaustive list of monitor operations. Since \CFA is not an object oriented it becomes much more difficult to implement but also much less clear for the user :
     500In \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 :
    482501
    483502\begin{lstlisting}
     
    485504
    486505        void f(A & mutex a);
    487         void g(A & mutex a);
    488         void h(A & mutex a) { accept(g); }
    489 \end{lstlisting}
    490 
    491 While this is the direct translation of the \uC code, at the time of compiling routine \code{f} the \CFA does not already have a declaration of \code{g} while the \uC compiler does. This means that either the compiler has to dynamically find which routines are "acceptable" or the language needs a way of statically listing "acceptable" routines. Since \CFA has no existing concept that resemble dynamic routine definitions or pattern matching, the static approach seems the more consistent with the current language paradigms. This approach leads to the \uC example being translated to :
    492 \begin{lstlisting}
    493         accept( void g(mutex struct A & mutex a) )
    494         mutex struct A {};
    495 
    496         void f(A & mutex a) { accept(g); }
    497         void g(A & mutex a);
    498 \end{lstlisting}
    499 
    500 This syntax is the most consistent with the language since it somewhat mimics the \code{forall} declarations. However, the fact that it comes before the struct declaration does means the type needs to be forward declared (done inline in the example). Here are a few alternatives to this syntax : \\
    501 \begin{tabular}[t]{l l}
     506        void g(A & mutex a) { accept(f); }
     507\end{lstlisting}
     508
     509However, 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 :
     510
     511\begin{center}
     512\begin{tabular}{l}
     513\begin{lstlisting}[language=Pseudo]
     514        if monitor is free :
     515                enter
     516        elif monitor accepts me :
     517                enter
     518        else :
     519                block
     520\end{lstlisting}
     521\end{tabular}
     522\end{center}
     523
     524For 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 :
     525
     526\begin{center}
     527{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
     528\end{center}
     529
     530There 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.
     531The alternative would be to have a picture more like this one:
     532
     533\begin{center}
     534{\resizebox{0.4\textwidth}{!}{\input{ext_monitor}}}
     535\end{center}
     536
     537Not 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.
     538
     539At 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.
     540
     541In either cases here are a few alternatives for the different syntaxes this syntax : \\
     542\begin{center}
     543{\renewcommand{\arraystretch}{1.5}
     544\begin{tabular}[t]{l @{\hskip 0.35in} l}
     545\hline
     546\multicolumn{2}{ c }{\code{accept} on type}\\
     547\hline
    502548Alternative 1 & Alternative 2 \\
    503549\begin{lstlisting}
    504550mutex struct A
    505 accept( void g(A & mutex a) )
     551accept( void f(A & mutex a) )
    506552{};
    507553\end{lstlisting} &\begin{lstlisting}
    508554mutex struct A {}
    509 accept( void g(A & mutex a) );
     555accept( void f(A & mutex a) );
    510556
    511557\end{lstlisting} \\
     
    513559\begin{lstlisting}
    514560mutex struct A {
    515         accept( void g(A & mutex a) )
     561        accept( void f(A & mutex a) )
    516562};
    517563
     
    519565mutex struct A {
    520566        accept :
    521                 void g(A & mutex a) );
     567                void f(A & mutex a) );
    522568};
    523 \end{lstlisting}
     569\end{lstlisting}\\
     570\hline
     571\multicolumn{2}{ c }{\code{accept} on routine}\\
     572\hline
     573\begin{lstlisting}
     574mutex struct A {};
     575
     576void f(A & mutex a)
     577
     578accept( void f(A & mutex a) )
     579void g(A & mutex a) {
     580        /*...*/
     581}
     582\end{lstlisting}&\\
    524583\end{tabular}
    525 
     584}
     585\end{center}
    526586
    527587An 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.
     
    554614\end{lstlisting}
    555615
    556 This is unambiguous. The 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.
     616This 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.
    557617
    558618\begin{lstlisting}
     
    569629Note 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.
    570630
    571 \subsection{Implementation Details}
    572 \textbf{\large{Work in progress...}}
    573 \subsubsection{Interaction with polymorphism}
    574 At first glance, interaction between monitors and \CFA's concept of polymorphism seem complexe to support. However, it can be reasoned that entry-point locking can solve most of the issues that could be present with polymorphism.
    575 
    576 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. We must remember that monitors' 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 handle incomplete types (by definition) no \code{dtype} polymorphic routine can access shared data since the data would require knowledge about the type. Therefore the only concern when combining \code{dtype} polymorphism and monitors is to protect access to routines. With callsite-locking, this would require significant amount of work since any \code{dtype} routine could have to obtain some lock before calling a routine. However, with entry-point-locking calling a monitor routine becomes exactly the same as calling it from anywhere else.
    577 
    578 \subsubsection{External scheduling queues}
    579 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 most 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 gut that is a reasonnable contraint. This algorithm choice has two consequences, the ofthe 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 probably that half the multi-monitor queues will go unused for the entire duration of the program.
     631\subsubsection{Implementation Details: External scheduling queues}
     632To 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.
    580633
    581634\subsection{Other concurrency tools}
    582 
     635TO BE CONTINUED...
     636
     637\newpage
    583638\section{Parallelism}
    584 Historically, computer performance was about processor speeds and instructions count. However, with heat dissipaction being an ever growing challenge, parallelism has become the new source of greatest performance \cite{Sutter05, Sutter05b}. In this decade, it is not longer reasonnable create high-performance application without caring about parallelism. Indeed, parallelism an important aspect of performance and more specifically throughput and hardware utilization. The lowest level approach parallelism is to use \glspl{kthread}. 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 which all have strengths and weaknesses.
     639Historically, computer performance was about processor speeds and instructions count. However, with heat dissipation being an ever growing challenge, parallelism has become the new source of greatest 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}. 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 which all have strengths and weaknesses.
    585640
    586641\subsection{User-level threads}
     
    590645
    591646\subsection{Jobs and thread pools}
    592 The opposite approach is to base parallelism on \glspl{job}. Indeed, \glspl{job} offer limited flexibility but at the benefit of a simpler user interface. In \gls{job} based systems users express parallelism as units of work and the dependency graph (either explicit or implicit) that tie them together. This means users need not to worry about concurrency but significantly limits the interaction that can occur between different jobs. Indeed, any \gls{job} that blocks also blocks the underlying \gls{kthread}, this effectively mean the CPU utilization, and therefore throughput, will suffer noticeably. The golden standard of this implementation is Intel's TBB library\cite{TBB}.
     647The approach on the opposite end of the spectrum is to base parallelism on \glspl{job}. Indeed, \glspl{job} offer limited flexibility but at the benefit of a simpler user interface. In \gls{job} based systems users express parallelism as units of work and the dependency graph (either explicit or implicit) that tie them together. This means users need not to worry about concurrency but significantly limits the interaction that can occur between different jobs. Indeed, any \gls{job} that blocks also blocks the underlying \gls{kthread}, this effectively mean the CPU utilization, and therefore throughput, will suffer noticeably.
     648The golden standard of this implementation is Intel's TBB library\cite{TBB}.
    593649
    594650\subsection{Fibers : user-level threads without preemption}
    595651Finally, in the middle of the flexibility versus complexity spectrum lay \glspl{fiber} which offer \glspl{uthread} without the complexity of preemption. This means users don't have to worry about other \glspl{fiber} suddenly executing between two instructions which signficantly reduces complexity. However, any call to IO or other concurrency primitives can lead to context switches. Furthermore, users can also block \glspl{fiber} in the middle of their execution without blocking a full processor core. This means users still have to worry about mutual exclusion, deadlocks and race conditions in their code, raising the complexity significantly.
    596 \cite{Go}
     652An example of a language that uses fibers is Go\cite{Go}
    597653
    598654\subsection{Paradigm performance}
    599 While the choice between the three paradigms listed above can have significant performance implication, it is difficult to pin the performance implications of chosing a model at the language level. Indeed, in many situations own of these paradigms will show better performance but it all depends on the usage.
    600 Having mostly indepent units of work to execute almost guarantess that the \gls{job} based system will have the best performance. However, add interactions between jobs and the processor utilisation might suffer. User-level threads may allow maximum ressource 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.
    601 
    602 \section{Parallelism in \CFA}
    603 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.
    604 
    605 \subsection{Kernel core}\label{kernel}
    606 At the ro
    607 \subsubsection{Threads}
    608 \CFA threads have all the caracteristiques of
    609 
    610 \subsection{High-level options}\label{tasks}
    611 
    612 \subsubsection{Thread interface}
    613 constructors destructors
    614         initializer lists
    615 monitors
    616 
    617 \subsubsection{Futures}
    618 
    619 \subsubsection{Implicit threading}
    620 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.
    621 
    622 \begin{center}
    623 \begin{tabular}[t]{|c|c|c|}
    624 Sequential & System Parallel & Language Parallel \\
    625 \begin{lstlisting}
    626 void big_sum(int* a, int* b,
    627                  int* out,
    628                  size_t length)
    629 {
    630         for(int i = 0; i < length; ++i ) {
    631                 out[i] = a[i] + b[i];
    632         }
    633 }
    634 
    635 
    636 
    637 
    638 
    639 int* a[10000];
    640 int* b[10000];
    641 int* c[10000];
    642 //... fill in a and b ...
    643 big_sum(a, b, c, 10000);
    644 \end{lstlisting} &\begin{lstlisting}
    645 void big_sum(int* a, int* b,
    646                  int* out,
    647                  size_t length)
    648 {
    649         range ar(a, a + length);
    650         range br(b, b + length);
    651         range or(out, out + length);
    652         parfor( ai, bi, oi,
    653         [](int* ai, int* bi, int* oi) {
    654                 oi = ai + bi;
    655         });
    656 }
    657 
    658 int* a[10000];
    659 int* b[10000];
    660 int* c[10000];
    661 //... fill in a and b ...
    662 big_sum(a, b, c, 10000);
    663 \end{lstlisting}&\begin{lstlisting}
    664 void big_sum(int* a, int* b,
    665                  int* out,
    666                  size_t length)
    667 {
    668         for (ai, bi, oi) in (a, b, out) {
    669                 oi = ai + bi;
    670         }
    671 }
    672 
    673 
    674 
    675 
    676 
    677 int* a[10000];
    678 int* b[10000];
    679 int* c[10000];
    680 //... fill in a and b ...
    681 big_sum(a, b, c, 10000);
    682 \end{lstlisting}
     655While the choice between the three paradigms listed above may have significant performance implication, it is difficult to pin the performance implications of chosing a model at the language level. Indeed, in many situations one of these paradigms will show better performance but it all strongly depends on the usage. Having mostly indepent units of work to execute almost guarantess that the \gls{job} based system will have the best performance. However, add interactions between jobs and the processor utilisation might suffer. User-level threads may allow maximum ressource 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.
     656
     657\section{\CFA 's Thread Building Blocks}
     658As 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 :
     659\begin{center}
     660\begin{tabular}[t]{| r | c | c |}
     661\cline{2-3}
     662\multicolumn{1}{ c| }{} & Has a stack & Preemptive \\
     663\hline
     664\Glspl{job} & X & X \\
     665\hline
     666\Glspl{fiber} & \checkmark & X \\
     667\hline
     668\Glspl{uthread} & \checkmark & \checkmark \\
     669\hline
    683670\end{tabular}
    684671\end{center}
    685672
    686 \subsection{Machine setup}\label{machine}
    687 Threads are all good and well but wee still some OS support to fully utilize available hardware.
    688 
    689 \textbf{\large{Work in progress...}} Do wee need something beyond specifying the number of kernel threads?
     673As shown in section \ref{cfaparadigms} these different blocks being available in \CFA it is trivial to reproduce any of these paradigm.
     674
     675\subsection{Thread Interface}
     676The 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 prefix with the \code{thread} as follows :
     677
     678\begin{lstlisting}
     679        thread struct foo {};
     680\end{lstlisting}
     681
     682Obviously, 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, we consider that statically tying a \code{main} routine to a thread superseeds this approach. Since the \code{main} routine is definetely a special routine in \CFA, we can reuse the existing syntax for declaring routines with unordinary name, i.e. operator overloading. As such the \code{main} routine of a thread can be defined as such :
     683\begin{lstlisting}
     684        thread struct foo {};
     685
     686        void ?main(thread foo* this) {
     687                /*... Some useful code ...*/
     688        }
     689\end{lstlisting}
     690
     691With these semantics it is trivial to write a thread type that takes a function pointer as parameter and executes it on its stack asynchronously :
     692\begin{lstlisting}
     693        typedef void (*voidFunc)(void);
     694
     695        thread struct FuncRunner {
     696                voidFunc func;
     697        };
     698
     699        //ctor
     700        void ?{}(thread FuncRunner* this, voidFunc inFunc) {
     701                func = inFunc;
     702        }
     703
     704        //main
     705        void ?main(thread FuncRunner* this) {
     706                this->func();
     707        }
     708\end{lstlisting}
     709
     710% In this example \code{func} is a function pointer stored in \acrfull{tls}, which is \CFA is both easy to use and completly typesafe.
     711
     712Of 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.
     713\begin{lstlisting}
     714thread struct FuncRunner; //FuncRunner declared above
     715
     716void world() {
     717        sout | "World!" | endl;
     718}
     719
     720void main() {
     721        FuncRunner run = {world};
     722        //Thread run forks here
     723
     724        //Print to "Hello " and "World!" will be run concurrently
     725        sout | "Hello " | endl;
     726
     727        //Implicit join at end of scope
     728}
     729\end{lstlisting}
     730This semantic has several advantages over explicit semantics : typesafety is guaranteed, any thread will always be started and stopped exaclty once and users can't make any progamming errors. Furthermore it naturally follows the memory allocation semantics which means users don't need to learn multiple semantics.
     731
     732These semantics also naturally scale to multiple threads meaning basic synchronisation is very simple :
     733\begin{lstlisting}
     734        thread struct MyThread {
     735                //...
     736        };
     737
     738        //ctor
     739        void ?{}(thread MyThread* this) {}
     740
     741        //main
     742        void ?main(thread MyThread* this) {
     743                //...
     744        }
     745
     746        void foo() {
     747                MyThread thrds[10];
     748                //Start 10 threads at the beginning of the scope
     749
     750                DoStuff();
     751
     752                //Wait for the 10 threads to finish
     753        }
     754\end{lstlisting}
     755
     756\newpage
     757\large{\textbf{WORK IN PROGRESS}}
     758\subsection{The \CFA Kernel : Processors, Clusters and Threads}\label{kernel}
     759
     760
     761\subsection{Paradigms}\label{cfaparadigms}
     762Given 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.
     763
     764% \subsection{High-level options}\label{tasks}
     765%
     766% \subsubsection{Thread interface}
     767% constructors destructors
     768%       initializer lists
     769% monitors
     770%
     771% \subsubsection{Futures}
     772%
     773% \subsubsection{Implicit threading}
     774% 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.
     775%
     776% \begin{center}
     777% \begin{tabular}[t]{|c|c|c|}
     778% Sequential & System Parallel & Language Parallel \\
     779% \begin{lstlisting}
     780% void big_sum(int* a, int* b,
     781%                int* out,
     782%                size_t length)
     783% {
     784%       for(int i = 0; i < length; ++i ) {
     785%               out[i] = a[i] + b[i];
     786%       }
     787% }
     788%
     789%
     790%
     791%
     792%
     793% int* a[10000];
     794% int* b[10000];
     795% int* c[10000];
     796% //... fill in a and b ...
     797% big_sum(a, b, c, 10000);
     798% \end{lstlisting} &\begin{lstlisting}
     799% void big_sum(int* a, int* b,
     800%                int* out,
     801%                size_t length)
     802% {
     803%       range ar(a, a + length);
     804%       range br(b, b + length);
     805%       range or(out, out + length);
     806%       parfor( ai, bi, oi,
     807%       [](int* ai, int* bi, int* oi) {
     808%               oi = ai + bi;
     809%       });
     810% }
     811%
     812% int* a[10000];
     813% int* b[10000];
     814% int* c[10000];
     815% //... fill in a and b ...
     816% big_sum(a, b, c, 10000);
     817% \end{lstlisting}&\begin{lstlisting}
     818% void big_sum(int* a, int* b,
     819%                int* out,
     820%                size_t length)
     821% {
     822%       for (ai, bi, oi) in (a, b, out) {
     823%               oi = ai + bi;
     824%       }
     825% }
     826%
     827%
     828%
     829%
     830%
     831% int* a[10000];
     832% int* b[10000];
     833% int* c[10000];
     834% //... fill in a and b ...
     835% big_sum(a, b, c, 10000);
     836% \end{lstlisting}
     837% \end{tabular}
     838% \end{center}
     839%
     840% \subsection{Machine setup}\label{machine}
     841% Threads are all good and well but wee still some OS support to fully utilize available hardware.
     842%
     843% \textbf{\large{Work in progress...}} Do wee need something beyond specifying the number of kernel threads?
     844
     845\section{Putting it all together}
    690846
    691847\section{Future work}
     
    696852
    697853\clearpage
     854\printglossary[type=\acronymtype]
    698855\printglossary
    699856
Note: See TracChangeset for help on using the changeset viewer.