# source:doc/proposals/concurrency/text/concurrency.tex@27dde72

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

Major update to the concurrency proposal to be based on multiple files

• Property mode set to 100644
File size: 42.8 KB
Line
1% ======================================================================
2% ======================================================================
3\chapter{Concurrency}
4% ======================================================================
5% ======================================================================
7
8\section{Basics}
9The basic features that concurrency tools neet to offer is support for mutual-exclusion and synchronisation. Mutual-exclusion is the concept that only a fixed number of threads can access a critical section at any given time, where a critical section is the group of instructions on an associated portion of data that requires the limited access. On the other hand, synchronization enforces relative ordering of execution and synchronization tools are used to guarantee that event \textit{X} always happens before \textit{Y}.
10
11\subsection{Mutual-Exclusion}
12As mentionned above, mutual-exclusion is the guarantee that only a fix number of threads can enter a critical section at once. However, many solution exists for mutual exclusion which vary in terms of performance, flexibility and ease of use. Methods range from low level locks, which are fast and flexible but require significant attention to be correct, to  higher level mutual-exclusion methods, which sacrifice some performance in order to improve ease of use. Often by either guaranteeing some problems cannot occur (e.g. being deadlock free) or by offering a more explicit coupling between data and corresponding critical section. For example, the \CC \code{std::atomic<T>} which offer an easy way to express mutual-exclusion on a restricted set of features (.e.g: reading/writing large types atomically). Another challenge with low level locks is composability. Locks are said to not be composable because it takes careful organising for multiple locks to be used and once while preventing deadlocks. Easing composability is another feature higher-level mutual-exclusion mechanisms often offer.
13
14\subsection{Synchronization}
15As for mutual-exclusion, low level synchronisation primitive often offer great performance and good flexibility at the cost of ease of use. Again, higher-level mechanism often simplify usage by adding better coupling between synchronization and data, for example message passing, or offering simple solution to otherwise involved challenges. An example of this is barging. As mentionned above synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}. Most of the time synchronisation happens around a critical section, where threads most acquire said critical section in a certain order. However, it may also be desired to be able to guarantee that event \textit{Z} does not occur between \textit{X} and \textit{Y}. This is called barging, where event \textit{X} tries to effect event \textit{Y} but anoter thread races to grab the critical section and emits \textit{Z} before \textit{Y}. Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs.
16
17% ======================================================================
18% ======================================================================
19\section{Monitors}
20% ======================================================================
21% ======================================================================
22A 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 :
23\begin{cfacode}
24        typedef /*some monitor type*/ monitor;
25        int f(monitor & m);
26
27        int main() {
28                monitor m;  //Handle m
29                f(m);       //Routine using handle
30        }
31\end{cfacode}
32
33% ======================================================================
34% ======================================================================
35\subsection{Call semantics} \label{call}
36% ======================================================================
37% ======================================================================
38The above monitor example displays some of the intrinsic characteristics. Indeed, it is necessary to use pass-by-reference over pass-by-value for monitor routines. This semantics is important because at their core, monitors are implicit mutual-exclusion objects (locks), and these objects cannot be copied. Therefore, monitors are implicitly non-copyable.
39
40Another aspect to consider is when a monitor acquires its mutual exclusion. For example, a monitor may need to be passed through multiple helper routines that do not acquire the monitor mutual-exclusion on entry. Pass through can be both generic helper routines (\code{swap}, \code{sort}, etc.) or specific helper routines like the following to implement an atomic counter :
41
42\begin{cfacode}
43        monitor counter_t { /*...see section $\ref{data}$...*/ };
44
45        void ?{}(counter_t & nomutex this); //constructor
46        size_t ++?(counter_t & mutex this); //increment
47
48        //need for mutex is platform dependent here
49        void ?{}(size_t * this, counter_t & mutex cnt); //conversion
50\end{cfacode}
51
52Here, the constructor(\code{?\{\}}) uses the \code{nomutex} keyword to signify that it does not acquire the monitor mutual-exclusion when constructing. This semantics is because an object not yet constructed should never be shared and therefore does not require mutual exclusion. The prefix increment operator uses \code{mutex} to protect the incrementing process from race conditions. Finally, there is a conversion operator from \code{counter_t} to \code{size_t}. This conversion may or may not require the \code{mutex} keyword depending on whether or not reading an \code{size_t} is an atomic operation.
53
54Having 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. For example, given a routine without qualifiers \code{void foo(counter_t & this)} then it is reasonable that it should default to the safest option \code{mutex}. 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. In fact \code{nomutex} is the "normal" parameter behaviour, with the \code{nomutex} keyword effectively stating explicitly that "this routine is not special". Another alternative is to make having exactly one of these keywords mandatory, which would provide the same semantics but without the ambiguity of supporting routines neither keyword. Mandatory keywords would also have the added benefit of being self-documented but at the cost of extra typing. While there are several benefits to mandatory keywords, they do bring a few challenges. Mandatory keywords in \CFA would imply that the compiler must know without a doubt wheter or not a parameter is a monitor or not. Since \CFA relies heavily on traits as an abstraction mechanism, the distinction between a type that is a monitor and a type that looks like a monitor can become blurred. For this reason, \CFA only has the \code{mutex} keyword.
55
56
57The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
58\begin{cfacode}
59int f1(monitor & mutex m);
60int f2(const monitor & mutex m);
61int f3(monitor ** mutex m);
62int f4(monitor *[] mutex m);
63int f5(graph(monitor*) & mutex m);
64\end{cfacode}
65The problem is to indentify which object(s) should be acquired. Furthermore, each object needs to be acquired only once. In the case of simple routines like \code{f1} and \code{f2} it is easy to identify an exhaustive list of objects to acquire on entry. Adding indirections (\code{f3}) still allows the compiler and programmer to indentify which object is acquired. However, adding in arrays (\code{f4}) makes it much harder. Array lengths are not necessarily known in C, and even then making sure objects are only acquired once becomes none-trivial. This can be extended to absurd limits like \code{f5}, which uses a graph of monitors. To keep everyone as sane as possible~\cite{Chicken}, this projects imposes the requirement that a routine may only acquire one monitor per parameter and it must be the type of the parameter with one level of indirection (ignoring potential qualifiers). Also note that while routine \code{f3} can be supported, meaning that monitor \code{**m} is be acquired, passing an array to this routine would be type safe and yet result in undefined behavior because only the first element of the array is acquired. This is specially true for non-copyable objects like monitors, where an array of pointers is simplest way to express a group of monitors. However, this ambiguity is part of the C type-system with respects to arrays. For this reason, \code{mutex} is disallowed in the context where arrays may be passed:
66
67\begin{cfacode}
68int f1(monitor & mutex m);   //Okay : recommanded case
69int f2(monitor * mutex m);   //Okay : could be an array but probably not
70int f3(monitor [] mutex m);  //Not Okay : Array of unkown length
71int f4(monitor ** mutex m);  //Not Okay : Could be an array
72int f5(monitor *[] mutex m); //Not Okay : Array of unkown length
73\end{cfacode}
74
75Unlike object-oriented monitors, where calling a mutex member \emph{implicitly} acquires mutual-exclusion, \CFA uses an explicit mechanism to acquire mutual-exclusion. A consequence of this approach is that it extends naturally to multi-monitor calls.
76\begin{cfacode}
77int f(MonitorA & mutex a, MonitorB & mutex b);
78
79MonitorA a;
80MonitorB b;
81f(a,b);
82\end{cfacode}
83The capacity to acquire multiple locks before entering a critical section is called \emph{\gls{group-acquire}}. In practice, writing multi-locking routines that do not lead to deadlocks is tricky. Having language support for such a feature is therefore a significant asset for \CFA. In the case presented above, \CFA guarantees that the order of aquisition is consistent across calls to routines using the same monitors as arguments. However, since \CFA monitors use multi-acquisition locks, users can effectively force the acquiring order. For example, notice which routines use \code{mutex}/\code{nomutex} and how this affects aquiring order:
84\begin{cfacode}
85        void foo(A & mutex a, B & mutex b) { //acquire a & b
86                ...
87        }
88
89        void bar(A & mutex a, B & /*nomutex*/ b) { //acquire a
90                ... foo(a, b); ... //acquire b
91        }
92
93        void baz(A & /*nomutex*/ a, B & mutex b) { //acquire b
94                ... foo(a, b); ... //acquire a
95        }
96\end{cfacode}
97The multi-acquisition monitor lock allows a monitor lock to be acquired by both \code{bar} or \code{baz} and acquired again in \code{foo}. In the calls to \code{bar} and \code{baz} the monitors are acquired in opposite order.
98
99However, such use leads the lock acquiring order problem. In the example above, the user uses implicit ordering in the case of function \code{foo} but explicit ordering in the case of \code{bar} and \code{baz}. This subtle mistake means that calling these routines concurrently may lead to deadlock and is therefore undefined behavior. As shown on several occasion\cit, solving this problem requires:
100\begin{enumerate}
101        \item Dynamically tracking of the monitor-call order.
102        \item Implement rollback semantics.
103\end{enumerate}
104While the first requirement is already a significant constraint on the system, implementing a general rollback semantics in a C-like language is prohibitively complex \cit. In \CFA, users simply need to be carefull when acquiring multiple monitors at the same time.
105
106Finally, for convenience, monitors support multiple acquiring, that is acquiring a monitor while already holding it does not cause a deadlock. It simply increments an internal counter which is then used to release the monitor after the number of acquires and releases match up. This is particularly usefull when monitor routines use other monitor routines as helpers or for recursions. For example:
107\begin{cfacode}
108monitor bank {
109        int money;
110        log_t usr_log;
111};
112
113void deposit( bank & mutex b, int deposit ) {
114        b.money += deposit;
115        b.usr_log | "Adding" | deposit | endl;
116}
117
118void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) {
119        deposit( mybank, -me2you );
120        deposit( yourbank, me2you );
121}
122\end{cfacode}
123
124% ======================================================================
125% ======================================================================
126\subsection{Data semantics} \label{data}
127% ======================================================================
128% ======================================================================
129Once 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 contain shared data. This data should be intrinsic to the monitor declaration to prevent any accidental use of data without its appropriate protection. For example, here is a complete version of the counter showed in section \ref{call}:
130\begin{cfacode}
131monitor counter_t {
132        int value;
133};
134
135void ?{}(counter_t & this) {
136        this.cnt = 0;
137}
138
139int ?++(counter_t & mutex this) {
140        return ++this.value;
141}
142
143//need for mutex is platform dependent here
144void ?{}(int * this, counter_t & mutex cnt) {
145        *this = (int)cnt;
146}
147\end{cfacode}
148
149This counter is used as follows:
150\begin{center}
151\begin{tabular}{c @{\hskip 0.35in} c @{\hskip 0.35in} c}
152\begin{cfacode}
153//shared counter
154counter_t cnt1, cnt2;
155
160        ...
162\end{cfacode}
163\end{tabular}
164\end{center}
165Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting.
166
167% ======================================================================
168% ======================================================================
169\subsection{Implementation Details: Interaction with polymorphism}
170% ======================================================================
171% ======================================================================
172Depending on the choice of semantics for when monitor locks are acquired, interaction between monitors and \CFA's concept of polymorphism can be complex to support. However, it is shown that entry-point locking solves most of the issues.
173
174First of all, interaction between \code{otype} polymorphism and monitors is impossible since monitors do not support copying. Therefore, the main question is how to support \code{dtype} polymorphism. Since a monitor's main purpose is to ensure mutual exclusion when accessing shared data, this implies that mutual exclusion is only required for routines that do in fact access shared data. However, since \code{dtype} polymorphism always handles incomplete types (by definition), no \code{dtype} polymorphic routine can access shared data since the data requires knowledge about the type. Therefore, the only concern when combining \code{dtype} polymorphism and monitors is to protect access to routines.
175
176Before looking into complex control flow, it is important to present the difference between the two acquiring options : \gls{callsite-locking} and \gls{entry-point-locking}, i.e. acquiring the monitors before making a mutex routine call or as the first instruction of the mutex routine call. For example:
177\begin{center}
178\setlength\tabcolsep{1.5pt}
179\begin{tabular}{|c|c|c|}
180Code & \gls{callsite-locking} & \gls{entry-point-locking} \\
181\CFA & pseudo-code & pseudo-code \\
182\hline
183\begin{cfacode}[tabsize=3]
184void foo(monitor& mutex a){
185
186
187
188        //Do Work
189        //...
190
191}
192
193void main() {
194        monitor a;
195
196
197
198        foo(a);
199
200}
201\end{cfacode} & \begin{pseudo}[tabsize=3]
202foo(& a) {
203
204
205
206        //Do Work
207        //...
208
209}
210
211main() {
212        monitor a;
213        //calling routine
214        //handles concurrency
215        acquire(a);
216        foo(a);
217        release(a);
218}
219\end{pseudo} & \begin{pseudo}[tabsize=3]
220foo(& a) {
221        //called routine
222        //handles concurrency
223        acquire(a);
224        //Do Work
225        //...
226        release(a);
227}
228
229main() {
230        monitor a;
231
232
233
234        foo(a);
235
236}
237\end{pseudo}
238\end{tabular}
239\end{center}
240
241\Gls{callsite-locking} is inefficient, since any \code{dtype} routine may have to obtain some lock before calling a routine, depending on whether or not the type passed is a monitor. However, with \gls{entry-point-locking} calling a monitor routine becomes exactly the same as calling it from anywhere else. Note that the \code{mutex} keyword relies on the resolver rather than another form of language, which mean that in cases where a generic monitor routine is actually desired, writing a mutex routine is possible with the proper trait. This is possible because monitors are designed in terms a trait. For example:
242\begin{cfacode}
243//Incorrect
244//T is not a monitor
245forall(dtype T)
246void foo(T * mutex t);
247
248//Correct
249//this function only works on monitors
250//(any monitor)
251forall(dtype T | is_monitor(T))
252void bar(T * mutex t));
253\end{cfacode}
254
255
256% ======================================================================
257% ======================================================================
258\section{Internal scheduling} \label{insched}
259% ======================================================================
260% ======================================================================
261In addition to mutual exclusion, the monitors at the core of \CFA's concurrency can also be used to achieve synchronisation. With monitors, this is generally achieved with internal or external scheduling as in\cit. Since internal scheduling of single monitors is mostly a solved problem, this proposal concentraits on extending internal scheduling to multiple monitors at once. Indeed, like the \gls{group-acquire} semantics, internal scheduling extends to multiple monitors at once in a way that is natural to the user but requires additional complexity on the implementation side.
262
263First, Here is a simple example of such a technique:
264
265\begin{cfacode}
266        monitor A {
267                condition e;
268        }
269
270        void foo(A & mutex a) {
271                ...
272                // Wait for cooperation from bar()
273                wait(a.e);
274                ...
275        }
276
277        void bar(A & mutex a) {
278                // Provide cooperation for foo()
279                ...
280                // Unblock foo at scope exit
281                signal(a.e);
282        }
283\end{cfacode}
284
285There are two details to note here. First, there \code{signal} is a delayed operation, it only unblocks the waiting thread when it reaches the end of the critical section. This is needed to respect mutual-exclusion. Second, in \CFA, \code{condition} have no particular need to be stored inside a monitor, beyond any software engineering reasons. Here routine \code{foo} waits for the \code{signal} from \code{bar} before making further progress, effectively ensuring a basic ordering.
286
287An important aspect to take into account here is that \CFA does not allow barging, which means that once function \code{bar} releases the monitor, foo is guaranteed to resume immediately after (unless some other thread waited on the same condition). This guarantees offers the benefit of not having to loop arount waits in order to guarantee that a condition is still met. The main reason \CFA offers this guarantee is that users can easily introduce barging if it becomes a necessity but adding barging prevention or barging avoidance is more involved without language support. Supporting barging prevention as well as extending internal scheduling to multiple monitors is the main source of complexity in the design of \CFA concurrency.
288
289% ======================================================================
290% ======================================================================
291\subsection{Internal Scheduling - multi monitor}
292% ======================================================================
293% ======================================================================
294It easier to understand the problem of multi-monitor scheduling using a series of pseudo-code. Note that for simplicity in the following snippets of pseudo-code, waiting and signalling is done using an implicit condition variable, like Java built-in monitors.
295
296\begin{multicols}{2}
298\begin{pseudo}
299acquire A
300        wait A
301release A
302\end{pseudo}
303
304\columnbreak
305
307\begin{pseudo}
308acquire A
309        signal A
310release A
311\end{pseudo}
312\end{multicols}
313
314The previous example shows the simple case of having two threads (one for each column) and a single monitor A. One thread acquires before waiting (atomically blocking and releasing A) and the other acquires before signalling. There is an important thing to note here, both \code{wait} and \code{signal} must be called with the proper monitor(s) already acquired. This restriction is hidden on the user side in \uC, as it is a logical requirement for barging prevention.
315
316A direct extension of the previous example is the \gls{group-acquire} version:
317
318\begin{multicols}{2}
319\begin{pseudo}
320acquire A & B
321        wait A & B
322release A & B
323\end{pseudo}
324
325\columnbreak
326
327\begin{pseudo}
328acquire A & B
329        signal A & B
330release A & B
331\end{pseudo}
332\end{multicols}
333
334This version uses \gls{group-acquire} (denoted using the \& symbol), but the presence of multiple monitors does not add a particularly new meaning. Synchronization happens between the two threads in exactly the same way and order. The only difference is that mutual exclusion covers more monitors. On the implementation side, handling multiple monitors does add a degree of complexity as the next few examples demonstrate.
335
336While deadlock issues can occur when nesting monitors, these issues are only a symptom of the fact that locks, and by extension monitors, are not perfectly composable. However, for monitors as for locks, it is possible to write a program using nesting without encountering any problems if nested is done correctly. For example, the next pseudo-code snippet acquires monitors A then B before waiting while only acquiring B when signalling, effectively avoiding the nested monitor problem.
337
338\begin{multicols}{2}
339\begin{pseudo}
340acquire A
341        acquire B
342                wait B
343        release B
344release A
345\end{pseudo}
346
347\columnbreak
348
349\begin{pseudo}
350
351acquire B
352        signal B
353release B
354
355\end{pseudo}
356\end{multicols}
357
358The next example is where \gls{group-acquire} adds a significant layer of complexity to the internal signalling semantics.
359
360\begin{multicols}{2}
362\begin{pseudo}[numbers=left]
363acquire A
364        // Code Section 1
365        acquire A & B
366                // Code Section 2
367                wait A & B
368                // Code Section 3
369        release A & B
370        // Code Section 4
371release A
372\end{pseudo}
373
374\columnbreak
375
377\begin{pseudo}[numbers=left, firstnumber=10]
378acquire A
379        // Code Section 5
380        acquire A & B
381                // Code Section 6
382                signal A & B
383                // Code Section 7
384        release A & B
385        // Code Section 8
386release A
387\end{pseudo}
388\end{multicols}
389
390It is particularly important to pay attention to code sections 8 and 3, which are where the existing semantics of internal scheduling need to be extended for multiple monitors. The root of the problem is that \gls{group-acquire} is used in a context where one of the monitors is already acquired and is why it is important to define the behaviour of the previous pseudo-code. When the signaller thread reaches the location where it should "release A \& B" (line 17), it must actually transfer ownership of monitor B to the waiting thread. This ownership trasnfer is required in order to prevent barging. Since the signalling thread still needs the monitor A, simply waking up the waiting thread is not an option because it would violate mutual exclusion. We are therefore left with three options:
391
392\subsubsection{Delaying signals}
393The first more obvious solution to solve the problem of multi-monitor scheduling is to keep ownership of all locks until the last lock is ready to be transferred. It can be argued that that moment is the correct time to transfer ownership when the last lock is no longer needed is what fits most closely to the behaviour of single monitor scheduling. This solution has the main benefit of transferring ownership of groups of monitors, which simplifies the semantics from mutiple objects to a single groupd of object. Effectively making the existing single monitor semantic viable by simply changing monitors to monitor collections.
394\begin{multicols}{2}
395Waiter
396\begin{pseudo}[numbers=left]
397acquire A
398        acquire A & B
399                wait A & B
400        release A & B
401release A
402\end{pseudo}
403
404\columnbreak
405
406Signaller
407\begin{pseudo}[numbers=left, firstnumber=6]
408acquire A
409        acquire A & B
410                signal A & B
411        release A & B
412        //Secretly keep B here
413release A
414//Wakeup waiter and transfer A & B
415\end{pseudo}
416\end{multicols}
417However, this solution can become much more complicated depending on what is executed while secretly holding B. Indeed, nothing prevents a user from signalling monitor A on a different condition variable:
418\begin{multicols}{2}
420\begin{pseudo}
421acquire A
422        acquire A & B
423                wait A & B
424        release A & B
425release A
426\end{pseudo}
427
429\begin{pseudo}
430acquire A
431        wait A
432release A
433\end{pseudo}
434
435\columnbreak
436
438\begin{pseudo}
439acquire A
440        acquire A & B
441                signal A & B
442        release A & B
443        //Secretly keep B here
444        signal A
445release A
447//Who wakes up the other thread?
448\end{pseudo}
449\end{multicols}
450
451The goal in this solution is to avoid the need to transfer ownership of a subset of the condition monitors. However, this goal is unreacheable in the previous example since \TODO
452
453\subsubsection{Dependency graphs}
454In the previous pseudo-code, there is a solution which would statisfy both barging prevention and mutual exclusion. If ownership of both monitors is transferred to the waiter when the signaller releases A and then the waiter transfers back ownership of A when it releases it then the problem is solved. Dynamically finding the correct order is therefore the second possible solution. The problem it encounters is that it effectively boils down to resolving a dependency graph of ownership requirements. Here even the simplest of code snippets requires two transfers and it seems to increase in a manner closer to polynomial. For example the following code which is just a direct extension to three monitors requires at least three ownership transfer and has multiple solutions:
455
456\begin{multicols}{2}
457\begin{pseudo}
458acquire A
459        acquire B
460                acquire C
461                        wait A & B & C
462                release C
463        release B
464release A
465\end{pseudo}
466
467\columnbreak
468
469\begin{pseudo}
470acquire A
471        acquire B
472                acquire C
473                        signal A & B & C
474                release C
475        release B
476release A
477\end{pseudo}
478\end{multicols}
479Resolving dependency graph being a complex and expensive endeavour, this solution is not the preffered one.
480
481\subsubsection{Partial signalling}
482Finally, the solution that was chosen for \CFA is to use partial signalling. Consider the following case:
483
484\begin{multicols}{2}
485\begin{pseudo}[numbers=left]
486acquire A
487        acquire A & B
488                wait A & B
489        release A & B
490release A
491\end{pseudo}
492
493\columnbreak
494
495\begin{pseudo}[numbers=left, firstnumber=6]
496acquire A
497        acquire A & B
498                signal A & B
499        release A & B
500        // ... More code
501release A
502\end{pseudo}
503\end{multicols}
504
505The partial signalling solution transfers ownership of monitor B at lines 10 but does not wake the waiting thread since it is still using monitor A. Only when it reaches line 11 does it actually wakeup the waiting thread. This solution has the benefit that complexity is encapsulated in to only two actions, passing monitors to the next owner when they should be release and conditionnaly waking threads if all conditions are met. Contrary to the other solutions, this solution quickly hits an upper bound on complexity of implementation.
506
507% ======================================================================
508% ======================================================================
509\subsection{Signalling: Now or Later}
510% ======================================================================
511% ======================================================================
512An important note is that, until now, signalling a monitor was a delayed operation. The ownership of the monitor is transferred only when the monitor would have otherwise been released, not at the point of the \code{signal} statement. However, in some cases, it may be more convenient for users to immediately transfer ownership to the thread that is waiting for cooperation. This is achieved using the \code{signal_block} routine\footnote{name to be discussed}.
513
514For example here is an example highlighting the difference in behaviour:
515\begin{center}
516\begin{tabular}{|c|c|}
517\code{signal} & \code{signal_block} \\
518\hline
519\begin{cfacode}
520monitor M { int val; };
521
522void foo(M & mutex m ) {
523        m.val++;
524        sout| "Foo:" | m.val |endl;
525
526        wait( c );
527
528        m.val++;
529        sout| "Foo:" | m.val |endl;
530}
531
532void bar(M & mutex m ) {
533        m.val++;
534        sout| "Bar:" | m.val |endl;
535
536        signal( c );
537
538        m.val++;
539        sout| "Bar:" | m.val |endl;
540}
541\end{cfacode}&\begin{cfacode}
542monitor M { int val; };
543
544void foo(M & mutex m ) {
545        m.val++;
546        sout| "Foo:" | m.val |endl;
547
548        wait( c );
549
550        m.val++;
551        sout| "Foo:" | m.val |endl;
552}
553
554void bar(M & mutex m ) {
555        m.val++;
556        sout| "Bar:" | m.val |endl;
557
558        signal_block( c );
559
560        m.val++;
561        sout| "Bar:" | m.val |endl;
562}
563\end{cfacode}
564\end{tabular}
565\end{center}
566Assuming that \code{val} is initialized at 0, that each routine are called from seperate thread and that \code{foo} is always called first. The previous code would yield the following output:
567
568\begin{center}
569\begin{tabular}{|c|c|}
570\code{signal} & \code{signal_block} \\
571\hline
572\begin{pseudo}
573Foo: 0
574Bar: 1
575Bar: 2
576Foo: 3
577\end{pseudo}&\begin{pseudo}
578Foo: 0
579Bar: 1
580Foo: 2
581Bar: 3
582\end{pseudo}
583\end{tabular}
584\end{center}
585
586As mentionned, \code{signal} only transfers ownership once the current critical section exits, resulting in the second "Bar" line to be printed before the second "Foo" line. On the other hand, \code{signal_block} immediately transfers ownership to \code{bar}, causing an inversion of output. Obviously this means that \code{signal_block} is a blocking call, which will only be resumed once the signalled function exits the critical section.
587
588% ======================================================================
589% ======================================================================
590\subsection{Internal scheduling: Implementation} \label{insched-impl}
591% ======================================================================
592% ======================================================================
593\TODO
594
595
596% ======================================================================
597% ======================================================================
598\section{External scheduling} \label{extsched}
599% ======================================================================
600% ======================================================================
601An alternative to internal scheduling is to use external scheduling.
602\begin{center}
603\begin{tabular}{|c|c|}
604Internal Scheduling & External Scheduling \\
605\hline
606\begin{ucppcode}
607_Monitor Semaphore {
608        condition c;
609        bool inUse;
610public:
611        void P() {
612                if(inUse) wait(c);
613                inUse = true;
614        }
615        void V() {
616                inUse = false;
617                signal(c);
618        }
619}
620\end{ucppcode}&\begin{ucppcode}
621_Monitor Semaphore {
622
623        bool inUse;
624public:
625        void P() {
626                if(inUse) _Accept(V);
627                inUse = true;
628        }
629        void g() {
630                inUse = false;
631
632        }
633}
634\end{ucppcode}
635\end{tabular}
636\end{center}
637This method is more constrained and explicit, which may help users tone down the undeterministic nature of concurrency. Indeed, as the following examples demonstrates, external scheduling allows users to wait for events from other threads without the concern of unrelated events occuring. External scheduling can generally be done either in terms of control flow (e.g. \uC) or in terms of data (e.g. 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 a simple use \code{accept} versus \code{wait}/\code{signal} and its advantages.
638
639In the case of internal scheduling, the call to \code{wait} only guarantees that \code{g} is the last routine to access the monitor. This entails 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.
640
641% ======================================================================
642% ======================================================================
643\subsection{Loose object definitions}
644% ======================================================================
645% ======================================================================
646In \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:
647
648\begin{cfacode}
649        monitor A {};
650
651        void f(A & mutex a);
652        void g(A & mutex a) { accept(f); }
653\end{cfacode}
654
655However, external scheduling is an example where implementation constraints become visible from the interface. Indeed, since 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:
656
657\begin{center}
658\begin{tabular}{l}
659\begin{pseudo}
660        if monitor is free
661                enter
662        elif monitor accepts me
663                enter
664        else
665                block
666\end{pseudo}
667\end{tabular}
668\end{center}
669
670For the \pscode{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 \pscode{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:
671
672\begin{center}
673{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
674\end{center}
675
676There are other alternatives to these pictures but in the case of this picture implementing a fast accept check is relatively easy. Indeed simply updating a bitmask when the acceptor queue changes is enough to have a check that executes in a single instruction, even with a fairly large number (e.g. 128) of mutex members. However, this relies on the fact that all the acceptable routines are declared with the monitor type. For OO languages this does not compromise much since monitors already have an exhaustive list of member routines. However, for \CFA this is not the case; routines can be added to a type anywhere after its declaration. Its important to note that the bitmask approach does not actually require an exhaustive list of routines, but it requires a dense unique ordering of routines with an upper-bound and that ordering must be consistent across translation units.
677The alternative would be to have a picture more like this one:
678
679\begin{center}
680{\resizebox{0.4\textwidth}{!}{\input{ext_monitor}}}
681\end{center}
682
683Not 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.
684
685At 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.
686
687In either cases here are a few alternatives for the different syntaxes this syntax : \\
688\begin{center}
689{\renewcommand{\arraystretch}{1.5}
690\begin{tabular}[t]{l @{\hskip 0.35in} l}
691\hline
692\multicolumn{2}{ c }{\code{accept} on type}\\
693\hline
694Alternative 1 & Alternative 2 \\
695\begin{lstlisting}
696mutex struct A
697accept( void f(A & mutex a) )
698{};
699\end{lstlisting} &\begin{lstlisting}
700mutex struct A {}
701accept( void f(A & mutex a) );
702
703\end{lstlisting} \\
704Alternative 3 & Alternative 4 \\
705\begin{lstlisting}
706mutex struct A {
707        accept( void f(A & mutex a) )
708};
709
710\end{lstlisting} &\begin{lstlisting}
711mutex struct A {
712        accept :
713                void f(A & mutex a) );
714};
715\end{lstlisting}\\
716\hline
717\multicolumn{2}{ c }{\code{accept} on routine}\\
718\hline
719\begin{lstlisting}
720mutex struct A {};
721
722void f(A & mutex a)
723
724accept( void f(A & mutex a) )
725void g(A & mutex a) {
726        /*...*/
727}
728\end{lstlisting}&\\
729\end{tabular}
730}
731\end{center}
732
733Another 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.
734
735% ======================================================================
736% ======================================================================
737\subsection{Multi-monitor scheduling}
738% ======================================================================
739% ======================================================================
740
741External 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:
742\begin{cfacode}
743        accept( void f(mutex struct A & mutex this))
744        mutex struct A {};
745
746        mutex struct B {};
747
748        void g(A & mutex a, B & mutex b) {
749                accept(f); //ambiguous, which monitor
750        }
751\end{cfacode}
752
753The obvious solution is to specify the correct monitor as follows:
754
755\begin{cfacode}
756        accept( void f(mutex struct A & mutex this))
757        mutex struct A {};
758
759        mutex struct B {};
760
761        void g(A & mutex a, B & mutex b) {
762                accept( b, f );
763        }
764\end{cfacode}
765
766This 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.
767
768\begin{cfacode}
769        accept( void f(mutex struct A & mutex, mutex struct A & mutex))
770        mutex struct A {};
771
772        mutex struct B {};
773
774        void g(A & mutex a, B & mutex b) {
775                accept( b, a, f);
776        }
777\end{cfacode}
778
779Note 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.
780
781% ======================================================================
782% ======================================================================
783\subsection{Implementation Details: External scheduling queues}
784% ======================================================================
785% ======================================================================
786To 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 reasonable 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.
787
788% ======================================================================
789% ======================================================================
790\section{Other concurrency tools}
791% ======================================================================
792% ======================================================================
793% \TODO
Note: See TracBrowser for help on using the repository browser.