source: doc/proposals/concurrency/text/concurrency.tex @ 7c17511

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 7c17511 was 7c17511, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

More work on the basics section

  • Property mode set to 100644
File size: 43.6 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. While this distinction can be hidden away in library code, effective use of the librairy still has to take both paradigms into account.
7
8Approaches 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 the lowest level, concurrent paradigms are implemented as atomic operations and locks. 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}.
9
10An 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 be the main concurrency paradigm for general purpose language, which is why it was rejected as the core paradigm for concurrency in \CFA.
11
12One 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.
13
14\section{Basics}
15Non-determinism requires concurrent systems to offer 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 a group of instructions on an associated portion of data that requires the restricted access. On the other hand, synchronization enforces relative ordering of execution and synchronization tools numerous mechanisms to establish timing relationships among threads.
16
17\subsection{Mutual-Exclusion}
18As 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. Ease of use comes 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 operations (.e.g: reading/writing large types atomically). Another challenge with low-level locks is composability. Locks are not composable because it takes careful organising for multiple locks to be used while preventing deadlocks. Easing composability is another feature higher-level mutual-exclusion mechanisms often offer.
19
20\subsection{Synchronization}
21As for mutual-exclusion, low level synchronisation primitive often offer good 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, .eg., 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.
22
23% ======================================================================
24% ======================================================================
25\section{Monitors}
26% ======================================================================
27% ======================================================================
28A 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 OO semantics. The only requirements is the ability to declare a handle to a shared object and a set of routines that act on it :
29\begin{cfacode}
30        typedef /*some monitor type*/ monitor;
31        int f(monitor & m);
32
33        int main() {
34                monitor m;  //Handle m
35                f(m);       //Routine using handle
36        }
37\end{cfacode}
38
39% ======================================================================
40% ======================================================================
41\subsection{Call semantics} \label{call}
42% ======================================================================
43% ======================================================================
44The above monitor example displays some of the intrinsic characteristics. First, 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 objects.
45
46Another 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 occur for generic helper routines (\code{swap}, \code{sort}, etc.) or specific helper routines like the following to implement an atomic counter :
47
48\begin{cfacode}
49        monitor counter_t { /*...see section $\ref{data}$...*/ };
50
51        void ?{}(counter_t & nomutex this); //constructor
52        size_t ++?(counter_t & mutex this); //increment
53
54        //need for mutex is platform dependent
55        void ?{}(size_t * this, counter_t & mutex cnt); //conversion
56\end{cfacode}
57
58Here, 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.
59
60Having both \code{mutex} and \code{nomutex} keywords is 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}, whereas assuming \code{nomutex} is unsafe and may 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.
61
62
63The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
64\begin{cfacode}
65int f1(monitor & mutex m);
66int f2(const monitor & mutex m);
67int f3(monitor ** mutex m);
68int f4(monitor * mutex m []);
69int f5(graph(monitor*) & mutex m);
70\end{cfacode}
71The 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:
72
73\begin{cfacode}
74int f1(monitor & mutex m);   //Okay : recommanded case
75int f2(monitor * mutex m);   //Okay : could be an array but probably not
76int f3(monitor mutex m []);  //Not Okay : Array of unkown length
77int f4(monitor ** mutex m);  //Not Okay : Could be an array
78int f5(monitor * mutex m []); //Not Okay : Array of unkown length
79\end{cfacode}
80
81Unlike 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.
82\begin{cfacode}
83int f(MonitorA & mutex a, MonitorB & mutex b);
84
85MonitorA a;
86MonitorB b;
87f(a,b);
88\end{cfacode}
89The 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:
90\begin{cfacode}
91        void foo(A & mutex a, B & mutex b) { //acquire a & b
92                ...
93        }
94
95        void bar(A & mutex a, B & /*nomutex*/ b) { //acquire a
96                ... foo(a, b); ... //acquire b
97        }
98
99        void baz(A & /*nomutex*/ a, B & mutex b) { //acquire b
100                ... foo(a, b); ... //acquire a
101        }
102\end{cfacode}
103The 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.
104
105However, 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:
106\begin{enumerate}
107        \item Dynamically tracking of the monitor-call order.
108        \item Implement rollback semantics.
109\end{enumerate}
110While 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.
111
112Finally, 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:
113\begin{cfacode}
114monitor bank {
115        int money;
116        log_t usr_log;
117};
118
119void deposit( bank & mutex b, int deposit ) {
120        b.money += deposit;
121        b.usr_log | "Adding" | deposit | endl;
122}
123
124void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) {
125        deposit( mybank, -me2you );
126        deposit( yourbank, me2you );
127}
128\end{cfacode}
129
130% ======================================================================
131% ======================================================================
132\subsection{Data semantics} \label{data}
133% ======================================================================
134% ======================================================================
135Once 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}:
136\begin{cfacode}
137monitor counter_t {
138        int value;
139};
140
141void ?{}(counter_t & this) {
142        this.cnt = 0;
143}
144
145int ?++(counter_t & mutex this) {
146        return ++this.value;
147}
148
149//need for mutex is platform dependent here
150void ?{}(int * this, counter_t & mutex cnt) {
151        *this = (int)cnt;
152}
153\end{cfacode}
154
155This counter is used as follows:
156\begin{center}
157\begin{tabular}{c @{\hskip 0.35in} c @{\hskip 0.35in} c}
158\begin{cfacode}
159//shared counter
160counter_t cnt1, cnt2;
161
162//multiple threads access counter
163thread 1 : cnt1++; cnt2++;
164thread 2 : cnt1++; cnt2++;
165thread 3 : cnt1++; cnt2++;
166        ...
167thread N : cnt1++; cnt2++;
168\end{cfacode}
169\end{tabular}
170\end{center}
171Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting.
172
173% ======================================================================
174% ======================================================================
175\subsection{Implementation Details: Interaction with polymorphism}
176% ======================================================================
177% ======================================================================
178Depending 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.
179
180First 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.
181
182Before 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:
183\begin{center}
184\setlength\tabcolsep{1.5pt}
185\begin{tabular}{|c|c|c|}
186Code & \gls{callsite-locking} & \gls{entry-point-locking} \\
187\CFA & pseudo-code & pseudo-code \\
188\hline
189\begin{cfacode}[tabsize=3]
190void foo(monitor& mutex a){
191
192
193
194        //Do Work
195        //...
196
197}
198
199void main() {
200        monitor a;
201
202
203
204        foo(a);
205
206}
207\end{cfacode} & \begin{pseudo}[tabsize=3]
208foo(& a) {
209
210
211
212        //Do Work
213        //...
214
215}
216
217main() {
218        monitor a;
219        //calling routine
220        //handles concurrency
221        acquire(a);
222        foo(a);
223        release(a);
224}
225\end{pseudo} & \begin{pseudo}[tabsize=3]
226foo(& a) {
227        //called routine
228        //handles concurrency
229        acquire(a);
230        //Do Work
231        //...
232        release(a);
233}
234
235main() {
236        monitor a;
237
238
239
240        foo(a);
241
242}
243\end{pseudo}
244\end{tabular}
245\end{center}
246
247\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:
248\begin{cfacode}
249//Incorrect
250//T is not a monitor
251forall(dtype T)
252void foo(T * mutex t);
253
254//Correct
255//this function only works on monitors
256//(any monitor)
257forall(dtype T | is_monitor(T))
258void bar(T * mutex t));
259\end{cfacode}
260
261
262% ======================================================================
263% ======================================================================
264\section{Internal scheduling} \label{insched}
265% ======================================================================
266% ======================================================================
267In 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.
268
269First, Here is a simple example of such a technique:
270
271\begin{cfacode}
272        monitor A {
273                condition e;
274        }
275
276        void foo(A & mutex a) {
277                ...
278                // Wait for cooperation from bar()
279                wait(a.e);
280                ...
281        }
282
283        void bar(A & mutex a) {
284                // Provide cooperation for foo()
285                ...
286                // Unblock foo at scope exit
287                signal(a.e);
288        }
289\end{cfacode}
290
291There 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.
292
293An 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.
294
295% ======================================================================
296% ======================================================================
297\subsection{Internal Scheduling - multi monitor}
298% ======================================================================
299% ======================================================================
300It 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.
301
302\begin{multicols}{2}
303thread 1
304\begin{pseudo}
305acquire A
306        wait A
307release A
308\end{pseudo}
309
310\columnbreak
311
312thread 2
313\begin{pseudo}
314acquire A
315        signal A
316release A
317\end{pseudo}
318\end{multicols}
319
320The 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.
321
322A direct extension of the previous example is the \gls{group-acquire} version:
323
324\begin{multicols}{2}
325\begin{pseudo}
326acquire A & B
327        wait A & B
328release A & B
329\end{pseudo}
330
331\columnbreak
332
333\begin{pseudo}
334acquire A & B
335        signal A & B
336release A & B
337\end{pseudo}
338\end{multicols}
339
340This 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.
341
342While 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.
343
344\begin{multicols}{2}
345\begin{pseudo}
346acquire A
347        acquire B
348                wait B
349        release B
350release A
351\end{pseudo}
352
353\columnbreak
354
355\begin{pseudo}
356
357acquire B
358        signal B
359release B
360
361\end{pseudo}
362\end{multicols}
363
364The next example is where \gls{group-acquire} adds a significant layer of complexity to the internal signalling semantics.
365
366\begin{multicols}{2}
367Waiting thread
368\begin{pseudo}[numbers=left]
369acquire A
370        // Code Section 1
371        acquire A & B
372                // Code Section 2
373                wait A & B
374                // Code Section 3
375        release A & B
376        // Code Section 4
377release A
378\end{pseudo}
379
380\columnbreak
381
382Signalling thread
383\begin{pseudo}[numbers=left, firstnumber=10]
384acquire A
385        // Code Section 5
386        acquire A & B
387                // Code Section 6
388                signal A & B
389                // Code Section 7
390        release A & B
391        // Code Section 8
392release A
393\end{pseudo}
394\end{multicols}
395\begin{center}
396Listing 1
397\end{center}
398
399It 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:
400
401\subsubsection{Delaying signals}
402The 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.
403\begin{multicols}{2}
404Waiter
405\begin{pseudo}[numbers=left]
406acquire A
407        acquire A & B
408                wait A & B
409        release A & B
410release A
411\end{pseudo}
412
413\columnbreak
414
415Signaller
416\begin{pseudo}[numbers=left, firstnumber=6]
417acquire A
418        acquire A & B
419                signal A & B
420        release A & B
421        //Secretly keep B here
422release A
423//Wakeup waiter and transfer A & B
424\end{pseudo}
425\end{multicols}
426However, 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:
427\newpage
428\begin{multicols}{2}
429Thread 1
430\begin{pseudo}[numbers=left, firstnumber=1]
431acquire A
432        acquire A & B
433                wait A & B
434        release A & B
435release A
436\end{pseudo}
437
438Thread 2
439\begin{pseudo}[numbers=left, firstnumber=6]
440acquire A
441        wait A
442release A
443\end{pseudo}
444
445\columnbreak
446
447Thread 3
448\begin{pseudo}[numbers=left, firstnumber=10]
449acquire A
450        acquire A & B
451                signal A & B
452        release A & B
453        //Secretly keep B here
454        signal A
455release A
456//Wakeup thread 1 or 2?
457//Who wakes up the other thread?
458\end{pseudo}
459\end{multicols}
460
461The 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.
462
463\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.
464\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.
465\\
466
467In 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.
468
469\subsubsection{Dependency graphs}
470In 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:
471
472\begin{multicols}{2}
473\begin{pseudo}
474acquire A
475        acquire B
476                acquire C
477                        wait A & B & C
478                release C
479        release B
480release A
481\end{pseudo}
482
483\columnbreak
484
485\begin{pseudo}
486acquire A
487        acquire B
488                acquire C
489                        signal A & B & C
490                release C
491        release B
492release A
493\end{pseudo}
494\end{multicols}
495Resolving dependency graph being a complex and expensive endeavour, this solution is not the preffered one.
496
497\subsubsection{Partial signalling}
498Finally, the solution that was chosen for \CFA is to use partial signalling. Consider the following case:
499
500\begin{multicols}{2}
501\begin{pseudo}[numbers=left]
502acquire A
503        acquire A & B
504                wait A & B
505        release A & B
506release A
507\end{pseudo}
508
509\columnbreak
510
511\begin{pseudo}[numbers=left, firstnumber=6]
512acquire A
513        acquire A & B
514                signal A & B
515        release A & B
516        // ... More code
517release A
518\end{pseudo}
519\end{multicols}
520
521The 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.
522
523% ======================================================================
524% ======================================================================
525\subsection{Signalling: Now or Later}
526% ======================================================================
527% ======================================================================
528An 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}.
529
530For example here is an example highlighting the difference in behaviour:
531\begin{center}
532\begin{tabular}{|c|c|}
533\code{signal} & \code{signal_block} \\
534\hline
535\begin{cfacode}
536monitor M { int val; };
537
538void foo(M & mutex m ) {
539        m.val++;
540        sout| "Foo:" | m.val |endl;
541
542        wait( c );
543
544        m.val++;
545        sout| "Foo:" | m.val |endl;
546}
547
548void bar(M & mutex m ) {
549        m.val++;
550        sout| "Bar:" | m.val |endl;
551
552        signal( c );
553
554        m.val++;
555        sout| "Bar:" | m.val |endl;
556}
557\end{cfacode}&\begin{cfacode}
558monitor M { int val; };
559
560void foo(M & mutex m ) {
561        m.val++;
562        sout| "Foo:" | m.val |endl;
563
564        wait( c );
565
566        m.val++;
567        sout| "Foo:" | m.val |endl;
568}
569
570void bar(M & mutex m ) {
571        m.val++;
572        sout| "Bar:" | m.val |endl;
573
574        signal_block( c );
575
576        m.val++;
577        sout| "Bar:" | m.val |endl;
578}
579\end{cfacode}
580\end{tabular}
581\end{center}
582Assuming 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:
583
584\begin{center}
585\begin{tabular}{|c|c|}
586\code{signal} & \code{signal_block} \\
587\hline
588\begin{pseudo}
589Foo: 0
590Bar: 1
591Bar: 2
592Foo: 3
593\end{pseudo}&\begin{pseudo}
594Foo: 0
595Bar: 1
596Foo: 2
597Bar: 3
598\end{pseudo}
599\end{tabular}
600\end{center}
601
602As 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.
603
604% ======================================================================
605% ======================================================================
606\subsection{Internal scheduling: Implementation} \label{insched-impl}
607% ======================================================================
608% ======================================================================
609\TODO
610
611
612% ======================================================================
613% ======================================================================
614\section{External scheduling} \label{extsched}
615% ======================================================================
616% ======================================================================
617An alternative to internal scheduling is to use external scheduling.
618\begin{center}
619\begin{tabular}{|c|c|}
620Internal Scheduling & External Scheduling \\
621\hline
622\begin{ucppcode}
623_Monitor Semaphore {
624        condition c;
625        bool inUse;
626public:
627        void P() { 
628                if(inUse) wait(c);
629                inUse = true;
630        }
631        void V() { 
632                inUse = false;         
633                signal(c);
634        }
635}
636\end{ucppcode}&\begin{ucppcode}
637_Monitor Semaphore {
638
639        bool inUse;
640public:
641        void P() { 
642                if(inUse) _Accept(V);
643                inUse = true;
644        }
645        void g() { 
646                inUse = false;
647
648        }
649}
650\end{ucppcode}
651\end{tabular}
652\end{center}
653This 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.
654
655In 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.
656
657% ======================================================================
658% ======================================================================
659\subsection{Loose object definitions}
660% ======================================================================
661% ======================================================================
662In \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:
663
664\begin{cfacode}
665        monitor A {};
666
667        void f(A & mutex a);
668        void g(A & mutex a) { accept(f); }
669\end{cfacode}
670
671However, 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:
672
673\begin{center}
674\begin{tabular}{l}
675\begin{pseudo}
676        if monitor is free
677                enter
678        elif monitor accepts me
679                enter
680        else
681                block
682\end{pseudo}
683\end{tabular}
684\end{center}
685
686For 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:
687
688\begin{center}
689{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
690\end{center}
691
692There 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.
693The alternative would be to have a picture more like this one:
694
695\begin{center}
696{\resizebox{0.4\textwidth}{!}{\input{ext_monitor}}}
697\end{center}
698
699Not 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.
700
701At 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.
702
703In either cases here are a few alternatives for the different syntaxes this syntax : \\
704\begin{center}
705{\renewcommand{\arraystretch}{1.5}
706\begin{tabular}[t]{l @{\hskip 0.35in} l}
707\hline
708\multicolumn{2}{ c }{\code{accept} on type}\\
709\hline
710Alternative 1 & Alternative 2 \\
711\begin{lstlisting}
712mutex struct A
713accept( void f(A & mutex a) )
714{};
715\end{lstlisting} &\begin{lstlisting}
716mutex struct A {}
717accept( void f(A & mutex a) );
718
719\end{lstlisting} \\
720Alternative 3 & Alternative 4 \\
721\begin{lstlisting}
722mutex struct A {
723        accept( void f(A & mutex a) )
724};
725
726\end{lstlisting} &\begin{lstlisting}
727mutex struct A {
728        accept :
729                void f(A & mutex a) );
730};
731\end{lstlisting}\\
732\hline
733\multicolumn{2}{ c }{\code{accept} on routine}\\
734\hline
735\begin{lstlisting}
736mutex struct A {};
737
738void f(A & mutex a)
739
740accept( void f(A & mutex a) )
741void g(A & mutex a) {
742        /*...*/
743}
744\end{lstlisting}&\\
745\end{tabular}
746}
747\end{center}
748
749Another 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.
750
751% ======================================================================
752% ======================================================================
753\subsection{Multi-monitor scheduling}
754% ======================================================================
755% ======================================================================
756
757External 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:
758\begin{cfacode}
759        accept( void f(mutex struct A & mutex this))
760        mutex struct A {};
761
762        mutex struct B {};
763
764        void g(A & mutex a, B & mutex b) {
765                accept(f); //ambiguous, which monitor
766        }
767\end{cfacode}
768
769The obvious solution is to specify the correct monitor as follows:
770
771\begin{cfacode}
772        accept( void f(mutex struct A & mutex this))
773        mutex struct A {};
774
775        mutex struct B {};
776
777        void g(A & mutex a, B & mutex b) {
778                accept( b, f );
779        }
780\end{cfacode}
781
782This 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.
783
784\begin{cfacode}
785        accept( void f(mutex struct A & mutex, mutex struct A & mutex))
786        mutex struct A {};
787
788        mutex struct B {};
789
790        void g(A & mutex a, B & mutex b) {
791                accept( b, a, f);
792        }
793\end{cfacode}
794
795Note 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.
796
797% ======================================================================
798% ======================================================================
799\subsection{Implementation Details: External scheduling queues}
800% ======================================================================
801% ======================================================================
802To 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.
803
804% ======================================================================
805% ======================================================================
806\section{Other concurrency tools}
807% ======================================================================
808% ======================================================================
809% \TODO
Note: See TracBrowser for help on using the repository browser.