Changes in / [b10c621c:0aaac0e]
- Location:
- doc/proposals/concurrency
- Files:
-
- 2 added
- 1 deleted
- 12 edited
-
Makefile (modified) (2 diffs)
-
annex/glossary.tex (modified) (1 diff)
-
figures/dependency.fig (added)
-
figures/ext_monitor.fig (modified) (5 diffs)
-
figures/int_monitor.fig.bak (deleted)
-
style/cfa-format.tex (modified) (4 diffs)
-
text/basics.tex (modified) (12 diffs)
-
text/cforall.tex (modified) (3 diffs)
-
text/concurrency.tex (modified) (27 diffs)
-
text/internals.tex (added)
-
text/intro.tex (modified) (1 diff)
-
text/parallelism.tex (modified) (2 diffs)
-
text/together.tex (modified) (1 diff)
-
thesis.tex (modified) (1 diff)
-
version (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
doc/proposals/concurrency/Makefile
rb10c621c r0aaac0e 16 16 text/basics \ 17 17 text/concurrency \ 18 text/internals \ 18 19 text/parallelism \ 19 20 text/together \ … … 25 26 ext_monitor \ 26 27 int_monitor \ 28 dependency \ 27 29 }} 28 30 -
doc/proposals/concurrency/annex/glossary.tex
rb10c621c r0aaac0e 13 13 } 14 14 15 \longnewglossaryentry{ group-acquire}16 {name={bulk acquiring}}15 \longnewglossaryentry{bulk-acq} 16 {name={bulk-acquiring}} 17 17 { 18 18 Implicitly acquiring several monitors when entering a monitor. 19 } 20 21 \longnewglossaryentry{multi-acq} 22 {name={multiple-acquisition}} 23 { 24 Any locking technique which allow any single thread to acquire a lock multiple times. 19 25 } 20 26 -
doc/proposals/concurrency/figures/ext_monitor.fig
rb10c621c r0aaac0e 14 14 4 1 -1 0 0 0 10 0.0000 2 105 90 6000 2160 d\001 15 15 -6 16 6 5 850 1650 6150 195017 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 6000 1800 105 105 6000 1800 6105 190518 4 1 -1 0 0 0 10 0.0000 2 105 90 6000 1860 b\00116 6 5100 2100 5400 2400 17 1 3 0 1 -1 -1 1 0 4 0.000 1 0.0000 5250 2250 105 105 5250 2250 5355 2250 18 4 1 -1 0 0 0 10 0.0000 2 105 120 5250 2295 X\001 19 19 -6 20 20 6 5100 1800 5400 2100 … … 22 22 4 1 -1 0 0 0 10 0.0000 2 105 120 5250 2010 Y\001 23 23 -6 24 6 5 100 2100 5400 240025 1 3 0 1 -1 -1 1 0 4 0.000 1 0.0000 5250 2250 105 105 5250 2250 5355 225026 4 1 -1 0 0 0 10 0.0000 2 105 120 5250 2295 X\00124 6 5850 1650 6150 1950 25 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 6000 1800 105 105 6000 1800 6105 1905 26 4 1 -1 0 0 0 10 0.0000 2 105 90 6000 1860 b\001 27 27 -6 28 6 30 00 5400 7200 570028 6 3070 5445 7275 5655 29 29 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 3150 5550 80 80 3150 5550 3230 5630 30 30 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4500 5550 105 105 4500 5550 4605 5655 … … 32 32 4 0 -1 0 0 0 12 0.0000 2 135 1035 4725 5625 blocked task\001 33 33 4 0 -1 0 0 0 12 0.0000 2 135 870 3300 5625 active task\001 34 4 0 -1 0 0 0 12 0.0000 2 1 80 930 6225 5625 routine ptrs\00134 4 0 -1 0 0 0 12 0.0000 2 135 1050 6225 5625 routine mask\001 35 35 -6 36 36 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 3300 3600 105 105 3300 3600 3405 3705 … … 43 43 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 44 44 4050 2925 5475 2925 5475 3225 4050 3225 4050 2925 45 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 0 0 246 5850 2850 6075 300047 45 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 0 0 4 48 46 3150 3750 3750 3750 3750 4050 3150 4050 … … 66 64 2 2 1 1 -1 -1 0 0 -1 4.000 0 0 0 0 0 5 67 65 5850 4200 5850 3300 4350 3300 4350 4200 5850 4200 68 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 0 0 369 5250 2850 5850 2850 5850 165070 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 0 0 471 3150 3150 3750 3150 3750 2850 5325 285072 66 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 1 2 73 67 1 1 1.00 60.00 120.00 74 68 7 1 1.00 60.00 120.00 75 69 5250 3150 5250 2400 70 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 71 3150 3150 3750 3150 3750 2850 5850 2850 5850 1650 72 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 73 5850 2850 6150 3000 76 74 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 77 75 5100 1800 5400 1800 5400 2400 5100 2400 5100 1800 -
doc/proposals/concurrency/style/cfa-format.tex
rb10c621c r0aaac0e 108 108 belowskip=3pt, 109 109 keepspaces=true, 110 tabsize=4, 110 111 % frame=lines, 111 112 literate=, … … 133 134 belowskip=3pt, 134 135 keepspaces=true, 136 tabsize=4, 135 137 % frame=lines, 136 138 literate=, … … 150 152 keywordstyle=\bfseries\color{blue}, 151 153 keywordstyle=[2]\bfseries\color{Plum}, 152 commentstyle=\ itshape\color{OliveGreen},% green and italic comments154 commentstyle=\sf\itshape\color{OliveGreen}, % green and italic comments 153 155 identifierstyle=\color{identifierCol}, 154 156 stringstyle=\sf\color{Mahogany}, % use sanserif font … … 158 160 belowskip=3pt, 159 161 keepspaces=true, 162 tabsize=4, 160 163 % frame=lines, 161 164 literate=, -
doc/proposals/concurrency/text/basics.tex
rb10c621c r0aaac0e 1 1 % ====================================================================== 2 2 % ====================================================================== 3 \chapter{ Basics}\label{basics}3 \chapter{Concurrency Basics}\label{basics} 4 4 % ====================================================================== 5 5 % ====================================================================== 6 Before any detailed discussion of the concurrency and parallelism in \CFA, it is important to describe the basics of concurrency and how they are expressed in \CFA user code.6 Before any detailed discussion of the concurrency and parallelism in \CFA, it is important to describe the basics of concurrency and how they are expressed in \CFA user-code. 7 7 8 8 \section{Basics of concurrency} 9 At its core, concurrency is based on having call-stacks and potentially multiple threads of execution for these stacks. Concurrency without parallelism only requires having multiple call stacks (or contexts) for a single thread of execution, and switching between these call stacks on a regular basis. A minimal concurrency product can be achieved by creating coroutines, which instead of context switching between each other, always ask an oracle where to context switch next. While coroutines do not technically require a stack, stackfull coroutines are the closest abstraction to a practical "naked"" call stack. When writing concurrency in terms of coroutines, the oracle effectively becomes a scheduler and the whole system now follows a cooperative threading-model \cit. The oracle/scheduler can either be a stackless or stackfull entity and correspondingly require one or two context switches to run a different coroutine. In any case, a subset of concurrency related challenges start to appear. For the complete set of concurrency challenges to occur, the only feature missing is preemption. Indeed, concurrency challenges appear with non-determinism. Guaranteeing mutual-exclusion or synchronisation are simply ways of limiting the lack of determinism in a system. A scheduler introduces order of execution uncertainty, while preemption introduces incertainty about where context-switches occur. Now it is important to understand that uncertainty is not necessarily undesireable; uncertainty can often be used by systems to significantly increase performance and is often the basis of giving a user the illusion that tasks are running in parallel. Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows\cit. 9 At its core, concurrency is based on having multiple call-stacks and scheduling among threads of execution executing on these stacks. Concurrency without parallelism only requires having multiple call stacks (or contexts) for a single thread of execution. 10 11 Indeed, while execution with a single thread and multiple stacks where the thread is self-scheduling deterministically across the stacks is called coroutining, execution with a single and multiple stacks but where the thread is scheduled by an oracle (non-deterministic from the thread perspective) across the stacks is called concurrency. 12 13 Therefore, a minimal concurrency system can be achieved by creating coroutines, which instead of context switching among each other, always ask an oracle where to context switch next. While coroutines can execute on the caller's stack-frame, stackfull coroutines allow full generality and are sufficient as the basis for concurrency. The aforementioned oracle is a scheduler and the whole system now follows a cooperative threading-model \cit. The oracle/scheduler can either be a stackless or stackfull entity and correspondingly require one or two context switches to run a different coroutine. In any case, a subset of concurrency related challenges start to appear. For the complete set of concurrency challenges to occur, the only feature missing is preemption. Indeed, concurrency challenges appear with non-determinism. Using mutual-exclusion or synchronisation are ways of limiting the lack of determinism in a system. A scheduler introduces order of execution uncertainty, while preemption introduces uncertainty about where context-switches occur. Now it is important to understand that uncertainty is not undesireable; uncertainty can often be used by systems to significantly increase performance and is often the basis of giving a user the illusion that tasks are running in parallel. Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows\cit. 10 14 11 15 \section{\protect\CFA 's Thread Building Blocks} 12 One of the important features that is missing in C is threading. On modern architectures, a lack of threading is becoming less and less forgivable\cite{Sutter05, Sutter05b}, and therefore modern programming languages must have the proper tools to allow users to write performant concurrent and/or parallel programs. As an extension of C, \CFA needs to express these concepts in a way that is as natural as possible to programmers used toimperative languages. And being a system-level language means programmers expect to choose precisely which features they need and which cost they are willing to pay.16 One of the important features that is missing in C is threading. On modern architectures, a lack of threading is unacceptable\cite{Sutter05, Sutter05b}, and therefore modern programming languages must have the proper tools to allow users to write performant concurrent and/or parallel programs. As an extension of C, \CFA needs to express these concepts in a way that is as natural as possible to programmers familiar with imperative languages. And being a system-level language means programmers expect to choose precisely which features they need and which cost they are willing to pay. 13 17 14 18 \section{Coroutines: A stepping stone}\label{coroutine} 15 While the main focus of this proposal is concurrency and parallelism, as mentionned above it is important to adress coroutines, which are actually a significant underlying aspect of a concurrency system. Indeed, while having nothing to do with parallelism and arguably little to do with concurrency, coroutines need to deal with context-switchs and other context-management operations. Therefore, this proposal includes coroutines both as an intermediate step for the implementation of threads, and a first class feature of \CFA. Furthermore, many design challenges of threads are at least partially present in designing coroutines, which makes the design effort that much more relevant. The core API of coroutines revolve around two features: independent call stacks and \code{suspend}/\code{resume}. 16 17 Here is an example of a solution to the fibonnaci problem using \CFA coroutines: 18 \begin{cfacode} 19 coroutine Fibonacci { 20 int fn; // used for communication 21 }; 22 23 void ?{}(Fibonacci & this) { // constructor 24 this.fn = 0; 25 } 26 27 // main automacically called on first resume 28 void main(Fibonacci & this) { 29 int fn1, fn2; // retained between resumes 30 this.fn = 0; 31 fn1 = this.fn; 32 suspend(this); // return to last resume 33 34 this.fn = 1; 19 While the main focus of this proposal is concurrency and parallelism, it is important to address coroutines, which are actually a significant building block of a concurrency system. Coroutines need to deal with context-switchs and other context-management operations. Therefore, this proposal includes coroutines both as an intermediate step for the implementation of threads, and a first class feature of \CFA. Furthermore, many design challenges of threads are at least partially present in designing coroutines, which makes the design effort that much more relevant. The core \acrshort{api} of coroutines revolve around two features: independent call stacks and \code{suspend}/\code{resume}. 20 21 A good example of a problem made easier with coroutines is genereting the fibonacci sequence. This problem comes with the challenge of decoupling how a sequence is generated and how it is used. Figure \ref{fig:fibonacci-c} shows conventional approaches to writing generators in C. All three of these approach suffer from strong coupling. The left and center approaches require that the generator have knowledge of how the sequence will be used, while the rightmost approach requires to user to hold internal state between calls on behalf of th sequence generator and makes it much harder to handle corner cases like the Fibonacci seed. 22 \begin{figure} 23 \label{fig:fibonacci-c} 24 \begin{center} 25 \begin{tabular}{c @{\hskip 0.025in}|@{\hskip 0.025in} c @{\hskip 0.025in}|@{\hskip 0.025in} c} 26 \begin{ccode}[tabsize=2] 27 //Using callbacks 28 void fibonacci_func( 29 int n, 30 void (*callback)(int) 31 ) { 32 int first = 0; 33 int second = 1; 34 int next, i; 35 for(i = 0; i < n; i++) 36 { 37 if(i <= 1) 38 next = i; 39 else { 40 next = f1 + f2; 41 f1 = f2; 42 f2 = next; 43 } 44 callback(next); 45 } 46 } 47 \end{ccode}&\begin{ccode}[tabsize=2] 48 //Using output array 49 void fibonacci_array( 50 int n, 51 int * array 52 ) { 53 int f1 = 0; int f2 = 1; 54 int next, i; 55 for(i = 0; i < n; i++) 56 { 57 if(i <= 1) 58 next = i; 59 else { 60 next = f1 + f2; 61 f1 = f2; 62 f2 = next; 63 } 64 *array = next; 65 array++; 66 } 67 } 68 \end{ccode}&\begin{ccode}[tabsize=2] 69 //Using external state 70 typedef struct { 71 int f1, f2; 72 } iterator_t; 73 74 int fibonacci_state( 75 iterator_t * it 76 ) { 77 int f; 78 f = it->f1 + it->f2; 79 it->f2 = it->f1; 80 it->f1 = f; 81 return f; 82 } 83 84 85 86 87 88 89 \end{ccode} 90 \end{tabular} 91 \end{center} 92 \caption{Different implementations of a fibonacci sequence generator in C.} 93 \end{figure} 94 95 96 Figure \ref{fig:fibonacci-cfa} is an example of a solution to the fibonnaci problem using \CFA coroutines, using the coroutine stack to hold sufficient state for the generation. This solution has the advantage of having very strong decoupling between how the sequence is generated and how it is used. Indeed, this version is a easy to use as the \code{fibonacci_state} solution, while the imlpementation is very similar to the \code{fibonacci_func} example. 97 98 \begin{figure} 99 \label{fig:fibonacci-cfa} 100 \begin{cfacode} 101 coroutine Fibonacci { 102 int fn; //used for communication 103 }; 104 105 void ?{}(Fibonacci & this) { //constructor 106 this.fn = 0; 107 } 108 109 //main automacically called on first resume 110 void main(Fibonacci & this) { 111 int fn1, fn2; //retained between resumes 112 this.fn = 0; 113 fn1 = this.fn; 114 suspend(this); //return to last resume 115 116 this.fn = 1; 117 fn2 = fn1; 118 fn1 = this.fn; 119 suspend(this); //return to last resume 120 121 for ( ;; ) { 122 this.fn = fn1 + fn2; 35 123 fn2 = fn1; 36 124 fn1 = this.fn; 37 suspend(this); // return to last resume 38 39 for ( ;; ) { 40 this.fn = fn1 + fn2; 41 fn2 = fn1; 42 fn1 = this.fn; 43 suspend(this); // return to last resume 44 } 45 } 46 47 int next(Fibonacci & this) { 48 resume(this); // transfer to last suspend 49 return this.fn; 50 } 51 52 void main() { // regular program main 53 Fibonacci f1, f2; 54 for ( int i = 1; i <= 10; i += 1 ) { 55 sout | next( f1 ) | next( f2 ) | endl; 56 } 57 } 58 \end{cfacode} 125 suspend(this); //return to last resume 126 } 127 } 128 129 int next(Fibonacci & this) { 130 resume(this); //transfer to last suspend 131 return this.fn; 132 } 133 134 void main() { //regular program main 135 Fibonacci f1, f2; 136 for ( int i = 1; i <= 10; i += 1 ) { 137 sout | next( f1 ) | next( f2 ) | endl; 138 } 139 } 140 \end{cfacode} 141 \caption{Implementation of fibonacci using coroutines} 142 \end{figure} 59 143 60 144 \subsection{Construction} 61 One important design challenge for coroutines and threads (shown in section \ref{threads}) is that the runtime system needs to run code after the user-constructor runs . In the case of coroutines, this challenge is simpler since there is no non-determinism from preemption or scheduling. However, the underlying challenge remains the same for coroutines and threads.62 63 The runtime system needs to create the coroutine's stack and more importantly prepare it for the first resumption. The timing of the creation is non-trivial since users both expect to have fully constructed objects once execution enters the coroutine main and to be able to resume the coroutine from the constructor. Like for regular objects, constructors can stillleak coroutines before they are ready. There are several solutions to this problem but the chosen options effectively forces the design of the coroutine.145 One important design challenge for coroutines and threads (shown in section \ref{threads}) is that the runtime system needs to run code after the user-constructor runs to connect the object into the system. In the case of coroutines, this challenge is simpler since there is no non-determinism from preemption or scheduling. However, the underlying challenge remains the same for coroutines and threads. 146 147 The runtime system needs to create the coroutine's stack and more importantly prepare it for the first resumption. The timing of the creation is non-trivial since users both expect to have fully constructed objects once execution enters the coroutine main and to be able to resume the coroutine from the constructor. As regular objects, constructors can leak coroutines before they are ready. There are several solutions to this problem but the chosen options effectively forces the design of the coroutine. 64 148 65 149 Furthermore, \CFA faces an extra challenge as polymorphic routines create invisible thunks when casted to non-polymorphic routines and these thunks have function scope. For example, the following code, while looking benign, can run into undefined behaviour because of thunks: … … 78 162 } 79 163 \end{cfacode} 164 80 165 The generated C code\footnote{Code trimmed down for brevity} creates a local thunk to hold type information: 81 166 … … 95 180 } 96 181 \end{ccode} 97 The problem in this example is a race condition between the start of the execution of \code{noop} on the other thread and the stack frame of \code{bar} being destroyed. This extra challenge limits which solutions are viable because storing the function pointer for too long only increases the chances that the race will end inundefined behavior; i.e. the stack based thunk being destroyed before it was used. This challenge is an extension of challenges that come with second-class routines. Indeed, GCC nested routines also have the limitation that the routines cannot be passed outside of the scope of the functions these were declared in. The case of coroutines and threads is simply an extension of this problem to multiple call-stacks.182 The problem in this example is a storage management issue, the function pointer \code{_thunk0} is only valid until the end of the block. This extra challenge limits which solutions are viable because storing the function pointer for too long causes undefined behavior; i.e. the stack based thunk being destroyed before it was used. This challenge is an extension of challenges that come with second-class routines. Indeed, GCC nested routines also have the limitation that the routines cannot be passed outside of the scope of the functions these were declared in. The case of coroutines and threads is simply an extension of this problem to multiple call-stacks. 98 183 99 184 \subsection{Alternative: Composition} 100 One solution to this challenge would be to use composition/containement, 101 102 \begin{cfacode} 103 struct Fibonacci { 104 int fn; // used for communication 105 coroutine c; //composition 106 }; 107 108 void ?{}(Fibonacci & this) { 109 this.fn = 0; 110 (this.c){}; 111 } 112 \end{cfacode} 113 There are two downsides to this approach. The first, which is relatively minor, is that the base class needs to be made aware of the main routine pointer, regardless of whether a parameter or a virtual pointer is used, this means the coroutine data must be made larger to store a value that is actually a compile time constant (address of the main routine). The second problem, which is both subtle and significant, is that now users can get the initialisation order of there coroutines wrong. Indeed, every field of a \CFA struct is constructed but in declaration order, unless users explicitly write otherwise. This semantics means that users who forget to initialize a the coroutine may resume the coroutine with an uninitilized object. For coroutines, this is unlikely to be a problem, for threads however, this is a significant problem. 185 One solution to this challenge is to use composition/containement, where uses add insert a coroutine field which contains the necessary information to manage the coroutine. 186 187 \begin{cfacode} 188 struct Fibonacci { 189 int fn; //used for communication 190 coroutine c; //composition 191 }; 192 193 void ?{}(Fibonacci & this) { 194 this.fn = 0; 195 (this.c){}; //Call constructor to initialize coroutine 196 } 197 \end{cfacode} 198 There are two downsides to this approach. The first, which is relatively minor, made aware of the main routine pointer. This information must either be store in the coroutine runtime data or in its static type structure. When using composition, all coroutine handles have the same static type structure which means the pointer to the main needs to be part of the runtime data. This requirement means the coroutine data must be made larger to store a value that is actually a compile time constant (address of the main routine). The second problem, which is both subtle and significant, is that now users can get the initialisation order of coroutines wrong. Indeed, every field of a \CFA struct is constructed but in declaration order, unless users explicitly write otherwise. This semantics means that users who forget to initialize the coroutine handle may resume the coroutine with an uninitilized object. For coroutines, this is unlikely to be a problem, for threads however, this is a significant problem. Figure \ref{fig:fmt-line} shows the \code{Format} coroutine which rearranges text in order to group characters into blocks of fixed size. This is a good example where the control flow is made much simpler from being able to resume the coroutine from the constructor and highlights the idea that interesting control flow can occor in the constructor. 199 \begin{figure} 200 \label{fig:fmt-line} 201 \begin{cfacode}[tabsize=3] 202 //format characters into blocks of 4 and groups of 5 blocks per line 203 coroutine Format { 204 char ch; //used for communication 205 int g, b; //global because used in destructor 206 }; 207 208 void ?{}(Format & fmt) { 209 resume( fmt ); //prime (start) coroutine 210 } 211 212 void ^?{}(Format & fmt) with fmt { 213 if ( fmt.g != 0 || fmt.b != 0 ) 214 sout | endl; 215 } 216 217 void main(Format & fmt) with fmt { 218 for ( ;; ) { //for as many characters 219 for(g = 0; g < 5; g++) { //groups of 5 blocks 220 for(b = 0; b < 4; fb++) { //blocks of 4 characters 221 suspend(); 222 sout | ch; //print character 223 } 224 sout | " "; //print block separator 225 } 226 sout | endl; //print group separator 227 } 228 } 229 230 void prt(Format & fmt, char ch) { 231 fmt.ch = ch; 232 resume(fmt); 233 } 234 235 int main() { 236 Format fmt; 237 char ch; 238 Eof: for ( ;; ) { //read until end of file 239 sin | ch; //read one character 240 if(eof(sin)) break Eof; //eof ? 241 prt(fmt, ch); //push character for formatting 242 } 243 } 244 \end{cfacode} 245 \caption{Formatting text into lines of 5 blocks of 4 characters.} 246 \end{figure} 247 114 248 115 249 \subsection{Alternative: Reserved keyword} … … 117 251 118 252 \begin{cfacode} 119 coroutine Fibonacci { 120 int fn; // used for communication 121 }; 122 \end{cfacode} 123 This mean the compiler can solve problems by injecting code where needed. The downside of this approach is that it makes coroutine a special case in the language. Users who would want to extend coroutines or build their own for various reasons can only do so in ways offered by the language. Furthermore, implementing coroutines without language supports also displays the power of \CFA. 124 While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can both be constructed by users without using the language support. The reserved keywords are only present to improve ease of use for the common cases. 253 coroutine Fibonacci { 254 int fn; //used for communication 255 }; 256 \end{cfacode} 257 This mean the compiler can solve problems by injecting code where needed. The downside of this approach is that it makes coroutine a special case in the language. Users who would want to extend coroutines or build their own for various reasons can only do so in ways offered by the language. Furthermore, implementing coroutines without language supports also displays the power of the programming language used. While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can both be constructed by users without using the language support. The reserved keywords are only present to improve ease of use for the common cases. 125 258 126 259 \subsection{Alternative: Lamda Objects} … … 159 292 coroutine_desc * get_coroutine(T & this); 160 293 }; 161 \end{cfacode} 162 This ensures an object is not a coroutine until \code{resume} (or \code{prime}) is called on the object. Correspondingly, any object that is passed to \code{resume} is a coroutine since it must satisfy the \code{is_coroutine} trait to compile. The advantage of this approach is that users can easily create different types of coroutines, for example, changing the memory foot print of a coroutine is trivial when implementing the \code{get_coroutine} routine. The \CFA keyword \code{coroutine} only has the effect of implementing the getter and forward declarations required for users to only have to implement the main routine. 294 295 forall( dtype T | is_coroutine(T) ) void suspend(T &); 296 forall( dtype T | is_coroutine(T) ) void resume (T &); 297 \end{cfacode} 298 This ensures an object is not a coroutine until \code{resume} is called on the object. Correspondingly, any object that is passed to \code{resume} is a coroutine since it must satisfy the \code{is_coroutine} trait to compile. The advantage of this approach is that users can easily create different types of coroutines, for example, changing the memory layout of a coroutine is trivial when implementing the \code{get_coroutine} routine. The \CFA keyword \code{coroutine} only has the effect of implementing the getter and forward declarations required for users to only have to implement the main routine. 163 299 164 300 \begin{center} … … 186 322 \end{center} 187 323 188 The combination of these two approaches allows users new to co ncurrency to have a easy and concise method while more advanced users can expose themselves to otherwise hidden pitfalls at the benefit oftighter control on memory layout and initialization.324 The combination of these two approaches allows users new to coroutinning and concurrency to have an easy and concise specification, while more advanced users have tighter control on memory layout and initialization. 189 325 190 326 \section{Thread Interface}\label{threads} … … 205 341 \end{cfacode} 206 342 207 Obviously, for this thread implementation to be usefull it must run some user code. Several other threading interfaces use a function-pointer representation as the interface of threads (for example \Csharp~\cite{Csharp} and Scala~\cite{Scala}). However, this proposal considers that statically tying a \code{main} routine to a thread superseeds this approach. Since the \code{main} routine is already a special routine in \CFA (where the program begins), it is possible naturally extendthe semantics using overloading to declare mains for different threads (the normal main being the main of the initial thread). As such the \code{main} routine of a thread can be defined as343 Obviously, for this thread implementation to be usefull it must run some user code. Several other threading interfaces use a function-pointer representation as the interface of threads (for example \Csharp~\cite{Csharp} and Scala~\cite{Scala}). However, this proposal considers that statically tying a \code{main} routine to a thread superseeds this approach. Since the \code{main} routine is already a special routine in \CFA (where the program begins), it is a natural extension of the semantics using overloading to declare mains for different threads (the normal main being the main of the initial thread). As such the \code{main} routine of a thread can be defined as 208 344 \begin{cfacode} 209 345 thread foo {}; … … 214 350 \end{cfacode} 215 351 216 In this example, threads of type \code{foo} start execution in the \code{void main(foo *)} routine which prints \code{"Hello World!"}. While this proposoal encourages this approach to enforce strongly-typed programming, users may prefer to use the routine based thread semantics for the sake of simplicity. With these semantics it is trivial to write a thread type that takes a function pointer asparameter and executes it on its stack asynchronously217 \begin{cfacode} 218 typedef void (*voidFunc)( void);352 In this example, threads of type \code{foo} start execution in the \code{void main(foo &)} routine, which prints \code{"Hello World!"}. While this thesis encourages this approach to enforce strongly-typed programming, users may prefer to use the routine-based thread semantics for the sake of simplicity. With these semantics it is trivial to write a thread type that takes a function pointer as a parameter and executes it on its stack asynchronously 353 \begin{cfacode} 354 typedef void (*voidFunc)(int); 219 355 220 356 thread FuncRunner { 221 357 voidFunc func; 358 int arg; 222 359 }; 223 360 224 //ctor 225 void ?{}(FuncRunner & this, voidFunc inFunc) { 361 void ?{}(FuncRunner & this, voidFunc inFunc, int arg) { 226 362 this.func = inFunc; 227 363 } 228 364 229 //main230 365 void main(FuncRunner & this) { 231 this.func( );232 } 233 \end{cfacode} 234 235 An advantage of the overloading approach to main is to clearly highlight where and what memory is required to pass parameters and return values to/from a thread.236 237 Of course for threads to be useful, it must be possible to start and stop threads and wait for them to complete execution. While using an \acrshort{api} such as \code{fork} and \code{join} is relatively common in the literature, such an interface is unnecessary. Indeed, the simplest approach is to use \acrshort{raii} principles and have threads \code{fork} oncethe constructor has completed and \code{join} before the destructor runs.366 this.func( this.arg ); 367 } 368 \end{cfacode} 369 370 An consequence of the strongly typed approach to main is that memory layout of parameters and return values to/from a thread are now explicitly specified in the \acrshort{api}. 371 372 Of course for threads to be useful, it must be possible to start and stop threads and wait for them to complete execution. While using an \acrshort{api} such as \code{fork} and \code{join} is relatively common in the literature, such an interface is unnecessary. Indeed, the simplest approach is to use \acrshort{raii} principles and have threads \code{fork} after the constructor has completed and \code{join} before the destructor runs. 238 373 \begin{cfacode} 239 374 thread World; … … 254 389 \end{cfacode} 255 390 256 This semantic has several advantages over explicit semantics typesafety is guaranteed, a thread is always started and stopped exaclty once and users cannot make any progamming errors. Another advantage of this semantic is that it naturally scaleto multiple threads meaning basic synchronisation is very simple391 This semantic has several advantages over explicit semantics: a thread is always started and stopped exaclty once and users cannot make any progamming errors and it naturally scales to multiple threads meaning basic synchronisation is very simple 257 392 258 393 \begin{cfacode} … … 276 411 \end{cfacode} 277 412 278 However, one of the apparent drawbacks of this system is that threads now always form a lattice, that is they are always destroyed in opposite order of construction because of block structure. However, storage allocation is not limited to blocks; dynamic allocation can create threads that outlive the scope in which the thread is createdmuch like dynamically allocating memory lets objects outlive the scope in which they are created413 However, one of the drawbacks of this approach is that threads now always form a lattice, that is they are always destroyed in opposite order of construction because of block structure. This restriction is relaxed by using dynamic allocation, so threads can outlive the scope in which they are created, much like dynamically allocating memory lets objects outlive the scope in which they are created 279 414 280 415 \begin{cfacode} … … 283 418 }; 284 419 285 //main286 420 void main(MyThread & this) { 287 421 //... … … 291 425 MyThread * long_lived; 292 426 { 427 //Start a thread at the beginning of the scope 293 428 MyThread short_lived; 294 //Start a thread at the beginning of the scope295 296 DoStuff();297 429 298 430 //create another thread that will outlive the thread in this scope 299 431 long_lived = new MyThread; 300 432 433 DoStuff(); 434 301 435 //Wait for the thread short_lived to finish 302 436 } 303 437 DoMoreStuff(); 304 438 305 //Now wait for the short_lived to finish439 //Now wait for the long_lived to finish 306 440 delete long_lived; 307 441 } -
doc/proposals/concurrency/text/cforall.tex
rb10c621c r0aaac0e 5 5 % ====================================================================== 6 6 7 As mentionned in the introduction, the document presents the design for the concurrency features in \CFA. Since it is a new language here is a quick review of the languagespecifically tailored to the features needed to support concurrency.7 This thesis presents the design for a set of concurrency features in \CFA. Since it is a new dialect of C, the following is a quick introduction to the language, specifically tailored to the features needed to support concurrency. 8 8 9 \CFA is a extension of ISO C and therefore supports much of the same paradigms as C. It is a non-object oriented system level language, meaning it has very most of the major abstractions have either no runtime cost or can be opt-out easily. Like C, the basics of \CFA revolve around structures and routines, which are thin abstractions over assembly. The vast majority of the code produced by a \CFA compiler respects memory-layouts and calling-conventions laid out by C. However, while \CFA is not an object-oriented language according to a strict definition. It does have some notion of objects, most importantly construction and destruction of objects. Most of the following pieces of code can be found as is on the \CFA website :\cite{www-cfa}9 \CFA is a extension of ISO-C and therefore supports all of the same paradigms as C. It is a non-object oriented system language, meaning most of the major abstractions have either no runtime overhead or can be opt-out easily. Like C, the basics of \CFA revolve around structures and routines, which are thin abstractions over machine code. The vast majority of the code produced by the \CFA translator respects memory-layouts and calling-conventions laid out by C. Interestingly, while \CFA is not an object-oriented language, lacking the concept of a received (e.g.: this), it does have some notion of objects\footnote{C defines the term objects as : [Where to I get the C11 reference manual?]}, most importantly construction and destruction of objects. Most of the following pieces of code can be found on the \CFA website \cite{www-cfa} 10 10 11 11 \section{References} 12 12 13 Like \CC, \CFA introduces references as an alternative to pointers. In regards to concurrency, the semantics difference between pointers and references are n't particularly relevant but since this document uses mostly references here is a quick overview of the semantics :13 Like \CC, \CFA introduces references as an alternative to pointers. In regards to concurrency, the semantics difference between pointers and references are not particularly relevant but since this document uses mostly references here is a quick overview of the semantics : 14 14 \begin{cfacode} 15 15 int x, *p1 = &x, **p2 = &p1, ***p3 = &p2, 16 16 &r1 = x, &&r2 = r1, &&&r3 = r2; 17 ***p3 = 3; // change x 18 r3 = 3; // change x, ***r3 19 **p3 = ...; // change p1 20 &r3 = ...; // change r1, (&*)**r3 21 *p3 = ...; // change p2 22 &&r3 = ...; // change r2, (&(&*)*)*r3 23 &&&r3 = p3; // change r3 to p3, (&(&(&*)*)*)r3 24 int y, z, & ar[3] = { x, y, z }; // initialize array of references 25 &ar[1] = &z; // change reference array element 26 typeof( ar[1] ) p; // is int, i.e., the type of referenced object 27 typeof( &ar[1] ) q; // is int &, i.e., the type of reference 28 sizeof( ar[1] ) == sizeof( int ); // is true, i.e., the size of referenced object 29 sizeof( &ar[1] ) == sizeof( int *); // is true, i.e., the size of a reference 17 ***p3 = 3; //change x 18 r3 = 3; //change x, ***r3 19 **p3 = ...; //change p1 20 *p3 = ...; //change p2 21 int y, z, & ar[3] = {x, y, z}; //initialize array of references 22 typeof( ar[1]) p; //is int, i.e., the type of referenced object 23 typeof(&ar[1]) q; //is int &, i.e., the type of reference 24 sizeof( ar[1]) == sizeof(int); //is true, i.e., the size of referenced object 25 sizeof(&ar[1]) == sizeof(int *); //is true, i.e., the size of a reference 30 26 \end{cfacode} 31 27 The important thing to take away from this code snippet is that references offer a handle to an object much like pointers but which is automatically derefferenced when convinient. … … 33 29 \section{Overloading} 34 30 35 Another important feature \CFA has in common with \CC is function overloading :31 Another important feature of \CFA is function overloading as in Java and \CC, where routine with the same name are selected based on the numbers and type of the arguments. As well, \CFA uses the return type as part of the selection criteria, as in Ada\cite{Ada}. For routines with multiple parameters and returns, the selection is complex. 36 32 \begin{cfacode} 37 // selection based on type and number of parameters38 void f( void ); //(1)39 void f( char ); //(2)40 void f( int, double ); //(3)41 f(); // select (1)42 f( 'a' ); //select (2)43 f( 3, 5.2 ); //select (3)33 //selection based on type and number of parameters 34 void f(void); //(1) 35 void f(char); //(2) 36 void f(int, double); //(3) 37 f(); //select (1) 38 f('a'); //select (2) 39 f(3, 5.2); //select (3) 44 40 45 // selection based on type and number of returns 46 char f( int ); // (1) 47 double f( int ); // (2) 48 [ int, double ] f( int ); // (3) 49 char c = f( 3 ); // select (1) 50 double d = f( 4 ); // select (2) 51 [ int, double ] t = f( 5 ); // select (3) 41 //selection based on type and number of returns 42 char f(int); //(1) 43 double f(int); //(2) 44 char c = f(3); //select (1) 45 double d = f(4); //select (2) 52 46 \end{cfacode} 53 This feature is particularly important for concurrency since the runtime system relies on creating different types do represent concurrency objects. Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions that prevent clashes. As seen in chapter \ref{basics}, the main is an example of routine that benefits from overloading when concurrency in introduced.47 This feature is particularly important for concurrency since the runtime system relies on creating different types to represent concurrency objects. Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions that prevent name clashes. As seen in chapter \ref{basics}, routines main is an example that benefits from overloading. 54 48 55 49 \section{Operators} 56 50 Overloading also extends to operators. The syntax for denoting operator-overloading is to name a routine with the symbol of the operator and question marks where the arguments of the operation would be, like so : 57 51 \begin{cfacode} 58 int ++? ( int op ); //unary prefix increment59 int ?++ ( int op ); //unary postfix increment60 int ?+? ( int op1, int op2 ); //binary plus61 int ?<=?( int op1, int op2 ); //binary less than62 int ?=? ( int & op1, int op2 ); //binary assignment63 int ?+=?( int & op1, int op2 ); //binary plus-assignment52 int ++? (int op); //unary prefix increment 53 int ?++ (int op); //unary postfix increment 54 int ?+? (int op1, int op2); //binary plus 55 int ?<=?(int op1, int op2); //binary less than 56 int ?=? (int & op1, int op2); //binary assignment 57 int ?+=?(int & op1, int op2); //binary plus-assignment 64 58 65 struct S { int i, j;};66 S ?+?( S op1, S op2 ) { //add two structures67 return (S){ op1.i + op2.i, op1.j + op2.j};59 struct S {int i, j;}; 60 S ?+?(S op1, S op2) { //add two structures 61 return (S){op1.i + op2.i, op1.j + op2.j}; 68 62 } 69 S s1 = { 1, 2 }, s2 = { 2, 3}, s3;70 s3 = s1 + s2; // compute sum: s3 == { 2, 5}63 S s1 = {1, 2}, s2 = {2, 3}, s3; 64 s3 = s1 + s2; //compute sum: s3 == {2, 5} 71 65 \end{cfacode} 72 73 Since concurrency does not use operator overloading, this feature is more important as an introduction for the syntax of constructors. 66 While concurrency does not use operator overloading directly, this feature is more important as an introduction for the syntax of constructors. 74 67 75 68 \section{Constructors/Destructors} 76 Object life time is often a challenge in concurrency. \CFA uses the approach of giving concurrent meaning to object life time as a mean of synchronization and/or mutual exclusion. Since \CFA relies heavily on the life time of objects, Constructors \& Destructors are a the core of the featuresrequired for concurrency and parallelism. \CFA uses the following syntax for constructors and destructors :69 Object life-time is often a challenge in concurrency. \CFA uses the approach of giving concurrent meaning to object life-time as a mean of synchronization and/or mutual exclusion. Since \CFA relies heavily on the life time of objects, constructors and destructors are a core feature required for concurrency and parallelism. \CFA uses the following syntax for constructors and destructors : 77 70 \begin{cfacode} 78 71 struct S { … … 80 73 int * ia; 81 74 }; 82 void ?{}( S & s, int asize ) with s { //constructor operator83 s ize = asize; //initialize fields84 ia = calloc( size, sizeof( S ));75 void ?{}(S & s, int asize) { //constructor operator 76 s.size = asize; //initialize fields 77 s.ia = calloc(size, sizeof(S)); 85 78 } 86 void ^?{}( S & s ) with s { //destructor operator87 free( ia ); //de-initialization fields79 void ^?{}(S & s) { //destructor operator 80 free(ia); //de-initialization fields 88 81 } 89 82 int main() { 90 S x = { 10 }, y = { 100 }; // implict calls: ?{}( x, 10 ), ?{}( y, 100)91 ... //use x and y92 ^x{}; ^y{}; //explicit calls to de-initialize93 x{ 20 }; y{ 200 }; //explicit calls to reinitialize94 ... //reuse x and y95 } // implict calls: ^?{}( y ), ^?{}( x)83 S x = {10}, y = {100}; //implict calls: ?{}(x, 10), ?{}(y, 100) 84 ... //use x and y 85 ^x{}; ^y{}; //explicit calls to de-initialize 86 x{20}; y{200}; //explicit calls to reinitialize 87 ... //reuse x and y 88 } //implict calls: ^?{}(y), ^?{}(x) 96 89 \end{cfacode} 97 The language guarantees that every object and all their fields are constructed. Like \CC construction is automatically done on declaration and destruction done when the declared variables reach the end of its scope. 90 The language guarantees that every object and all their fields are constructed. Like \CC, construction of an object is automatically done on allocation and destruction of the object is done on deallocation. Allocation and deallocation can occur on the stack or on the heap. 91 \begin{cfacode} 92 { 93 struct S s = {10}; //allocation, call constructor 94 ... 95 } //deallocation, call destructor 96 struct S * s = new(); //allocation, call constructor 97 ... 98 delete(s); //deallocation, call destructor 99 \end{cfacode} 100 Note that like \CC, \CFA introduces \code{new} and \code{delete}, which behave like \code{malloc} and \code{free} in addition to constructing and destructing objects, after calling \code{malloc} and before calling \code{free} respectively. 98 101 99 For more information see \cite{cforall-ug,rob-thesis,www-cfa}. 102 \section{Parametric Polymorphism} 103 Routines in \CFA can also be reused for multiple types. This is done using the \code{forall} clause which gives \CFA it's name. \code{forall} clauses allow seperatly compiled routines to support generic usage over multiple types. For example, the following sum function will work for any type which support construction from 0 and addition : 104 \begin{cfacode} 105 //constraint type, 0 and + 106 forall(otype T | { void ?{}(T *, zero_t); T ?+?(T, T); }) 107 T sum(T a[ ], size_t size) { 108 T total = 0; //construct T from 0 109 for(size_t i = 0; i < size; i++) 110 total = total + a[i]; //select appropriate + 111 return total; 112 } 113 114 S sa[5]; 115 int i = sum(sa, 5); //use S's 0 construction and + 116 \end{cfacode} 117 118 Since writing constraints on types can become cumbersome for more constrained functions, \CFA also has the concept of traits. Traits are named collection of constraints which can be used both instead and in addition to regular constraints: 119 \begin{cfacode} 120 trait sumable( otype T ) { 121 void ?{}(T *, zero_t); //constructor from 0 literal 122 T ?+?(T, T); //assortment of additions 123 T ?+=?(T *, T); 124 T ++?(T *); 125 T ?++(T *); 126 }; 127 forall( otype T | sumable(T) ) //use trait 128 T sum(T a[], size_t size); 129 \end{cfacode} 130 131 \section{with Clause/Statement} 132 Since \CFA lacks the concept of a receiver, certain functions end-up needing to repeat variable names often, to solve this \CFA offers the \code{with} statement which opens an aggregate scope making its fields directly accessible (like Pascal). 133 \begin{cfacode} 134 struct S { int i, j; }; 135 int mem(S & this) with this //with clause 136 i = 1; //this->i 137 j = 2; //this->j 138 } 139 int foo() { 140 struct S1 { ... } s1; 141 struct S2 { ... } s2; 142 with s1 //with statement 143 { 144 //access fields of s1 145 //without qualification 146 with s2 //nesting 147 { 148 //access fields of s1 and s2 149 //without qualification 150 } 151 } 152 with s1, s2 //scopes open in parallel 153 { 154 //access fields of s1 and s2 155 //without qualification 156 } 157 } 158 \end{cfacode} 159 160 For more information on \CFA see \cite{cforall-ug,rob-thesis,www-cfa}. -
doc/proposals/concurrency/text/concurrency.tex
rb10c621c r0aaac0e 4 4 % ====================================================================== 5 5 % ====================================================================== 6 Several 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 thatclosely 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.6 Several 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 7 8 8 Approaches based on shared memory are more closely related to non-concurrent paradigms since they often rely on basic constructs like routine calls and shared objects. At 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 9 10 An approach that is worth mentionning because it is gaining in popularity is transactionnal memory~\cite{Dice10}[Check citation]. While this approach is even pursued by system languages like \CC\cit, the performance and feature set is currently too restrictive to be the main concurrency paradigm for general purposelanguage, which is why it was rejected as the core paradigm for concurrency in \CFA.11 12 One of the most natural, elegant, and efficient mechanisms for synchronization and communication, especially for shared memory systems, is the \emph{monitor}. Monitors were first proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}. Many programming languages---e.g., Concurrent Pascal~\cite{ConcurrentPascal}, Mesa~\cite{Mesa}, Modula~\cite{Modula-2}, Turing~\cite{Turing:old}, Modula-3~\cite{Modula-3}, NeWS~\cite{NeWS}, Emerald~\cite{Emerald}, \uC~\cite{Buhr92a} and Java~\cite{Java}---provide monitors as explicit language constructs. In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as semaphores or locks to simulate monitors. For these reasons, this project proposes monitors as the core concurrency-construct.10 An approach that is worth mentionning because it is gaining in popularity is transactionnal memory~\cite{Dice10}[Check citation]. While this approach is even pursued by system languages like \CC\cit, the performance and feature set is currently too restrictive to be the main concurrency paradigm for systems language, which is why it was rejected as the core paradigm for concurrency in \CFA. 11 12 One of the most natural, elegant, and efficient mechanisms for synchronization and communication, especially for shared-memory systems, is the \emph{monitor}. Monitors were first proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}. Many programming languages---e.g., Concurrent Pascal~\cite{ConcurrentPascal}, Mesa~\cite{Mesa}, Modula~\cite{Modula-2}, Turing~\cite{Turing:old}, Modula-3~\cite{Modula-3}, NeWS~\cite{NeWS}, Emerald~\cite{Emerald}, \uC~\cite{Buhr92a} and Java~\cite{Java}---provide monitors as explicit language constructs. In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as semaphores or locks to simulate monitors. For these reasons, this project proposes monitors as the core concurrency-construct. 13 13 14 14 \section{Basics} 15 Non-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.15 Non-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 16 17 17 \subsection{Mutual-Exclusion} 18 As 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 composablebecause 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.18 As 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 19 20 20 \subsection{Synchronization} 21 As 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.21 As 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 22 23 23 % ====================================================================== … … 55 55 void ?{}(size_t * this, counter_t & mutex cnt); //conversion 56 56 \end{cfacode} 57 58 Here, 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 60 Having 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 63 The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:64 \begin{cfacode}65 int f1(monitor & mutex m);66 int f2(const monitor & mutex m);67 int f3(monitor ** mutex m);68 int f4(monitor * mutex m []);69 int f5(graph(monitor*) & mutex m);70 \end{cfacode}71 The 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 make the issue tractable, 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}74 int f1(monitor & mutex m); //Okay : recommanded case75 int f2(monitor * mutex m); //Okay : could be an array but probably not76 int f3(monitor mutex m []); //Not Okay : Array of unkown length77 int f4(monitor ** mutex m); //Not Okay : Could be an array78 int f5(monitor * mutex m []); //Not Okay : Array of unkown length79 \end{cfacode}80 81 Unlike 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}83 int f(MonitorA & mutex a, MonitorB & mutex b);84 85 MonitorA a;86 MonitorB b;87 f(a,b);88 \end{cfacode}89 The 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 & b92 ...93 }94 95 void bar(A & mutex a, B & /*nomutex*/ b) { //acquire a96 ... foo(a, b); ... //acquire b97 }98 99 void baz(A & /*nomutex*/ a, B & mutex b) { //acquire b100 ... foo(a, b); ... //acquire a101 }102 \end{cfacode}103 The 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 105 However, 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}110 While 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 112 Finally, 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}114 monitor bank {115 int money;116 log_t usr_log;117 };118 119 void deposit( bank & mutex b, int deposit ) {120 b.money += deposit;121 b.usr_log | "Adding" | deposit | endl;122 }123 124 void 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 % ======================================================================135 Once 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}137 monitor counter_t {138 int value;139 };140 141 void ?{}(counter_t & this) {142 this.cnt = 0;143 }144 145 int ?++(counter_t & mutex this) {146 return ++this.value;147 }148 149 //need for mutex is platform dependent here150 void ?{}(int * this, counter_t & mutex cnt) {151 *this = (int)cnt;152 }153 \end{cfacode}154 155 57 This counter is used as follows: 156 58 \begin{center} … … 171 73 Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting. 172 74 173 % ====================================================================== 174 % ====================================================================== 175 \subsection{Implementation Details: Interaction with polymorphism} 176 % ====================================================================== 177 % ====================================================================== 178 Depending 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 180 First 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 182 Before looking into complex control-flow, it is important to present the difference between the two acquiring options : callsite and entry-point locking, i.e. acquiring the monitors before making a mutex routine call or as the first operation of the mutex routine-call. For example: 183 \begin{center} 184 \setlength\tabcolsep{1.5pt} 185 \begin{tabular}{|c|c|c|} 186 Code & \gls{callsite-locking} & \gls{entry-point-locking} \\ 187 \CFA & pseudo-code & pseudo-code \\ 188 \hline 189 \begin{cfacode}[tabsize=3] 190 void foo(monitor& mutex a){ 191 192 193 194 //Do Work 195 //... 196 197 } 198 199 void main() { 200 monitor a; 201 202 203 204 foo(a); 205 206 } 207 \end{cfacode} & \begin{pseudo}[tabsize=3] 208 foo(& a) { 209 210 211 212 //Do Work 213 //... 214 215 } 216 217 main() { 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] 226 foo(& a) { 227 //called routine 228 //handles concurrency 229 acquire(a); 230 //Do Work 231 //... 232 release(a); 233 } 234 235 main() { 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. 248 249 Note the \code{mutex} keyword relies on the resolver, which means 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: 250 \begin{cfacode} 251 //Incorrect 252 //T is not a monitor 253 forall(dtype T) 254 void foo(T * mutex t); 255 256 //Correct 257 //this function only works on monitors 258 //(any monitor) 259 forall(dtype T | is_monitor(T)) 260 void bar(T * mutex t)); 75 Here, 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 77 For 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} 81 monitor printer { ... }; 82 struct tree { 83 tree * left, right; 84 char * value; 85 }; 86 void print(printer & mutex p, char * v); 87 88 void 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 97 Having 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 99 The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations: 100 \begin{cfacode} 101 int f1(monitor & mutex m); 102 int f2(const monitor & mutex m); 103 int f3(monitor ** mutex m); 104 int f4(monitor * mutex m []); 105 int f5(graph(monitor*) & mutex m); 106 \end{cfacode} 107 The 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} 109 int f1(monitor & mutex m); //Okay : recommanded case 110 int f2(monitor * mutex m); //Okay : could be an array but probably not 111 int f3(monitor mutex m []); //Not Okay : Array of unkown length 112 int f4(monitor ** mutex m); //Not Okay : Could be an array 113 int f5(monitor * mutex m []); //Not Okay : Array of unkown length 114 \end{cfacode} 115 Note 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 117 Unlike 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} 119 int f(MonitorA & mutex a, MonitorB & mutex b); 120 121 MonitorA a; 122 MonitorB b; 123 f(a,b); 124 \end{cfacode} 125 The 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} 139 The \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 141 However, 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} 146 While 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} 150 monitor bank { ... }; 151 152 void deposit( bank & mutex b, int deposit ); 153 154 void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) { 155 deposit( mybank, -me2you ); 156 deposit( yourbank, me2you ); 157 } 158 \end{cfacode} 159 This 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 % ====================================================================== 166 Once 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} 168 monitor counter_t { 169 int value; 170 }; 171 172 void ?{}(counter_t & this) { 173 this.cnt = 0; 174 } 175 176 int ?++(counter_t & mutex this) { 177 return ++this.value; 178 } 179 180 //need for mutex is platform dependent here 181 void ?{}(int * this, counter_t & mutex cnt) { 182 *this = (int)cnt; 183 } 261 184 \end{cfacode} 262 185 … … 267 190 % ====================================================================== 268 191 % ====================================================================== 269 In 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 oncein a way that is natural to the user but requires additional complexity on the implementation side.192 In 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. 270 193 271 194 First, here is a simple example of such a technique: … … 278 201 void foo(A & mutex a) { 279 202 ... 280 // Wait for cooperation from bar()203 //Wait for cooperation from bar() 281 204 wait(a.e); 282 205 ... … … 284 207 285 208 void bar(A & mutex a) { 286 // Provide cooperation for foo()209 //Provide cooperation for foo() 287 210 ... 288 // Unblock foo at scope exit211 //Unblock foo 289 212 signal(a.e); 290 213 } 291 214 \end{cfacode} 292 215 293 There are two details to note here. First, the re \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.294 295 An important aspect to take into account hereis 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.216 There 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 218 An 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. 296 219 297 220 % ====================================================================== … … 319 242 \end{pseudo} 320 243 \end{multicols} 321 The 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 itis a logical requirement for barging prevention.322 323 A direct extension of the previous example is the \gls{group-acquire} version:244 The 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 246 A direct extension of the previous example is a \gls{bulk-acq} version: 324 247 325 248 \begin{multicols}{2} … … 338 261 \end{pseudo} 339 262 \end{multicols} 340 This 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 342 While 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 263 This 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 265 While 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 : 344 266 \begin{multicols}{2} 345 267 \begin{pseudo} … … 354 276 355 277 \begin{pseudo} 278 acquire A 279 acquire B 280 signal B 281 release B 282 release A 283 \end{pseudo} 284 \end{multicols} 285 However, 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} 289 acquire A 290 acquire B 291 wait B 292 release B 293 release A 294 \end{pseudo} 295 296 \columnbreak 297 298 \begin{pseudo} 356 299 357 300 acquire B … … 362 305 \end{multicols} 363 306 364 The next example is where \gls{ group-acquire} adds a significant layer of complexity to the internal signalling semantics.307 The next example is where \gls{bulk-acq} adds a significant layer of complexity to the internal signalling semantics. 365 308 366 309 \begin{multicols}{2} … … 368 311 \begin{pseudo}[numbers=left] 369 312 acquire A 370 // Code Section 1371 acquire A & B 372 // Code Section 2313 //Code Section 1 314 acquire A & B 315 //Code Section 2 373 316 wait A & B 374 // Code Section 3375 release A & B 376 // Code Section 4317 //Code Section 3 318 release A & B 319 //Code Section 4 377 320 release A 378 321 \end{pseudo} … … 383 326 \begin{pseudo}[numbers=left, firstnumber=10] 384 327 acquire A 385 // Code Section 5386 acquire A & B 387 // Code Section 6328 //Code Section 5 329 acquire A & B 330 //Code Section 6 388 331 signal A & B 389 // Code Section 7390 release A & B 391 // Code Section 8332 //Code Section 7 333 release A & B 334 //Code Section 8 392 335 release A 393 336 \end{pseudo} … … 397 340 \end{center} 398 341 399 It is particularly important to pay attention to code sections 8 and 4, 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 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 the monitor A, simply waking up the waiting thread is not an option because it would violate mutual exclusion. There are three options:342 It 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. 400 343 401 344 \subsubsection{Delaying signals} 402 The 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 object , effectively making the existing single monitor semantic viable by simply changing monitors to monitor collections.345 The 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. 403 346 \begin{multicols}{2} 404 347 Waiter … … 424 367 \end{pseudo} 425 368 \end{multicols} 426 However, this solution can become much more complicated depending on what is executed while secretly holding B (at line 10). Indeed, nothing prevents a user from signalling monitor A on a different condition variable: 427 \newpage 369 However, 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: 428 370 \begin{multicols}{2} 429 371 Thread 1 … … 467 409 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. 468 410 469 In 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.411 In 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. 470 412 471 413 \subsubsection{Dependency graphs} 472 In 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:414 In 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: 473 415 474 416 \begin{multicols}{2} … … 495 437 \end{pseudo} 496 438 \end{multicols} 497 Resolving dependency graph being a complex and expensive endeavour, this solution is not the preffered one. 439 440 \begin{figure} 441 \begin{multicols}{3} 442 Thread $\alpha$ 443 \begin{pseudo}[numbers=left, firstnumber=1] 444 acquire A 445 acquire A & B 446 wait A & B 447 release A & B 448 release A 449 \end{pseudo} 450 451 \columnbreak 452 453 Thread $\gamma$ 454 \begin{pseudo}[numbers=left, firstnumber=1] 455 acquire A 456 acquire A & B 457 signal A & B 458 release A & B 459 signal A 460 release A 461 \end{pseudo} 462 463 \columnbreak 464 465 Thread $\beta$ 466 \begin{pseudo}[numbers=left, firstnumber=1] 467 acquire A 468 wait A 469 release 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 485 Listing \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. 498 486 499 487 \subsubsection{Partial signalling} \label{partial-sig} … … 516 504 signal A & B 517 505 release A & B 518 // ... More code519 release A 520 \end{pseudo} 521 \end{multicols} 522 The 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 condition naly waking threads if all conditions are met. Contrary to the other solutions, this solution quickly hits an upper bound on complexity of implementation.506 //... More code 507 release A 508 \end{pseudo} 509 \end{multicols} 510 The 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. 523 511 524 512 % ====================================================================== … … 529 517 An 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}. 530 518 531 For example here is an example highlighting the difference in behaviour: 532 \begin{ center}519 The 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} 533 521 \begin{tabular}{|c|c|} 534 522 \code{signal} & \code{signal_block} \\ 535 523 \hline 536 \begin{cfacode} 537 monitor M { int val; }; 538 539 void foo(M & mutex m ) { 540 m.val++; 541 sout| "Foo:" | m.val |endl; 542 543 wait( c ); 544 545 m.val++; 546 sout| "Foo:" | m.val |endl; 547 } 548 549 void bar(M & mutex m ) { 550 m.val++; 551 sout| "Bar:" | m.val |endl; 552 553 signal( c ); 554 555 m.val++; 556 sout| "Bar:" | m.val |endl; 557 } 558 \end{cfacode}&\begin{cfacode} 559 monitor M { int val; }; 560 561 void foo(M & mutex m ) { 562 m.val++; 563 sout| "Foo:" | m.val |endl; 564 565 wait( c ); 566 567 m.val++; 568 sout| "Foo:" | m.val |endl; 569 } 570 571 void bar(M & mutex m ) { 572 m.val++; 573 sout| "Bar:" | m.val |endl; 574 575 signal_block( c ); 576 577 m.val++; 578 sout| "Bar:" | m.val |endl; 524 \begin{cfacode}[tabsize=3] 525 monitor DatingService 526 { 527 //compatibility codes 528 enum{ CCodes = 20 }; 529 530 int girlPhoneNo 531 int boyPhoneNo; 532 }; 533 534 condition girls[CCodes]; 535 condition boys [CCodes]; 536 condition exchange; 537 538 int 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 566 int boy(int phoneNo, int ccode) 567 { 568 //same as above 569 //with boy/girl interchanged 570 } 571 \end{cfacode}&\begin{cfacode}[tabsize=3] 572 monitor DatingService 573 { 574 //compatibility codes 575 enum{ CCodes = 20 }; 576 577 int girlPhoneNo; 578 int boyPhoneNo; 579 }; 580 581 condition girls[CCodes]; 582 condition boys [CCodes]; 583 //exchange is not needed 584 585 int 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 613 int boy(int phoneNo, int ccode) 614 { 615 //same as above 616 //with boy/girl interchanged 579 617 } 580 618 \end{cfacode} 581 619 \end{tabular} 582 \end{center} 583 Assuming 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: 584 585 \begin{center} 586 \begin{tabular}{|c|c|} 587 \code{signal} & \code{signal_block} \\ 588 \hline 589 \begin{pseudo} 590 Foo: 0 591 Bar: 1 592 Bar: 2 593 Foo: 3 594 \end{pseudo}&\begin{pseudo} 595 Foo: 0 596 Bar: 1 597 Foo: 2 598 Bar: 3 599 \end{pseudo} 600 \end{tabular} 601 \end{center} 602 603 As 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. 604 605 % ====================================================================== 606 % ====================================================================== 607 \subsection{Internal scheduling: Implementation} \label{inschedimpl} 608 % ====================================================================== 609 % ====================================================================== 610 There are several challenges specific to \CFA when implementing internal scheduling. These challenges are direct results of \gls{group-acquire} and loose object definitions. These two constraints are to root cause of most design decisions in the implementation of internal scheduling. Furthermore, to avoid the head-aches of dynamically allocating memory in a concurrent environment, the internal-scheduling design is entirely free of mallocs and other dynamic memory allocation scheme. This is to avoid the chicken and egg problem \cite{Chicken} of having a memory allocator that relies on the threading system and a threading system that relies on the runtime. This extra goal, means that memory management is a constant concern in the design of the system. 611 612 The main memory concern for concurrency is queues. All blocking operations are made by parking threads onto queues. These queues need to be intrinsic\cit to avoid the need memory allocation. This entails that all the fields needed to keep track of all needed information. Since internal scheduling can use an unbound amount of memory (depending on \gls{group-acquire}) statically defining information information in the intrusive fields of threads is insufficient. The only variable sized container that does not require memory allocation is the callstack, which is heavily used in the implementation of internal scheduling. Particularly the GCC extension variable length arrays which is used extensively. 613 614 Since stack allocation is based around scope, the first step of the implementation is to identify the scopes that are available to store the information, and which of these can have a variable length. In the case of external scheduling, the threads and the condition both allow a fixed amount of memory to be stored, while mutex-routines and the actual blocking call allow for an unbound amount (though adding too much to the mutex routine stack size can become expansive faster). 615 616 The following figure is the traditionnal illustration of a monitor : 617 618 \begin{center} 619 {\resizebox{0.4\textwidth}{!}{\input{monitor}}} 620 \end{center} 621 622 For \CFA, the previous picture does not have support for blocking multiple monitors on a single condition. To support \gls{group-acquire} two changes to this picture are required. First, it doesn't make sense to tie the condition to a single monitor since blocking two monitors as one would require arbitrarily picking a monitor to hold the condition. Secondly, the object waiting on the conditions and AS-stack cannot simply contain the waiting thread since a single thread can potentially wait on multiple monitors. As mentionned in section \ref{inschedimpl}, the handling in multiple monitors is done by partially passing, which entails that each concerned monitor needs to have a node object. However, for waiting on the condition, since all threads need to wait together, a single object needs to be queued in the condition. Moving out the condition and updating the node types yields : 623 624 \begin{center} 625 {\resizebox{0.8\textwidth}{!}{\input{int_monitor}}} 626 \end{center} 627 628 \newpage 629 630 This picture and the proper entry and leave algorithms is the fundamental implementation of internal scheduling. 631 632 \begin{multicols}{2} 633 Entry 634 \begin{pseudo}[numbers=left] 635 if monitor is free 636 enter 637 elif I already own the monitor 638 continue 639 else 640 block 641 increment recursion 642 643 \end{pseudo} 644 \columnbreak 645 Exit 646 \begin{pseudo}[numbers=left, firstnumber=8] 647 decrement recursion 648 if recursion == 0 649 if signal_stack not empty 650 set_owner to thread 651 if all monitors ready 652 wake-up thread 653 654 if entry queue not empty 655 wake-up thread 656 \end{pseudo} 657 \end{multicols} 658 659 Some important things to notice about the exit routine. The solution discussed in \ref{inschedimpl} can be seen on line 11 of the previous pseudo code. Basically, the solution boils down to having a seperate data structure for the condition queue and the AS-stack, and unconditionally transferring ownership of the monitors but only unblocking the thread when the last monitor has trasnferred ownership. This solution is safe as well as preventing any potential barging. 620 \caption{Dating service example using \code{signal} and \code{signal_block}. } 621 \label{lst:datingservice} 622 \end{figure} 660 623 661 624 % ====================================================================== … … 700 663 \end{tabular} 701 664 \end{center} 702 This 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 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} as the core external scheduling keyword, \CFA uses \code{waitfor} to prevent name collisions with existing socket APIs.703 704 In 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 the routine \code{V}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.665 This 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 667 In 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. 705 668 706 669 % ====================================================================== … … 715 678 716 679 void f(A & mutex a); 717 void f(int a, float b);718 680 void g(A & mutex a) { 719 waitfor(f); // Less obvious which f() to wait for 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 720 687 } 721 688 \end{cfacode} … … 728 695 if monitor is free 729 696 enter 730 elif Ialready own the monitor697 elif already own the monitor 731 698 continue 732 699 elif monitor accepts me … … 738 705 \end{center} 739 706 740 For the fi st 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:707 For 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: 741 708 742 709 \begin{center} … … 744 711 \end{center} 745 712 746 There are other alternatives to these pictures but in the case of this pictureimplementing 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.747 The alternative would be to have a picture more like this one:713 There 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. 714 The alternative is to have a picture like this one: 748 715 749 716 \begin{center} … … 751 718 \end{center} 752 719 753 Not 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 waitfor to check if a routine is already queued in.754 755 At 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 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.756 757 A nother 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 are considered as distinct routines. However, this could easily be extended in the future.720 Not 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 722 Note 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 724 At 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. 758 725 759 726 % ====================================================================== … … 763 730 % ====================================================================== 764 731 765 External scheduling, like internal scheduling, becomes orders of magnitude more complex when we start introducing multi-monitor syntax. Even in the simplest possible casesome new semantics need to be established:766 \begin{cfacode} 767 m utex struct A{};768 769 mutex struct B {};770 771 void g( A & mutex a, B& mutex b) {772 waitfor(f); //ambiguous, which monitor732 External 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? 773 740 } 774 741 \end{cfacode} … … 777 744 778 745 \begin{cfacode} 779 m utex struct A{};780 781 mutex struct B {};782 783 void g( A & mutex a, B& mutex b) {746 monitor M {}; 747 748 void f(M & mutex a); 749 750 void g(M & mutex a, M & mutex b) { 784 751 waitfor( f, b ); 785 752 } 786 753 \end{cfacode} 787 754 788 This is unambiguous. Both locks will be acquired and kept, when routine \code{f} is called the lock for monitor \code{b} will betemporarily 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.789 790 \begin{cfacode} 791 m utex struct A{};792 793 mutex struct B {};794 795 void g( A & mutex a, B& mutex b) {755 This 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) { 796 763 waitfor( f, a, b); 797 764 } 798 765 \end{cfacode} 799 766 800 Note that the set of monitors passed to the \code{waitfor} statement must be entirely contained in the set of monitor already acquired in the routine. \code{waitfor} used in any other context is Undefined Behaviour.801 802 An important behavior to note is that what happens when set of monitors only match partially :767 Note 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 769 An important behavior to note is that what happens when a set of monitors only match partially : 803 770 804 771 \begin{cfacode} … … 815 782 816 783 void foo() { 817 g(a1, b); 784 g(a1, b); //block on accept 818 785 } 819 786 820 787 void bar() { 821 f(a2, b); 822 } 823 \end{cfacode} 824 825 While the equivalent can happen when using internal scheduling, the fact that conditions are branded on first use means that users have to use two different condition variables. In both cases, partially matching monitor sets will 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. 826 827 % ====================================================================== 828 % ====================================================================== 829 \subsection{Implementation Details: External scheduling queues} 830 % ====================================================================== 831 % ====================================================================== 832 To 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. 833 834 835 \subsection{Internals} 836 The complete mask can be pushed to any one, we are in a context where we already have full ownership of (at least) every concerned monitor and therefore monitors will refuse all calls no matter what. 788 f(a2, b); //fufill cooperation 789 } 790 \end{cfacode} 791 792 While 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 % ====================================================================== -
doc/proposals/concurrency/text/intro.tex
rb10c621c r0aaac0e 3 3 % ====================================================================== 4 4 5 This proposal provides a minimal concurrency API that is simple, efficient and can be reused to build higher-level features. The simplest possible concurrency system is a thread and a lock but this low-level approach is hard to master. An easier approach for users is to support higher-level constructs as the basis of the concurrency, in \CFA. Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{HPP:Study}. Examples are task based, message passing and implicit threading. Therefore a high-level approach is adopted in \CFA5 This thesis provides a minimal concurrency \acrshort{api} that is simple, efficient and can be reused to build higher-level features. The simplest possible concurrency system is a thread and a lock but this low-level approach is hard to master. An easier approach for users is to support higher-level constructs as the basis of concurrency. Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{HPP:Study}. Examples are task based, message passing and implicit threading. The high-level approach and its minimal \acrshort{api} are tested in a dialect of C, call \CFA. [Is there value to say that this thesis is also an early definition of the \CFA language and library in regards to concurrency?] 6 6 7 There are actually two problems that need to be solved in the design of concurrency for a programming language: which concurrency and which parallelism tools are available to the programmer s. While these two concepts are often combined, they are in fact distinct, requiring different tools~\cite{Buhr05a}. Concurrency tools need to handle mutual exclusion and synchronization, while parallelism tools are about performance, cost and resource utilization.7 There are actually two problems that need to be solved in the design of concurrency for a programming language: which concurrency and which parallelism tools are available to the programmer. While these two concepts are often combined, they are in fact distinct, requiring different tools~\cite{Buhr05a}. Concurrency tools need to handle mutual exclusion and synchronization, while parallelism tools are about performance, cost and resource utilization. -
doc/proposals/concurrency/text/parallelism.tex
rb10c621c r0aaac0e 21 21 22 22 \subsection{Jobs and thread pools} 23 The approach on the opposite end of the spectrum is to base parallelism on \glspl{pool}. Indeed, \glspl{pool} offer limited flexibility but at the benefit of a simpler user interface. In \gls{pool} based systems, users express parallelism as units of work, called jobs, and a dependency graph (either explicit or implicit) that tie them together. This approach means users need not worry about concurrency but significantly limitsthe interaction that can occur among jobs. Indeed, any \gls{job} that blocks also blocks the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably. It can be argued that a solution to this problem is to use more workers than available cores. However, unless the number of jobs and the number of workers are comparable, having a significant amount of blocked jobs always results in idles cores.23 An approach on the opposite end of the spectrum is to base parallelism on \glspl{pool}. Indeed, \glspl{pool} offer limited flexibility but at the benefit of a simpler user interface. In \gls{pool} based systems, users express parallelism as units of work, called jobs, and a dependency graph (either explicit or implicit) that tie them together. This approach means users need not worry about concurrency but significantly limit the interaction that can occur among jobs. Indeed, any \gls{job} that blocks also blocks the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably. It can be argued that a solution to this problem is to use more workers than available cores. However, unless the number of jobs and the number of workers are comparable, having a significant amount of blocked jobs always results in idles cores. 24 24 25 25 The gold standard of this implementation is Intel's TBB library~\cite{TBB}. 26 26 27 27 \subsection{Paradigm performance} 28 While the choice between the three paradigms listed above may have significant performance implication, it is difficult to pindown the performance implications of chosing a model at the language level. Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload. Having a large amount of mostly independent units of work to execute almost guarantess that the \gls{pool} based system has the best performance thanks to the lower memory overhead (i.e., not thread stack per job). However, interactions among jobs can easily exacerbate contention. User-level threads allow fine-grain context switching, which results in better resource utilisation, but context switches is more expansive and the extra control means users need to tweak more variables to get the desired performance. Finally, if the units of uninterrupted work are large enough the paradigm choice is largely amortised by the actual work done.28 While the choice between the three paradigms listed above may have significant performance implication, it is difficult to pindown the performance implications of chosing a model at the language level. Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload. Having a large amount of mostly independent units of work to execute almost guarantess that the \gls{pool} based system has the best performance thanks to the lower memory overhead (i.e., not thread stack per job). However, interactions among jobs can easily exacerbate contention. User-level threads allow fine-grain context switching, which results in better resource utilisation, but a context switch is more expensive and the extra control means users need to tweak more variables to get the desired performance. Finally, if the units of uninterrupted work are large enough the paradigm choice is largely amortised by the actual work done. 29 29 30 30 \TODO … … 33 33 34 34 35 \subs ubsection{Future Work: Machine setup}\label{machine}36 While this was not done in the context of this proposal, another important aspect of clusters is affinity. While many common desktop and laptop PCs have homogeneous CPUs, other devices often have more heteregenous setups. For example, system using \acrshort{numa} configurations may benefit from users being able to tie clusters and/or kernel threads to certains CPU cores. OS support for CPU affinity is now common \cit, which means it is both possible and desirable for \CFA to offer an abstraction mechanism for portable CPU affinity.35 \subsection{Future Work: Machine setup}\label{machine} 36 While this was not done in the context of this thesis, another important aspect of clusters is affinity. While many common desktop and laptop PCs have homogeneous CPUs, other devices often have more heteregenous setups. For example, system using \acrshort{numa} configurations may benefit from users being able to tie clusters and/or kernel threads to certains CPU cores. OS support for CPU affinity is now common \cit, which means it is both possible and desirable for \CFA to offer an abstraction mechanism for portable CPU affinity. 37 37 38 38 \subsection{Paradigms}\label{cfaparadigms} -
doc/proposals/concurrency/text/together.tex
rb10c621c r0aaac0e 7 7 8 8 \section{Threads as monitors} 9 As it was s btely alluded in section \ref{threads}, \code{threads} in \CFA are in factormonitors. This means that all the monitors features are available when using threads. For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine :9 As it was subtely alluded in section \ref{threads}, \code{threads} in \CFA are in fact monitors. This means that all the monitors features are available when using threads. For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine : 10 10 \begin{cfacode} 11 11 // Visualization declaration -
doc/proposals/concurrency/thesis.tex
rb10c621c r0aaac0e 103 103 \input{parallelism} 104 104 105 \input{internals} 106 105 107 \input{together} 106 108 -
doc/proposals/concurrency/version
rb10c621c r0aaac0e 1 0.10. 21 0.10.181
Note:
See TracChangeset
for help on using the changeset viewer.