source: doc/proposals/concurrency/text/concurrency.tex @ ff98952

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since ff98952 was ff98952, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Updated draft up to 3.4

  • Property mode set to 100644
File size: 43.7 KB
Line 
1% ======================================================================
2% ======================================================================
3\chapter{Concurrency}
4% ======================================================================
5% ======================================================================
6Several tool can be used to solve concurrency challenges. Since many of these challenges appear with the use of mutable shared-state, some languages and libraries simply disallow mutable shared-state (Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, Akka (Scala)~\cite{Akka}). In these paradigms, interaction among concurrent objects relies on message passing~\cite{Thoth,Harmony,V-Kernel} or other paradigms that closely relate to networking concepts (channels\cit for example). However, in languages that use routine calls as their core abstraction-mechanism, these approaches force a clear distinction between concurrent and non-concurrent paradigms (i.e., message passing versus routine call). This distinction in turn means that, in order to be effective, programmers need to learn two sets of designs patterns. This distinction can be hidden away in library code, effective use of the librairy still has to take both paradigms into account. Approaches based on shared memory are more closely related to non-concurrent paradigms since they often rely on basic constructs like routine calls and shared objects. At a lower level, non-concurrent paradigms are often implemented as locks and atomic operations. Many such mechanisms have been proposed, including semaphores~\cite{Dijkstra68b} and path expressions~\cite{Campbell74}. However, for productivity reasons it is desireable to have a higher-level construct be the core concurrency paradigm~\cite{HPP:Study}. An approach that is worth mentionning because it is gaining in popularity is transactionnal memory~\cite{Dice10}[Check citation]. While this approach is even pursued by system languages like \CC\cit, the performance and feature set is currently too restrictive to add such a paradigm to a language like C or \CC\cit, which is why it was rejected as the core paradigm for concurrency in \CFA. One of the most natural, elegant, and efficient mechanisms for synchronization and communication, especially for shared memory systems, is the \emph{monitor}. Monitors were first proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}. Many programming languages---e.g., Concurrent Pascal~\cite{ConcurrentPascal}, Mesa~\cite{Mesa}, Modula~\cite{Modula-2}, Turing~\cite{Turing:old}, Modula-3~\cite{Modula-3}, NeWS~\cite{NeWS}, Emerald~\cite{Emerald}, \uC~\cite{Buhr92a} and Java~\cite{Java}---provide monitors as explicit language constructs. In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as semaphores or locks to simulate monitors. For these reasons, this project proposes monitors as the core concurrency-construct.
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
156//multiple threads access counter
157thread 1 : cnt1++; cnt2++;
158thread 2 : cnt1++; cnt2++;
159thread 3 : cnt1++; cnt2++;
160        ...
161thread N : cnt1++; cnt2++;
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}
297thread 1
298\begin{pseudo}
299acquire A
300        wait A
301release A
302\end{pseudo}
303
304\columnbreak
305
306thread 2
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}
361Waiting thread
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
376Signalling thread
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\begin{center}
390Listing 1
391\end{center}
392
393It 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:
394
395\subsubsection{Delaying signals}
396The 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.
397\begin{multicols}{2}
398Waiter
399\begin{pseudo}[numbers=left]
400acquire A
401        acquire A & B
402                wait A & B
403        release A & B
404release A
405\end{pseudo}
406
407\columnbreak
408
409Signaller
410\begin{pseudo}[numbers=left, firstnumber=6]
411acquire A
412        acquire A & B
413                signal A & B
414        release A & B
415        //Secretly keep B here
416release A
417//Wakeup waiter and transfer A & B
418\end{pseudo}
419\end{multicols}
420However, 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:
421\newpage
422\begin{multicols}{2}
423Thread 1
424\begin{pseudo}[numbers=left, firstnumber=1]
425acquire A
426        acquire A & B
427                wait A & B
428        release A & B
429release A
430\end{pseudo}
431
432Thread 2
433\begin{pseudo}[numbers=left, firstnumber=6]
434acquire A
435        wait A
436release A
437\end{pseudo}
438
439\columnbreak
440
441Thread 3
442\begin{pseudo}[numbers=left, firstnumber=10]
443acquire A
444        acquire A & B
445                signal A & B
446        release A & B
447        //Secretly keep B here
448        signal A
449release A
450//Wakeup thread 1 or 2?
451//Who wakes up the other thread?
452\end{pseudo}
453\end{multicols}
454
455The 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. Depending on the order of signals (line 12 and 15) two cases can happen. Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order. However, regardless of the answer, users can move line 15 before line 11 and get the reverse effect.
456
457\paragraph{Case 1: thread 1 will go first.} In this case, the problem is that monitor A needs to be passed to thread 2 when thread 1 is done with it.
458\paragraph{Case 2: thread 2 will go first.} In this case, the problem is that monitor B needs to be passed to thread 1. This can be done directly or using thread 2 as an intermediate.
459\\
460
461In both cases however, the threads need to be able to distinguish on a per monitor basis which ones need to be released and which ones need to be transferred. Which means monitors cannot be handled as a single homogenous group.
462
463\subsubsection{Dependency graphs}
464In the Listing 1 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:
465
466\begin{multicols}{2}
467\begin{pseudo}
468acquire A
469        acquire B
470                acquire C
471                        wait A & B & C
472                release C
473        release B
474release A
475\end{pseudo}
476
477\columnbreak
478
479\begin{pseudo}
480acquire A
481        acquire B
482                acquire C
483                        signal A & B & C
484                release C
485        release B
486release A
487\end{pseudo}
488\end{multicols}
489Resolving dependency graph being a complex and expensive endeavour, this solution is not the preffered one.
490
491\subsubsection{Partial signalling}
492Finally, the solution that was chosen for \CFA is to use partial signalling. Consider the following case:
493
494\begin{multicols}{2}
495\begin{pseudo}[numbers=left]
496acquire A
497        acquire A & B
498                wait A & B
499        release A & B
500release A
501\end{pseudo}
502
503\columnbreak
504
505\begin{pseudo}[numbers=left, firstnumber=6]
506acquire A
507        acquire A & B
508                signal A & B
509        release A & B
510        // ... More code
511release A
512\end{pseudo}
513\end{multicols}
514
515The 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.
516
517% ======================================================================
518% ======================================================================
519\subsection{Signalling: Now or Later}
520% ======================================================================
521% ======================================================================
522An 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}.
523
524For example here is an example highlighting the difference in behaviour:
525\begin{center}
526\begin{tabular}{|c|c|}
527\code{signal} & \code{signal_block} \\
528\hline
529\begin{cfacode}
530monitor M { int val; };
531
532void foo(M & mutex m ) {
533        m.val++;
534        sout| "Foo:" | m.val |endl;
535
536        wait( c );
537
538        m.val++;
539        sout| "Foo:" | m.val |endl;
540}
541
542void bar(M & mutex m ) {
543        m.val++;
544        sout| "Bar:" | m.val |endl;
545
546        signal( c );
547
548        m.val++;
549        sout| "Bar:" | m.val |endl;
550}
551\end{cfacode}&\begin{cfacode}
552monitor M { int val; };
553
554void foo(M & mutex m ) {
555        m.val++;
556        sout| "Foo:" | m.val |endl;
557
558        wait( c );
559
560        m.val++;
561        sout| "Foo:" | m.val |endl;
562}
563
564void bar(M & mutex m ) {
565        m.val++;
566        sout| "Bar:" | m.val |endl;
567
568        signal_block( c );
569
570        m.val++;
571        sout| "Bar:" | m.val |endl;
572}
573\end{cfacode}
574\end{tabular}
575\end{center}
576Assuming 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:
577
578\begin{center}
579\begin{tabular}{|c|c|}
580\code{signal} & \code{signal_block} \\
581\hline
582\begin{pseudo}
583Foo: 0
584Bar: 1
585Bar: 2
586Foo: 3
587\end{pseudo}&\begin{pseudo}
588Foo: 0
589Bar: 1
590Foo: 2
591Bar: 3
592\end{pseudo}
593\end{tabular}
594\end{center}
595
596As 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.
597
598% ======================================================================
599% ======================================================================
600\subsection{Internal scheduling: Implementation} \label{insched-impl}
601% ======================================================================
602% ======================================================================
603\TODO
604
605
606% ======================================================================
607% ======================================================================
608\section{External scheduling} \label{extsched}
609% ======================================================================
610% ======================================================================
611An alternative to internal scheduling is to use external scheduling.
612\begin{center}
613\begin{tabular}{|c|c|}
614Internal Scheduling & External Scheduling \\
615\hline
616\begin{ucppcode}
617_Monitor Semaphore {
618        condition c;
619        bool inUse;
620public:
621        void P() { 
622                if(inUse) wait(c);
623                inUse = true;
624        }
625        void V() { 
626                inUse = false;         
627                signal(c);
628        }
629}
630\end{ucppcode}&\begin{ucppcode}
631_Monitor Semaphore {
632
633        bool inUse;
634public:
635        void P() { 
636                if(inUse) _Accept(V);
637                inUse = true;
638        }
639        void g() { 
640                inUse = false;
641
642        }
643}
644\end{ucppcode}
645\end{tabular}
646\end{center}
647This 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.
648
649In 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.
650
651% ======================================================================
652% ======================================================================
653\subsection{Loose object definitions}
654% ======================================================================
655% ======================================================================
656In \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:
657
658\begin{cfacode}
659        monitor A {};
660
661        void f(A & mutex a);
662        void g(A & mutex a) { accept(f); }
663\end{cfacode}
664
665However, 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:
666
667\begin{center}
668\begin{tabular}{l}
669\begin{pseudo}
670        if monitor is free
671                enter
672        elif monitor accepts me
673                enter
674        else
675                block
676\end{pseudo}
677\end{tabular}
678\end{center}
679
680For 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:
681
682\begin{center}
683{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
684\end{center}
685
686There 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.
687The alternative would be to have a picture more like this one:
688
689\begin{center}
690{\resizebox{0.4\textwidth}{!}{\input{ext_monitor}}}
691\end{center}
692
693Not 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.
694
695At 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.
696
697In either cases here are a few alternatives for the different syntaxes this syntax : \\
698\begin{center}
699{\renewcommand{\arraystretch}{1.5}
700\begin{tabular}[t]{l @{\hskip 0.35in} l}
701\hline
702\multicolumn{2}{ c }{\code{accept} on type}\\
703\hline
704Alternative 1 & Alternative 2 \\
705\begin{lstlisting}
706mutex struct A
707accept( void f(A & mutex a) )
708{};
709\end{lstlisting} &\begin{lstlisting}
710mutex struct A {}
711accept( void f(A & mutex a) );
712
713\end{lstlisting} \\
714Alternative 3 & Alternative 4 \\
715\begin{lstlisting}
716mutex struct A {
717        accept( void f(A & mutex a) )
718};
719
720\end{lstlisting} &\begin{lstlisting}
721mutex struct A {
722        accept :
723                void f(A & mutex a) );
724};
725\end{lstlisting}\\
726\hline
727\multicolumn{2}{ c }{\code{accept} on routine}\\
728\hline
729\begin{lstlisting}
730mutex struct A {};
731
732void f(A & mutex a)
733
734accept( void f(A & mutex a) )
735void g(A & mutex a) {
736        /*...*/
737}
738\end{lstlisting}&\\
739\end{tabular}
740}
741\end{center}
742
743Another 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.
744
745% ======================================================================
746% ======================================================================
747\subsection{Multi-monitor scheduling}
748% ======================================================================
749% ======================================================================
750
751External 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:
752\begin{cfacode}
753        accept( void f(mutex struct A & mutex this))
754        mutex struct A {};
755
756        mutex struct B {};
757
758        void g(A & mutex a, B & mutex b) {
759                accept(f); //ambiguous, which monitor
760        }
761\end{cfacode}
762
763The obvious solution is to specify the correct monitor as follows:
764
765\begin{cfacode}
766        accept( void f(mutex struct A & mutex this))
767        mutex struct A {};
768
769        mutex struct B {};
770
771        void g(A & mutex a, B & mutex b) {
772                accept( b, f );
773        }
774\end{cfacode}
775
776This 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.
777
778\begin{cfacode}
779        accept( void f(mutex struct A & mutex, mutex struct A & mutex))
780        mutex struct A {};
781
782        mutex struct B {};
783
784        void g(A & mutex a, B & mutex b) {
785                accept( b, a, f);
786        }
787\end{cfacode}
788
789Note 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.
790
791% ======================================================================
792% ======================================================================
793\subsection{Implementation Details: External scheduling queues}
794% ======================================================================
795% ======================================================================
796To 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.
797
798% ======================================================================
799% ======================================================================
800\section{Other concurrency tools}
801% ======================================================================
802% ======================================================================
803% \TODO
Note: See TracBrowser for help on using the repository browser.