source: doc/proposals/concurrency/concurrency.tex @ 9b4343e

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

Made significant changes to proposal and added simple version number

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