source: doc/proposals/concurrency/concurrency.tex @ a9aab60

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerresolv-newwith_gc
Last change on this file since a9aab60 was a9aab60, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

some progress on parallelism

  • Property mode set to 100644
File size: 40.3 KB
Line 
1% requires tex packages: texlive-base texlive-latex-base tex-common texlive-humanities texlive-latex-extra texlive-fonts-recommended
2
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-^
9% math escape $...$ (dollar symbol)
10
11\documentclass[twoside,11pt]{article}
12
13%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
14
15% Latex packages used in the document.
16\usepackage[T1]{fontenc}                                % allow Latin1 (extended ASCII) characters
17\usepackage{textcomp}
18\usepackage[latin1]{inputenc}
19\usepackage{fullpage,times,comment}
20\usepackage{epic,eepic}
21\usepackage{upquote}                                                                    % switch curled `'" to straight
22\usepackage{calc}
23\usepackage{xspace}
24\usepackage{graphicx}
25\usepackage{tabularx}
26\usepackage[acronym]{glossaries}
27\usepackage{varioref}                                                           % extended references
28\usepackage{inconsolata}
29\usepackage{listings}                                                                   % format program code
30\usepackage[flushmargin]{footmisc}                                              % support label/reference in footnote
31\usepackage{latexsym}                                   % \Box glyph
32\usepackage{mathptmx}                                   % better math font with "times"
33\usepackage[usenames]{color}
34\usepackage[pagewise]{lineno}
35\renewcommand{\linenumberfont}{\scriptsize\sffamily}
36\input{common}                                          % bespoke macros used in the document
37\usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
38\usepackage{breakurl}
39
40\usepackage{tikz}
41\def\checkmark{\tikz\fill[scale=0.4](0,.35) -- (.25,0) -- (1,.7) -- (.25,.15) -- cycle;}
42
43\renewcommand{\UrlFont}{\small\sf}
44
45\setlength{\topmargin}{-0.45in}                                                 % move running title into header
46\setlength{\headsep}{0.25in}
47
48%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
49
50% Names used in the document.
51
52\newcommand{\Version}{1.0.0}
53\newcommand{\CS}{C\raisebox{-0.9ex}{\large$^\sharp$}\xspace}
54
55\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
56\newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}}
57\newcommand{\R}[1]{\Textbf{#1}}
58\newcommand{\B}[1]{{\Textbf[blue]{#1}}}
59\newcommand{\G}[1]{{\Textbf[OliveGreen]{#1}}}
60\newcommand{\uC}{$\mu$\CC}
61\newcommand{\cit}{\textsuperscript{[Citation Needed]}\xspace}
62\newcommand{\code}[1]{\lstinline{#1}}
63
64\input{glossary}
65
66\newsavebox{\LstBox}
67
68%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
69
70\setcounter{secnumdepth}{3}                             % number subsubsections
71\setcounter{tocdepth}{3}                                % subsubsections in table of contents
72\makeindex
73
74%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
75
76\begin{document}
77% \linenumbers
78
79\title{Concurrency in \CFA}
80\author{Thierry Delisle \\
81Dept. of Computer Science, University of Waterloo, \\ Waterloo, Ontario, Canada
82}
83
84\maketitle
85\section{Introduction}
86This 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.
87Indeed, for higly productive parallel programming high-level approaches are much more popular\cite{HPP:Study}. Examples are task based parallelism, message passing, implicit threading.
88
89There 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.
90
91\section{Concurrency}
92Several 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.
93
94Finally, 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.
95
96\section{Monitors}
97A 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 :
98\begin{lstlisting}
99        typedef /*some monitor type*/ monitor;
100        int f(monitor & m);
101
102        int main() {
103                monitor m;
104                f(m);
105        }
106\end{lstlisting}
107
108\subsection{Call semantics} \label{call}
109The 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.
110
111Another 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 :
112
113\begin{lstlisting}
114        mutex struct counter_t { /*...*/ };
115
116        void ?{}(counter_t & mutex this);
117        int ++?(counter_t & mutex this);
118        void ?{}(int * this, counter_t & mutex cnt);
119
120        bool is_zero(counter_t & nomutex this) {
121                int val = this;
122                return val == 0;
123        }
124\end{lstlisting}
125*semantics of the declaration of \code{mutex struct counter_t} will be discussed in details in \ref{data}
126
127This 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} ).
128
129Having 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.
130
131Regardless of which keyword is kept, it is important to establish when mutex/nomutex may be used depending on type parameters.
132\begin{lstlisting}
133        int f01(monitor & mutex m);
134        int f02(const monitor & mutex m);
135        int f03(monitor * mutex m);
136        int f04(monitor * mutex * m);
137        int f05(monitor ** mutex m);
138        int f06(monitor[10] mutex m);
139        int f07(monitor[] mutex m);
140        int f08(vector(monitor) & mutex m);
141        int f09(list(monitor) & mutex m);
142        int f10([monitor*, int] & mutex m);
143        int f11(graph(monitor*) & mutex m);
144\end{lstlisting}
145
146For 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.
147
148\subsection{Data semantics} \label{data}
149Once 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}:
150\begin{lstlisting}
151        mutex struct counter_t {
152                int value;
153        };
154
155        void ?{}(counter_t & mutex this) {
156                this.cnt = 0;
157        }
158
159        int ++?(counter_t & mutex this) {
160                return ++this->value;
161        }
162
163        void ?{}(int * this, counter_t & mutex cnt) {
164                *this = (int)cnt;
165        }
166\end{lstlisting}
167\begin{tabular}{ c c }
168Thread 1 & Thread 2 \\
169\begin{lstlisting}
170        void main(counter_t & mutex c) {
171                for(;;) {
172                        int count = c;
173                        sout | count | endl;
174                }
175        }
176\end{lstlisting} &\begin{lstlisting}
177        void main(counter_t & mutex c) {
178                for(;;) {
179                        ++c;
180                }
181        }
182
183\end{lstlisting}
184\end{tabular}
185\\
186
187
188This 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. \\
189
190These simple mutual exclusion semantics also naturally expand to multi-monitor calls.
191\begin{lstlisting}
192        int f(MonitorA & mutex a, MonitorB & mutex b);
193
194        MonitorA a;
195        MonitorB b;
196        f(a,b);
197\end{lstlisting}
198
199This 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 :
200\begin{lstlisting}
201        void foo(A & mutex a, B & mutex a) {
202                //...
203        }
204
205        void bar(A & mutex a, B & nomutex a)
206                //...
207                foo(a, b);
208                //...
209        }
210
211        void baz(A & nomutex a, B & mutex a)
212                //...
213                foo(a, b);
214                //...
215        }
216\end{lstlisting}
217
218TODO: dig further into monitor order aquiring
219
220Thoughs : 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.
221
222\subsubsection{Internal scheduling} \label{insched}
223Monitors 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 :
224
225\begin{lstlisting}
226        mutex struct A {
227                condition e;
228        }
229
230        void foo(A & mutex a) {
231                //...
232                wait(a.e);
233                //...
234        }
235
236        void bar(A & mutex a) {
237                signal(a.e);
238        }
239\end{lstlisting}
240
241Here 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.
242
243\begin{center}
244\begin{tabular}{ c @{\hskip 0.65in} c }
245Thread 1 & Thread 2 \\
246\begin{lstlisting}
247void foo(monitor & mutex a,
248         monitor & mutex b) {
249        //...
250        wait(a.e);
251        //...
252}
253
254foo(a, b);
255\end{lstlisting} &\begin{lstlisting}
256void bar(monitor & mutex a,
257         monitor & mutex b) {
258        signal(a.e);
259}
260
261
262
263bar(a, b);
264\end{lstlisting}
265\end{tabular}
266\end{center}
267
268A 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 :
269
270\begin{center}
271\begin{tabular}{|c|c|c|}
272Context 1 & Context 2 & Context 3 \\
273\hline
274\begin{lstlisting}
275void foo(monitor & mutex a,
276         monitor & mutex b) {
277        wait(a.e);
278}
279
280
281
282
283
284
285foo(a,b);
286\end{lstlisting} &\begin{lstlisting}
287void bar(monitor & mutex a,
288         monitor & nomutex b) {
289        foo(a,b);
290}
291
292void foo(monitor & mutex a,
293         monitor & mutex b) {
294        wait(a.e);
295}
296
297bar(a, b);
298\end{lstlisting} &\begin{lstlisting}
299void bar(monitor & mutex a,
300         monitor & nomutex b) {
301        foo(a,b);
302}
303
304void baz(monitor & nomutex a,
305         monitor & mutex b) {
306        wait(a.e);
307}
308
309bar(a, b);
310\end{lstlisting}
311\end{tabular}
312\end{center}
313
314This can be interpreted in two different ways :
315\begin{enumerate}
316        \item \code{wait} atomically releases the monitors \underline{theoretically} acquired by the inner-most mutex routine.
317        \item \code{wait} atomically releases the monitors \underline{actually} acquired by the inner-most mutex routine.
318\end{enumerate}
319While 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.
320
321\begin{center}
322\begin{tabular}{c @{\hskip 0.35in} c @{\hskip 0.35in} c}
323\begin{lstlisting}
324enterMonitor(a);
325enterMonitor(b);
326// do stuff
327leaveMonitor(b);
328leaveMonitor(a);
329\end{lstlisting} & != &\begin{lstlisting}
330enterMonitor(a);
331enterMonitor(a, b);
332// do stuff
333leaveMonitor(a, b);
334leaveMonitor(a);
335\end{lstlisting}
336\end{tabular}
337\end{center}
338
339This 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.
340\\
341
342The following examples shows three alternatives of explicit wait semantics :
343\\
344
345\begin{center}
346\begin{tabular}{|c|c|c|}
347Case 1 & Case 2 & Case 3 \\
348Branding on construction & Explicit release list & Explicit ignore list \\
349\hline
350\begin{lstlisting}
351void foo(monitor & mutex a,
352         monitor & mutex b,
353           condition & c)
354{
355        // Releases monitors
356        // branded in ctor
357        wait(c);
358}
359
360monitor a;
361monitor b;
362condition1 c1 = {a};
363condition2 c2 = {a, b};
364
365//Will release only a
366foo(a,b,c1);
367
368//Will release a and b
369foo(a,b,c2);
370\end{lstlisting} &\begin{lstlisting}
371void foo(monitor & mutex a,
372         monitor & mutex b,
373           condition & c)
374{
375        // Releases monitor a
376        // Holds monitor b
377        waitRelease(c, [a]);
378}
379
380monitor a;
381monitor b;
382condition c;
383
384
385
386foo(a,b,c);
387
388
389
390\end{lstlisting} &\begin{lstlisting}
391void foo(monitor & mutex a,
392         monitor & mutex b,
393           condition & c)
394{
395        // Releases monitor a
396        // Holds monitor b
397        waitHold(c, [b]);
398}
399
400monitor a;
401monitor b;
402condition c;
403
404
405
406foo(a,b,c);
407
408
409
410\end{lstlisting}
411\end{tabular}
412\end{center}
413(Note : Case 2 and 3 use tuple semantics to pass a variable length list of elements.)
414\\
415
416All 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 :
417\begin{lstlisting}
418void wait(condition & cond) {
419        waitHold(cond, []);
420}
421\end{lstlisting}
422This 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 :
423\begin{lstlisting}
424extern void doStuff();
425
426void foo(monitor & mutex m) {
427        //...
428        doStuff(); //warning can release monitor m
429        //...
430}
431\end{lstlisting}
432
433Indeed, 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 :
434\begin{lstlisting}
435struct condition { /*...*/ };
436
437// Second argument is a variable length tuple.
438void wait(condition & cond, [...] monitorsToRelease);
439void signal(condition & cond);
440
441struct conditionN { /*...*/ };
442
443void ?{}(conditionN* this, /*list of N monitors to release*/);
444void wait(conditionN & cond);
445void signal(conditionN & cond);
446\end{lstlisting}
447
448Regardless 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.
449
450Finally, 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.
451
452\subsection{External scheduling} \label{extsched}
453As 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.
454
455\begin{center}
456\begin{tabular}{|c|c|}
457Internal Scheduling & External Scheduling \\
458\hline
459\begin{lstlisting}
460        _Monitor blarg {
461                condition c;
462        public:
463                void f();
464                void g() { signal}
465                void h() { wait(c); }
466        private:
467        }
468\end{lstlisting}&\begin{lstlisting}
469        _Monitor blarg {
470
471        public:
472                void f();
473                void g();
474                void h() { _Accept(g); }
475        private:
476        }
477\end{lstlisting}
478\end{tabular}
479\end{center}
480
481In 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.
482
483\subsubsection{Loose object definitions}
484In \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 :
485
486\begin{lstlisting}
487        mutex struct A {};
488
489        void f(A & mutex a);
490        void g(A & mutex a);
491        void h(A & mutex a) { accept(g); }
492\end{lstlisting}
493
494While 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 :
495\begin{lstlisting}
496        accept( void g(mutex struct A & mutex a) )
497        mutex struct A {};
498
499        void f(A & mutex a) { accept(g); }
500        void g(A & mutex a);
501\end{lstlisting}
502
503This 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 : \\
504\begin{tabular}[t]{l l}
505Alternative 1 & Alternative 2 \\
506\begin{lstlisting}
507mutex struct A
508accept( void g(A & mutex a) )
509{};
510\end{lstlisting} &\begin{lstlisting}
511mutex struct A {}
512accept( void g(A & mutex a) );
513
514\end{lstlisting} \\
515Alternative 3 & Alternative 4 \\
516\begin{lstlisting}
517mutex struct A {
518        accept( void g(A & mutex a) )
519};
520
521\end{lstlisting} &\begin{lstlisting}
522mutex struct A {
523        accept :
524                void g(A & mutex a) );
525};
526\end{lstlisting}
527\end{tabular}
528
529
530An 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.
531
532\subsubsection{Multi-monitor scheduling}
533
534External 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 :
535\begin{lstlisting}
536        accept( void f(mutex struct A & mutex this))
537        mutex struct A {};
538
539        mutex struct B {};
540
541        void g(A & mutex a, B & mutex b) {
542                accept(f); //ambiguous, which monitor
543        }
544\end{lstlisting}
545
546The obvious solution is to specify the correct monitor as follows :
547
548\begin{lstlisting}
549        accept( void f(mutex struct A & mutex this))
550        mutex struct A {};
551
552        mutex struct B {};
553
554        void g(A & mutex a, B & mutex b) {
555                accept( f, b );
556        }
557\end{lstlisting}
558
559This 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.
560
561\begin{lstlisting}
562        accept( void f(mutex struct A & mutex, mutex struct A & mutex))
563        mutex struct A {};
564
565        mutex struct B {};
566
567        void g(A & mutex a, B & mutex b) {
568                accept( f, b, a );
569        }
570\end{lstlisting}
571
572Note 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.
573
574\subsection{Implementation Details}
575\textbf{\large{Work in progress...}}
576\subsubsection{Interaction with polymorphism}
577At 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.
578
579First 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.
580
581\subsubsection{External scheduling queues}
582To 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.
583
584\subsection{Other concurrency tools}
585
586\section{Parallelism}
587Historically, 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.
588
589\subsection{User-level threads}
590A 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 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 complexities are hidden, users still have to think about data races, deadlocks and synchronization issues. This can be somewhat alleviated by a concurrency toolkit with strong garantees but the parallelism toolkit offers very little to reduce complexity in itself.
591
592Examples of languages that support are Java\cite{Java}, Haskell\cite{Haskell} and \uC\cite{uC++book}.
593
594\subsection{Jobs and thread pools}
595The 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}.
596
597\subsection{Fibers : user-level threads without preemption}
598Finally, 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.
599\cite{Go}
600
601\subsection{Paradigm performance}
602While 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 own 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 fully armoticised by the actual work done.
603
604\section{\CFA 's Thread Building Blocks}
605As 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 :
606\begin{center}
607\begin{tabular}[t]{| r | c | c |}
608\cline{2-3}
609\multicolumn{1}{ c| }{} & Has a stack & Preemptive \\
610\hline
611\Glspl{job} & X & X \\
612\hline
613\Glspl{fiber} & \checkmark & X \\
614\hline
615\Glspl{uthread} & \checkmark & \checkmark \\
616\hline
617\end{tabular}
618\end{center}
619
620As shown in section \ref{cfaparadigms} these different blocks being available in \CFA it is trivial to reproduce any of these paradigm.
621
622\subsection{Thread Interface}
623The 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 :
624
625\begin{lstlisting}
626        thread struct foo {};
627\end{lstlisting}
628
629Obviously, 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 function 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 :
630\begin{lstlisting}
631        thread struct foo {};
632
633        void ?main(thread foo* this) {
634                /*... Some useful code ...*/
635        }
636\end{lstlisting}
637
638With these semantics it is trivial to write a thread type that takes a function pointer as parameter and executes it on its stack asynchronously :
639\begin{lstlisting}
640        typedef void (*voidFunc)(void);
641
642        thread struct FuncRunner {
643                voidFunc func;
644        };
645
646        //ctor
647        void ?{}(thread FuncRunner* this, voidFunc inFunc) {
648                func = inFunc;
649        }
650
651        //main
652        void ?main(thread FuncRunner* this) {
653                this->func();
654        }
655\end{lstlisting}
656
657In this example \code{func} is a function pointer stored in \acrfull{tls}, which is \CFA is both easy to use and completly typesafe.
658
659Of course for threads to be useful, it must be possible to start and stop threads and wait for them to complete execution. While using \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.
660\begin{lstlisting}
661thread struct FuncRunner; //FuncRunner declared above
662
663void world() {
664        sout | "World!" | endl;
665}
666
667void main() {
668        FuncRunner run = {world};
669        //Thread run forks here
670
671        //Print to "Hello " and "World!" will be run concurrently
672        sout | "Hello " | endl;
673
674        //Implicit join at end of scope
675}
676\end{lstlisting}
677This 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.
678
679These semantics also naturally scale to multiple threads meaning basic synchronisation is very simple :
680\begin{lstlisting}
681        thread struct MyThread {
682                //...
683        };
684
685        //ctor
686        void ?{}(thread MyThread* this) {}
687
688        //main
689        void ?main(thread MyThread* this) {
690                //...
691        }
692
693        void foo() {
694                MyThread thrds[10];
695                //Start 10 threads at the beginning of the scope
696
697                DoStuff();
698
699                //Wait for the 10 threads to finish
700        }
701\end{lstlisting}
702
703\subsection{The \CFA Kernel : Processors, Clusters and Threads}\label{kernel}
704
705
706\subsection{Paradigms}\label{cfaparadigms}
707Given 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.
708
709% \subsection{High-level options}\label{tasks}
710%
711% \subsubsection{Thread interface}
712% constructors destructors
713%       initializer lists
714% monitors
715%
716% \subsubsection{Futures}
717%
718% \subsubsection{Implicit threading}
719% 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.
720%
721% \begin{center}
722% \begin{tabular}[t]{|c|c|c|}
723% Sequential & System Parallel & Language Parallel \\
724% \begin{lstlisting}
725% void big_sum(int* a, int* b,
726%                int* out,
727%                size_t length)
728% {
729%       for(int i = 0; i < length; ++i ) {
730%               out[i] = a[i] + b[i];
731%       }
732% }
733%
734%
735%
736%
737%
738% int* a[10000];
739% int* b[10000];
740% int* c[10000];
741% //... fill in a and b ...
742% big_sum(a, b, c, 10000);
743% \end{lstlisting} &\begin{lstlisting}
744% void big_sum(int* a, int* b,
745%                int* out,
746%                size_t length)
747% {
748%       range ar(a, a + length);
749%       range br(b, b + length);
750%       range or(out, out + length);
751%       parfor( ai, bi, oi,
752%       [](int* ai, int* bi, int* oi) {
753%               oi = ai + bi;
754%       });
755% }
756%
757% int* a[10000];
758% int* b[10000];
759% int* c[10000];
760% //... fill in a and b ...
761% big_sum(a, b, c, 10000);
762% \end{lstlisting}&\begin{lstlisting}
763% void big_sum(int* a, int* b,
764%                int* out,
765%                size_t length)
766% {
767%       for (ai, bi, oi) in (a, b, out) {
768%               oi = ai + bi;
769%       }
770% }
771%
772%
773%
774%
775%
776% int* a[10000];
777% int* b[10000];
778% int* c[10000];
779% //... fill in a and b ...
780% big_sum(a, b, c, 10000);
781% \end{lstlisting}
782% \end{tabular}
783% \end{center}
784%
785% \subsection{Machine setup}\label{machine}
786% Threads are all good and well but wee still some OS support to fully utilize available hardware.
787%
788% \textbf{\large{Work in progress...}} Do wee need something beyond specifying the number of kernel threads?
789
790\section{Putting it all together}
791
792\section{Future work}
793Concurrency 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.
794\subsection{Transactions}
795
796\section*{Acknowledgements}
797
798\clearpage
799\printglossary[type=\acronymtype]
800\printglossary
801
802\clearpage
803\bibliographystyle{plain}
804\bibliography{pl,local}
805
806
807\end{document}
Note: See TracBrowser for help on using the repository browser.