# source:doc/proposals/concurrency/text/concurrency.tex@3364962

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

Updated concurrency draft and added new section for implementation.

• Property mode set to 100644
File size: 42.3 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 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 systems 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 provide 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 solutions exist 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>} offers 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 have restricted composability 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 primitives 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, e.g.: message passing, or offering simple solution to otherwise involved challenges. An example is barging. As mentioned 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 must acquire critical sections in a certain order. However, it may also be desirable to guarantee that event \textit{Z} does not occur between \textit{X} and \textit{Y}. Not satisfying this property called barging. For example, where event \textit{X} tries to effect event \textit{Y} but another thread acquires 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. This challenge is often split into two different methods, barging avoidance and barging prevention. Algorithms that use status flags and other flag variables to detect barging threads are said to be using barging avoidance while algorithms that baton-passing locks between threads instead of releasing the locks are said to be using barging prevention.
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}
57This counter is used as follows:
58\begin{center}
59\begin{tabular}{c @{\hskip 0.35in} c @{\hskip 0.35in} c}
60\begin{cfacode}
61//shared counter
62counter_t cnt1, cnt2;
63
68        ...
70\end{cfacode}
71\end{tabular}
72\end{center}
73Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting.
74
75Here, 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 a \code{size_t} is an atomic operation.
76
77For maximum usability, monitors use \gls{multi-acq} semantics, which means a single thread can acquire multiple times the same monitor without deadlock. For example, figure \ref{fig:search} uses recursion and \gls{multi-acq} to print values inside a binary tree.
78\begin{figure}
79\label{fig:search}
80\begin{cfacode}
81monitor printer { ... };
82struct tree {
83        tree * left, right;
84        char * value;
85};
86void print(printer & mutex p, char * v);
87
88void print(printer & mutex p, tree * t) {
89        print(p, t->value);
90        print(p, t->left );
91        print(p, t->right);
92}
93\end{cfacode}
94\caption{Recursive printing algorithm using \gls{multi-acq}.}
95\end{figure}
96
97Having 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 making exactly one of these keywords mandatory, which would provide the same semantics but without the ambiguity of supporting routines with 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 doubt whether 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 and uses no keyword to mean \code{nomutex}.
98
99The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
100\begin{cfacode}
101int f1(monitor & mutex m);
102int f2(const monitor & mutex m);
103int f3(monitor ** mutex m);
104int f4(monitor * mutex m []);
105int f5(graph(monitor*) & mutex m);
106\end{cfacode}
107The 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 problem can be extended to absurd limits like \code{f5}, which uses a graph of monitors. To make the issue tractable, this project imposes the requirement that a routine may only acquire one monitor per parameter and it must be the type of the parameter with at most 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. 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:
108\begin{cfacode}
109int f1(monitor & mutex m);   //Okay : recommanded case
110int f2(monitor * mutex m);   //Okay : could be an array but probably not
111int f3(monitor mutex m []);  //Not Okay : Array of unkown length
112int f4(monitor ** mutex m);  //Not Okay : Could be an array
113int f5(monitor * mutex m []); //Not Okay : Array of unkown length
114\end{cfacode}
115Note that not all array functions are actually distinct in the type system sense. However, even the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
116
117Unlike object-oriented monitors, where calling a mutex member \emph{implicitly} acquires mutual-exclusion often receives an object, \CFA uses an explicit mechanism to acquire mutual-exclusion. A consequence of this approach is that it extends naturally to multi-monitor calls.
118\begin{cfacode}
119int f(MonitorA & mutex a, MonitorB & mutex b);
120
121MonitorA a;
122MonitorB b;
123f(a,b);
124\end{cfacode}
125The capacity to acquire multiple locks before entering a critical section is called \emph{\gls{bulk-acq}}. 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 \gls{multi-acq} locks, users can effectively force the acquiring order. For example, notice which routines use \code{mutex}/\code{nomutex} and how this affects aquiring order:
126\begin{cfacode}
127        void foo(A & mutex a, B & mutex b) { //acquire a & b
128                ...
129        }
130
131        void bar(A & mutex a, B & /*nomutex*/ b) { //acquire a
132                ... foo(a, b); ... //acquire b
133        }
134
135        void baz(A & /*nomutex*/ a, B & mutex b) { //acquire b
136                ... foo(a, b); ... //acquire a
137        }
138\end{cfacode}
139The \gls{multi-acq} 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.
140
141However, such use leads to 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:
142\begin{enumerate}
143        \item Dynamically tracking of the monitor-call order.
144        \item Implement rollback semantics.
145\end{enumerate}
146While 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 or only use \gls{bulk-acq} of all the monitors.
147
148\Gls{multi-acq} and \gls{bulk-acq} can be used together in interesting ways, for example:
149\begin{cfacode}
150monitor bank { ... };
151
152void deposit( bank & mutex b, int deposit );
153
154void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) {
155        deposit( mybank, -me2you );
156        deposit( yourbank, me2you );
157}
158\end{cfacode}
159This example shows a trivial solution to the bank account transfer problem\cit. Without \gls{multi-acq} and \gls{bulk-acq}, the solution to this problem is much more involved and requires carefull engineering.
160
161% ======================================================================
162% ======================================================================
163\subsection{Data semantics} \label{data}
164% ======================================================================
165% ======================================================================
166Once 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}:
167\begin{cfacode}
168monitor counter_t {
169        int value;
170};
171
172void ?{}(counter_t & this) {
173        this.cnt = 0;
174}
175
176int ?++(counter_t & mutex this) {
177        return ++this.value;
178}
179
180//need for mutex is platform dependent here
181void ?{}(int * this, counter_t & mutex cnt) {
182        *this = (int)cnt;
183}
184\end{cfacode}
185
186
187% ======================================================================
188% ======================================================================
189\section{Internal scheduling} \label{insched}
190% ======================================================================
191% ======================================================================
192In addition to mutual exclusion, the monitors at the core of \CFA's concurrency can also be used to achieve synchronisation. With monitors, this capability is generally achieved with internal or external scheduling as in\cit. Since internal scheduling within a single monitor is mostly a solved problem, this thesis concentrates on extending internal scheduling to multiple monitors. Indeed, like the \gls{bulk-acq} semantics, internal scheduling extends to multiple monitors in a way that is natural to the user but requires additional complexity on the implementation side.
193
194First, here is a simple example of such a technique:
195
196\begin{cfacode}
197        monitor A {
198                condition e;
199        }
200
201        void foo(A & mutex a) {
202                ...
203                //Wait for cooperation from bar()
204                wait(a.e);
205                ...
206        }
207
208        void bar(A & mutex a) {
209                //Provide cooperation for foo()
210                ...
211                //Unblock foo
212                signal(a.e);
213        }
214\end{cfacode}
215
216There are two details to note here. First, the \code{signal} is a delayed operation, it only unblocks the waiting thread when it reaches the end of the critical section. This semantic is needed to respect mutual-exclusion. Second, in \CFA, a \code{condition} variable can be stored/created independently of a monitor. Here routine \code{foo} waits for the \code{signal} from \code{bar} before making further progress, effectively ensuring a basic ordering.
217
218An important aspect of the implementation 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.
219
220% ======================================================================
221% ======================================================================
222\subsection{Internal Scheduling - multi monitor}
223% ======================================================================
224% ======================================================================
225It is 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.
226
227\begin{multicols}{2}
229\begin{pseudo}
230acquire A
231        wait A
232release A
233\end{pseudo}
234
235\columnbreak
236
238\begin{pseudo}
239acquire A
240        signal A
241release A
242\end{pseudo}
243\end{multicols}
244The 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. It is important to note here that both \code{wait} and \code{signal} must be called with the proper monitor(s) already acquired. This semantic is a logical requirement for barging prevention.
245
246A direct extension of the previous example is a \gls{bulk-acq} version:
247
248\begin{multicols}{2}
249\begin{pseudo}
250acquire A & B
251        wait A & B
252release A & B
253\end{pseudo}
254
255\columnbreak
256
257\begin{pseudo}
258acquire A & B
259        signal A & B
260release A & B
261\end{pseudo}
262\end{multicols}
263This version uses \gls{bulk-acq} (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.
264
265While 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. For monitors, a well known deadlock problem is the Nested Monitor Problem\cit, which occurs when a \code{wait} is made on a thread that holds more than one monitor. For example, the following pseudo-code will run into the nested monitor problem :
266\begin{multicols}{2}
267\begin{pseudo}
268acquire A
269        acquire B
270                wait B
271        release B
272release A
273\end{pseudo}
274
275\columnbreak
276
277\begin{pseudo}
278acquire A
279        acquire B
280                signal B
281        release B
282release A
283\end{pseudo}
284\end{multicols}
285However, for monitors as for locks, it is possible to write a program using nesting without encountering any problems if nesting is done correctly. For example, the next pseudo-code snippet acquires monitors {\sf A} then {\sf B} before waiting, while only acquiring {\sf B} when signalling, effectively avoiding the nested monitor problem.
286
287\begin{multicols}{2}
288\begin{pseudo}
289acquire A
290        acquire B
291                wait B
292        release B
293release A
294\end{pseudo}
295
296\columnbreak
297
298\begin{pseudo}
299
300acquire B
301        signal B
302release B
303
304\end{pseudo}
305\end{multicols}
306
307The next example is where \gls{bulk-acq} adds a significant layer of complexity to the internal signalling semantics.
308
309\begin{multicols}{2}
311\begin{pseudo}[numbers=left]
312acquire A
313        //Code Section 1
314        acquire A & B
315                //Code Section 2
316                wait A & B
317                //Code Section 3
318        release A & B
319        //Code Section 4
320release A
321\end{pseudo}
322
323\columnbreak
324
326\begin{pseudo}[numbers=left, firstnumber=10]
327acquire A
328        //Code Section 5
329        acquire A & B
330                //Code Section 6
331                signal A & B
332                //Code Section 7
333        release A & B
334        //Code Section 8
335release A
336\end{pseudo}
337\end{multicols}
338\begin{center}
339Listing 1
340\end{center}
341
342It is particularly important to pay attention to code sections 4 and 8, which are where the existing semantics of internal scheduling need to be extended for multiple monitors. The root of the problem is that \gls{bulk-acq} 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 16), 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 monitor A, simply waking up the waiting thread is not an option because it would violate mutual exclusion. There are three options.
343
344\subsubsection{Delaying signals}
345The 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 because this semantics 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 group of objects, effectively making the existing single monitor semantic viable by simply changing monitors to monitor groups.
346\begin{multicols}{2}
347Waiter
348\begin{pseudo}[numbers=left]
349acquire A
350        acquire A & B
351                wait A & B
352        release A & B
353release A
354\end{pseudo}
355
356\columnbreak
357
358Signaller
359\begin{pseudo}[numbers=left, firstnumber=6]
360acquire A
361        acquire A & B
362                signal A & B
363        release A & B
364        //Secretly keep B here
365release A
366//Wakeup waiter and transfer A & B
367\end{pseudo}
368\end{multicols}
369However, this solution can become much more complicated depending on what is executed while secretly holding B (at line 10). Indeed, nothing prevents signalling monitor A on a different condition variable:
370\begin{multicols}{2}
372\begin{pseudo}[numbers=left, firstnumber=1]
373acquire A
374        acquire A & B
375                wait A & B
376        release A & B
377release A
378\end{pseudo}
379
381\begin{pseudo}[numbers=left, firstnumber=6]
382acquire A
383        wait A
384release A
385\end{pseudo}
386
387\columnbreak
388
390\begin{pseudo}[numbers=left, firstnumber=10]
391acquire A
392        acquire A & B
393                signal A & B
394        release A & B
395        //Secretly keep B here
396        signal A
397release A
399//Who wakes up the other thread?
400\end{pseudo}
401\end{multicols}
402
403The 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.
404
405\paragraph{Case 1: thread 1 goes first.} In this case, the problem is that monitor A needs to be passed to thread 2 when thread 1 is done with it.
406\paragraph{Case 2: thread 2 goes first.} In this case, the problem is that monitor B needs to be passed to thread 1, which can be done directly or using thread 2 as an intermediate.
407\\
408
409Note 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.
410
411In both cases, 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 and therefore invalidates the main benefit of this approach.
412
413\subsubsection{Dependency graphs}
414In the Listing 1 pseudo-code, there is a solution which statisfies 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:
415
416\begin{multicols}{2}
417\begin{pseudo}
418acquire A
419        acquire B
420                acquire C
421                        wait A & B & C
422                release C
423        release B
424release A
425\end{pseudo}
426
427\columnbreak
428
429\begin{pseudo}
430acquire A
431        acquire B
432                acquire C
433                        signal A & B & C
434                release C
435        release B
436release A
437\end{pseudo}
438\end{multicols}
439
440\begin{figure}
441\begin{multicols}{3}
442Thread $\alpha$
443\begin{pseudo}[numbers=left, firstnumber=1]
444acquire A
445        acquire A & B
446                wait A & B
447        release A & B
448release A
449\end{pseudo}
450
451\columnbreak
452
453Thread $\gamma$
454\begin{pseudo}[numbers=left, firstnumber=1]
455acquire A
456        acquire A & B
457                signal A & B
458        release A & B
459        signal A
460release A
461\end{pseudo}
462
463\columnbreak
464
465Thread $\beta$
466\begin{pseudo}[numbers=left, firstnumber=1]
467acquire A
468        wait A
469release A
470\end{pseudo}
471
472\end{multicols}
473\caption{Dependency graph}
474\label{lst:dependency}
475\end{figure}
476
477\begin{figure}
478\begin{center}
479\input{dependency}
480\end{center}
481\label{fig:dependency}
482\caption{Dependency graph of the statments in listing \ref{lst:dependency}}
483\end{figure}
484
485Listing \ref{lst:dependency} is the three thread example rewritten for dependency graphs as well as the corresponding dependency graph. Figure \ref{fig:dependency} shows the corresponding dependency graph that results, where every node is a statment of one of the three threads, and the arrows the dependency of that statment. The extra challenge is that this dependency graph is effectively post-mortem, but the run time system needs to be able to build and solve these graphs as the dependency unfolds. Resolving dependency graph being a complex and expensive endeavour, this solution is not the preffered one.
486
487\subsubsection{Partial signalling} \label{partial-sig}
488Finally, the solution that is chosen for \CFA is to use partial signalling. Consider the following case:
489
490\begin{multicols}{2}
491\begin{pseudo}[numbers=left]
492acquire A
493        acquire A & B
494                wait A & B
495        release A & B
496release A
497\end{pseudo}
498
499\columnbreak
500
501\begin{pseudo}[numbers=left, firstnumber=6]
502acquire A
503        acquire A & B
504                signal A & B
505        release A & B
506        //... More code
507release A
508\end{pseudo}
509\end{multicols}
510The 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 into only two actions, passing monitors to the next owner when they should be release and conditionally waking threads if all conditions are met. This solution has a much simpler implementation than a dependency graph solving algorithm which is why it was chosen.
511
512% ======================================================================
513% ======================================================================
514\subsection{Signalling: Now or Later}
515% ======================================================================
516% ======================================================================
517An 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, which is achieved using the \code{signal_block} routine\footnote{name to be discussed}.
518
519The example in listing \ref{lst:datingservice} highlights the difference in behaviour. As mentioned, \code{signal} only transfers ownership once the current critical section exits, this behaviour cause the need for additional synchronisation when a two-way handshake is needed. To avoid this extraneous synchronisation, the \code{condition} type offers the \code{signal_block} routine which handle two-way handshakes as shown in the example. This removes the need for a second condition variables and simplifies programming. Like every other monitor semantic, \code{signal_block} uses barging prevention which means mutual-exclusion is baton-passed both on the frond-end and the back-end of the call to \code{signal_block}, meaning no other thread can acquire the monitor neither before nor after the call.
520\begin{figure}
521\begin{tabular}{|c|c|}
522\code{signal} & \code{signal_block} \\
523\hline
524\begin{cfacode}[tabsize=3]
525monitor DatingService
526{
527        //compatibility codes
528        enum{ CCodes = 20 };
529
530        int girlPhoneNo
531        int boyPhoneNo;
532};
533
534condition girls[CCodes];
535condition boys [CCodes];
536condition exchange;
537
538int girl(int phoneNo, int ccode)
539{
540        //no compatible boy ?
541        if(empty(boys[ccode]))
542        {
543                //wait for boy
544                wait(girls[ccode]);
545
546                //make phone number available
547                girlPhoneNo = phoneNo;
548
549                //wake boy fron chair
550                signal(exchange);
551        }
552        else
553        {
554                //make phone number available
555                girlPhoneNo = phoneNo;
556
557                //wake boy
558                signal(boys[ccode]);
559
560                //sit in chair
561                wait(exchange);
562        }
563        return boyPhoneNo;
564}
565
566int boy(int phoneNo, int ccode)
567{
568        //same as above
569        //with boy/girl interchanged
570}
571\end{cfacode}&\begin{cfacode}[tabsize=3]
572monitor DatingService
573{
574        //compatibility codes
575        enum{ CCodes = 20 };
576
577        int girlPhoneNo;
578        int boyPhoneNo;
579};
580
581condition girls[CCodes];
582condition boys [CCodes];
583//exchange is not needed
584
585int girl(int phoneNo, int ccode)
586{
587        //no compatible boy ?
588        if(empty(boys[ccode]))
589        {
590                //wait for boy
591                wait(girls[ccode]);
592
593                //make phone number available
594                girlPhoneNo = phoneNo;
595
596                //wake boy fron chair
597                signal(exchange);
598        }
599        else
600        {
601                //make phone number available
602                girlPhoneNo = phoneNo;
603
604                //wake boy
605                signal_block(boys[ccode]);
606
607                //second handshake unnecessary
608
609        }
610        return boyPhoneNo;
611}
612
613int boy(int phoneNo, int ccode)
614{
615        //same as above
616        //with boy/girl interchanged
617}
618\end{cfacode}
619\end{tabular}
620\caption{Dating service example using \code{signal} and \code{signal_block}. }
621\label{lst:datingservice}
622\end{figure}
623
624% ======================================================================
625% ======================================================================
626\section{External scheduling} \label{extsched}
627% ======================================================================
628% ======================================================================
629An alternative to internal scheduling is to use external scheduling.
630\begin{center}
631\begin{tabular}{|c|c|}
632Internal Scheduling & External Scheduling \\
633\hline
634\begin{ucppcode}
635_Monitor Semaphore {
636        condition c;
637        bool inUse;
638public:
639        void P() {
640                if(inUse) wait(c);
641                inUse = true;
642        }
643        void V() {
644                inUse = false;
645                signal(c);
646        }
647}
648\end{ucppcode}&\begin{ucppcode}
649_Monitor Semaphore {
650
651        bool inUse;
652public:
653        void P() {
654                if(inUse) _Accept(V);
655                inUse = true;
656        }
657        void V() {
658                inUse = false;
659
660        }
661}
662\end{ucppcode}
663\end{tabular}
664\end{center}
665This method is more constrained and explicit, which helps 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 with \code{_Accept}) or in terms of data (e.g. Go with channels). Of course, both of these paradigms have their own strenghts and weaknesses but for this project control-flow semantics were 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 previous example shows a simple use \code{_Accept} versus \code{wait}/\code{signal} and its advantages. Note that while other languages often use \code{accept}/\code{select} as the core external scheduling keyword, \CFA uses \code{waitfor} to prevent name collisions with existing socket \acrshort{api}s.
666
667In the case of internal scheduling, the call to \code{wait} only guarantees that \code{V} is the last routine to access the monitor. This entails that a third routine, say \code{isInUse()}, may have acquired mutual exclusion several times while routine \code{P} was waiting. On the other hand, external scheduling guarantees that while routine \code{P} was waiting, no routine other than \code{V} could acquire the monitor.
668
669% ======================================================================
670% ======================================================================
671\subsection{Loose object definitions}
672% ======================================================================
673% ======================================================================
674In \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:
675
676\begin{cfacode}
677        monitor A {};
678
679        void f(A & mutex a);
680        void g(A & mutex a) {
681                waitfor(f); //Obvious which f() to wait for
682        }
683
684        void f(A & mutex a, int); // New different F added in scope
685        void h(A & mutex a) {
686                waitfor(f); //Less obvious which f() to wait for
687        }
688\end{cfacode}
689
690Furthermore, 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:
691
692\begin{center}
693\begin{tabular}{l}
694\begin{pseudo}
695        if monitor is free
696                enter
697        elif already own the monitor
698                continue
699        elif monitor accepts me
700                enter
701        else
702                block
703\end{pseudo}
704\end{tabular}
705\end{center}
706
707For the first two conditions, 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:
708
709\begin{center}
710{\resizebox{0.4\textwidth}{!}{\input{monitor}}}
711\end{center}
712
713There 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. This technique cannot be used in \CFA because it relies on the fact that the monitor type declares all the acceptable routines. 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.
714The alternative is to have a picture like this one:
715
716\begin{center}
717{\resizebox{0.4\textwidth}{!}{\input{ext_monitor}}}
718\end{center}
719
720Not storing the mask inside the monitor means that the storage for the mask information can vary between calls to \code{waitfor}, 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 waitfor to check if a routine is already queued in.
721
722Note that in the second picture, tasks need to always keep track of through which routine they are attempting to acquire the monitor and the routine mask needs to have both a function pointer and a set of monitors, as will be discussed in the next section. These details where omitted from the picture for the sake of simplifying the representation.
723
724At 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. In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be prohibitively hard to write. This decision is based on the assumption that writing fast but inflexible locks is closer to a solved problems than writing locks that are as flexible as external scheduling in \CFA.
725
726% ======================================================================
727% ======================================================================
728\subsection{Multi-monitor scheduling}
729% ======================================================================
730% ======================================================================
731
732External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax. Even in the simplest possible case, some new semantics need to be established:
733\begin{cfacode}
734        monitor M {};
735
736        void f(M & mutex a);
737
738        void g(M & mutex a, M & mutex b) {
739                waitfor(f); //ambiguous, keep a pass b or other way around?
740        }
741\end{cfacode}
742
743The obvious solution is to specify the correct monitor as follows:
744
745\begin{cfacode}
746        monitor M {};
747
748        void f(M & mutex a);
749
750        void g(M & mutex a, M & mutex b) {
751                waitfor( f, b );
752        }
753\end{cfacode}
754
755This syntax is unambiguous. Both locks are acquired and kept. When routine \code{f} is called, the lock for monitor \code{b} is temporarily transferred from \code{g} to \code{f} (while \code{g} still holds lock \code{a}). This behavior can be extended to multi-monitor waitfor statment as follows.
756
757\begin{cfacode}
758        monitor M {};
759
760        void f(M & mutex a, M & mutex b);
761
762        void g(M & mutex a, M & mutex b) {
763                waitfor( f, a, b);
764        }
765\end{cfacode}
766
767Note that the set of monitors passed to the \code{waitfor} statement must be entirely contained in the set of monitors already acquired in the routine. \code{waitfor} used in any other context is Undefined Behaviour.
768
769An important behavior to note is that what happens when a set of monitors only match partially :
770
771\begin{cfacode}
772        mutex struct A {};
773
774        mutex struct B {};
775
776        void g(A & mutex a, B & mutex b) {
777                waitfor(f, a, b);
778        }
779
780        A a1, a2;
781        B b;
782
783        void foo() {
784                g(a1, b); //block on accept
785        }
786
787        void bar() {
788                f(a2, b); //fufill cooperation
789        }
790\end{cfacode}
791
792While the equivalent can happen when using internal scheduling, the fact that conditions are specific to a set of monitors means that users have to use two different condition variables. In both cases, partially matching monitor sets does not wake-up the waiting thread. It is also important to note that in the case of external scheduling, as for routine calls, the order of parameters is important; \code{waitfor(f,a,b)} and \code{waitfor(f,b,a)} are to distinct waiting condition.
793
794% ======================================================================
795% ======================================================================
796\subsection{Waitfor semantics}
797% ======================================================================
798% ======================================================================
Note: See TracBrowser for help on using the repository browser.