Changes in / [9c35431:c6e2c18]


Ignore:
Files:
1 added
10 deleted
46 edited

Legend:

Unmodified
Added
Removed
  • .gitignore

    r9c35431 rc6e2c18  
    2525include
    2626share
    27 *.class
    2827
    2928# src executables, for lib and bin
  • doc/proposals/concurrency/.gitignore

    r9c35431 rc6e2c18  
    1313build/*.ind
    1414build/*.ist
    15 build/*.lof
    1615build/*.log
    17 build/*.lol
    18 build/*.lot
    1916build/*.out
    2017build/*.ps
  • doc/proposals/concurrency/Makefile

    r9c35431 rc6e2c18  
    1212style/cfa-format \
    1313annex/glossary \
    14 text/frontpgs \
    1514text/intro \
    1615text/basics \
  • doc/proposals/concurrency/annex/glossary.tex

    r9c35431 rc6e2c18  
    44{name={callsite-locking}}
    55{
    6 Locking done by the calling routine. With this technique, a routine calling a monitor routine aquires the monitor \emph{before} making the call to the actuall routine.
     6Locking done by the calling routine. With this technique, a routine calling a monitor routine will aquire the monitor \emph{before} making the call to the actuall routine.
    77}
    88
     
    1010{name={entry-point-locking}}
    1111{
    12 Locking done by the called routine. With this technique, a monitor routine called by another routine aquires the monitor \emph{after} entering the routine body but prior to any other code.
     12Locking done by the called routine. With this technique, a monitor routine called by another routine will aquire the monitor \emph{after} entering the routine body but prior to any other code.
    1313}
    1414
     
    2222{name={multiple-acquisition}}
    2323{
    24 Any locking technique that allows a single thread to acquire the same lock multiple times.
     24Any locking technique which allow any single thread to acquire a lock multiple times.
    2525}
    2626
     
    3535{name={user-level thread}}
    3636{
    37 Threads created and managed inside user-space. Each thread has its own stack and its own thread of execution. User-level threads are invisible to the underlying operating system.
     37Threads created and managed inside user-space. Each thread has its own stack and its own thread of execution. User-level threads are insisible to the underlying operating system.
    3838
    3939\textit{Synonyms : User threads, Lightweight threads, Green threads, Virtual threads, Tasks.}
     
    5151{name={fiber}}
    5252{
    53 Fibers are non-preemptive user-level threads. They share most of the caracteristics of user-level threads except that they cannot be preempted by another fiber.
     53Fibers are non-preemptive user-level threads. They share most of the caracteristics of user-level threads except that they cannot be preempted by an other fiber.
    5454
    5555\textit{Synonyms : Tasks.}
     
    5959{name={job}}
    6060{
    61 Unit of work, often sent to a thread pool or worker pool to be executed. Has neither its own stack nor its own thread of execution.
     61Unit of work, often send to a thread pool or worker pool to be executed. Has neither its own stack or its own thread of execution.
    6262
    6363\textit{Synonyms : Tasks.}
     
    7575{name={cluster}}
    7676{
    77 A group of \gls{kthread} executed in isolation.
     77TBD...
     78
     79\textit{Synonyms : None.}
     80}
     81
     82\longnewglossaryentry{cfacpu}
     83{name={processor}}
     84{
     85TBD...
    7886
    7987\textit{Synonyms : None.}
     
    8391{name={thread}}
    8492{
    85 User level threads that are the default in \CFA. Generally declared using the \code{thread} keyword.
     93TBD...
    8694
    8795\textit{Synonyms : None.}
     
    9199{name={preemption}}
    92100{
    93 Involuntary context switch imposed on threads at a specified rate.
     101TBD...
    94102
    95103\textit{Synonyms : None.}
  • doc/proposals/concurrency/annex/local.bib

    r9c35431 rc6e2c18  
    3838        keywords        = {Intel, TBB},
    3939        title   = {Intel Thread Building Blocks},
    40         note            = "\url{https://www.threadingbuildingblocks.org/}"
    4140}
    4241
     
    7574        title   = {TwoHardThings},
    7675        author  = {Martin Fowler},
    77         howpublished= "\url{https://martinfowler.com/bliki/TwoHardThings.html}",
     76        address = {https://martinfowler.com/bliki/TwoHardThings.html},
    7877        year            = 2009
    7978}
     
    8988}
    9089
    91 @book{Herlihy93,
    92         title={Transactional memory: Architectural support for lock-free data structures},
    93         author={Herlihy, Maurice and Moss, J Eliot B},
    94         volume={21},
    95         number={2},
    96         year={1993},
    97         publisher={ACM}
    98 }
    99 
    100 @manual{affinityLinux,
     90@misc{affinityLinux,
    10191        title           = "{Linux man page - sched\_setaffinity(2)}"
    10292}
    10393
    104 @manual{affinityWindows,
     94@misc{affinityWindows,
    10595        title           = "{Windows (vs.85) - SetThreadAffinityMask function}"
    10696}
    10797
    108 @manual{switchToWindows,
    109         title           = "{Windows (vs.85) - SwitchToFiber function}"
    110 }
    111 
    112 @manual{affinityFreebsd,
     98@misc{affinityFreebsd,
    11399        title           = "{FreeBSD General Commands Manual - CPUSET(1)}"
    114100}
    115101
    116 @manual{affinityNetbsd,
     102@misc{affinityNetbsd,
    117103        title           = "{NetBSD Library Functions Manual - AFFINITY(3)}"
    118104}
    119105
    120 @manual{affinityMacosx,
     106@misc{affinityMacosx,
    121107        title           = "{Affinity API Release Notes for OS X v10.5}"
    122108}
    123 
    124 
    125 @misc{NodeJs,
    126         title           = "{Node.js}",
    127         howpublished= "\url{https://nodejs.org/en/}",
    128 }
    129 
    130 @misc{SpringMVC,
    131         title           = "{Spring Web MVC}",
    132         howpublished= "\url{https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html}",
    133 }
    134 
    135 @misc{Django,
    136         title           = "{Django}",
    137         howpublished= "\url{https://www.djangoproject.com/}",
    138 }
  • doc/proposals/concurrency/figures/ext_monitor.fig

    r9c35431 rc6e2c18  
    6969         5250 3150 5250 2400
    70702 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
    71          3150 3150 3750 3150 3750 2850 5700 2850 5700 1650
     71         3150 3150 3750 3150 3750 2850 5850 2850 5850 1650
    72722 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
    73          5700 2850 6150 3000
     73         5850 2850 6150 3000
    74742 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
    7575         5100 1800 5400 1800 5400 2400 5100 2400 5100 1800
     
    91914 1 -1 0 0 0 12 0.0000 2 135 735 5100 3975 variables\001
    92924 0 0 50 -1 0 11 0.0000 2 165 855 4275 3150 Acceptables\001
    93 4 0 0 50 -1 0 11 0.0000 2 120 165 5775 2700 W\001
    94 4 0 0 50 -1 0 11 0.0000 2 120 135 5775 2400 X\001
    95 4 0 0 50 -1 0 11 0.0000 2 120 105 5775 2100 Z\001
    96 4 0 0 50 -1 0 11 0.0000 2 120 135 5775 1800 Y\001
  • doc/proposals/concurrency/figures/int_monitor.fig

    r9c35431 rc6e2c18  
    47471 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 1200 2850 125 125 1200 2850 1082 2809
    48481 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 900 2850 125 125 900 2850 782 2809
    49 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 6000 4650 105 105 6000 4650 6105 4755
    50 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 3900 4650 80 80 3900 4650 3980 4730
     491 3 0 1 -1 -1 0 0 4 0.000 1 0.0000 6225 4650 105 105 6225 4650 6330 4755
     501 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 3150 4650 80 80 3150 4650 3230 4730
     511 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4575 4650 105 105 4575 4650 4680 4755
    51522 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
    5253         3900 1950 4200 2100
     
    1061074 1 -1 0 0 0 12 0.0000 2 165 420 4050 1050 entry\001
    1071084 0 0 50 -1 0 11 0.0000 2 120 705 600 2325 Condition\001
    108 4 0 -1 0 0 0 12 0.0000 2 135 1215 6150 4725 blocked thread\001
    109 4 0 -1 0 0 0 12 0.0000 2 135 1050 4050 4725 active thread\001
     1094 0 -1 0 0 0 12 0.0000 2 180 930 6450 4725 routine ptrs\001
     1104 0 -1 0 0 0 12 0.0000 2 135 1050 3300 4725 active thread\001
     1114 0 -1 0 0 0 12 0.0000 2 135 1215 4725 4725 blocked thread\001
  • doc/proposals/concurrency/style/cfa-format.tex

    r9c35431 rc6e2c18  
    178178    language = C,
    179179    style=defaultStyle,
    180     captionpos=b,
    181180    #1
    182181  }
     
    187186    language = CFA,
    188187    style=cfaStyle,
    189     captionpos=b,
    190188    #1
    191189  }
     
    196194    language = pseudo,
    197195    style=pseudoStyle,
    198     captionpos=b,
    199196    #1
    200197  }
     
    205202    language = c++,
    206203    style=defaultStyle,
    207     captionpos=b,
    208204    #1
    209205  }
     
    214210    language = c++,
    215211    style=defaultStyle,
    216     captionpos=b,
    217212    #1
    218213  }
     
    223218    language = java,
    224219    style=defaultStyle,
    225     captionpos=b,
    226220    #1
    227221  }
     
    232226    language = scala,
    233227    style=defaultStyle,
    234     captionpos=b,
    235228    #1
    236229  }
     
    241234    language = sml,
    242235    style=defaultStyle,
    243     captionpos=b,
    244236    #1
    245237  }
     
    250242    language = D,
    251243    style=defaultStyle,
    252     captionpos=b,
    253244    #1
    254245  }
     
    259250    language = rust,
    260251    style=defaultStyle,
    261     captionpos=b,
    262252    #1
    263253  }
     
    268258    language = Golang,
    269259    style=defaultStyle,
    270     captionpos=b,
    271260    #1
    272261  }
  • doc/proposals/concurrency/text/basics.tex

    r9c35431 rc6e2c18  
    1111Execution 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.
    1212
    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, stack-full 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 (a.k.a non-preemptive scheduling). The oracle/scheduler can either be a stack-less or stack-full 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.
    14 
    15 A scheduler introduces order of execution uncertainty, while preemption introduces uncertainty about where context-switches occur. Mutual-exclusion and synchronization are ways of limiting non-determinism in a concurrent system. Now it is important to understand that uncertainty is desirable; uncertainty can be used by runtime 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.
     13Therefore, 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 (a.k.a non-preemptive scheduling). 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.
     14
     15A scheduler introduces order of execution uncertainty, while preemption introduces uncertainty about where context-switches occur. Mutual-exclusion and synchronisation are ways of limiting non-determinism in a concurrent system. Now it is important to understand that uncertainty is desireable; uncertainty can be used by runtime 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.
    1616
    1717\section{\protect\CFA 's Thread Building Blocks}
    18 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 programs to take advantage of parallelism. 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.
     18One 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 programs to take advantage of parallelism. 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.
    1919
    2020\section{Coroutines: A stepping stone}\label{coroutine}
    2121While 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-switches 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}.
    2222
    23 \begin{table}
     23\begin{figure}
    2424\begin{center}
    2525\begin{tabular}{c @{\hskip 0.025in}|@{\hskip 0.025in} c @{\hskip 0.025in}|@{\hskip 0.025in} c}
     
    6262void fibonacci_array(
    6363        int n,
    64         int* array
     64        int * array
    6565) {
    6666        int f1 = 0; int f2 = 1;
     
    9999
    100100int fibonacci_state(
    101         Iterator_t* it
     101        Iterator_t * it
    102102) {
    103103        int f;
     
    129129\end{tabular}
    130130\end{center}
    131 \caption{Different implementations of a Fibonacci sequence generator in C.},
     131\caption{Different implementations of a fibonacci sequence generator in C.}
    132132\label{lst:fibonacci-c}
    133 \end{table}
    134 
    135 A good example of a problem made easier with coroutines is generators, like the Fibonacci sequence. This problem comes with the challenge of decoupling how a sequence is generated and how it is used. Table \ref{lst: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 is used, while the rightmost approach requires holding internal state between calls on behalf of the generator and makes it much harder to handle corner cases like the Fibonacci seed.
    136 
    137 Listing \ref{lst:fibonacci-cfa} is an example of a solution to the Fibonacci problem using \CFA coroutines, where the coroutine stack holds sufficient state for the next 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 as easy to use as the \code{fibonacci_state} solution, while the implementation is very similar to the \code{fibonacci_func} example.
     133\end{figure}
     134
     135A good example of a problem made easier with coroutines is generators, like the fibonacci sequence. This problem comes with the challenge of decoupling how a sequence is generated and how it is used. Figure \ref{lst: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 is used, while the rightmost approach requires holding internal state between calls on behalf of the generator and makes it much harder to handle corner cases like the Fibonacci seed.
     136
     137Figure \ref{lst:fibonacci-cfa} is an example of a solution to the fibonnaci problem using \CFA coroutines, where the coroutine stack holds 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 as easy to use as the \code{fibonacci_state} solution, while the imlpementation is very similar to the \code{fibonacci_func} example.
    138138
    139139\begin{figure}
    140 \begin{cfacode}[caption={Implementation of Fibonacci using coroutines},label={lst:fibonacci-cfa}]
     140\begin{cfacode}
    141141coroutine Fibonacci {
    142142        int fn; //used for communication
    143143};
    144144
    145 void ?{}(Fibonacci& this) { //constructor
     145void ?{}(Fibonacci & this) { //constructor
    146146        this.fn = 0;
    147147}
    148148
    149 //main automatically called on first resume
    150 void main(Fibonacci& this) with (this) {
     149//main automacically called on first resume
     150void main(Fibonacci & this) with (this) {
    151151        int fn1, fn2;           //retained between resumes
    152152        fn  = 0;
     
    167167}
    168168
    169 int next(Fibonacci& this) {
     169int next(Fibonacci & this) {
    170170        resume(this); //transfer to last suspend
    171171        return this.fn;
     
    179179}
    180180\end{cfacode}
     181\caption{Implementation of fibonacci using coroutines}
     182\label{lst:fibonacci-cfa}
    181183\end{figure}
    182184
    183 Listing \ref{lst:fmt-line} shows the \code{Format} coroutine for restructuring text into groups of character blocks of fixed size. The example takes advantage of resuming coroutines in the constructor to simplify the code and highlights the idea that interesting control flow can occur in the constructor.
     185Figure \ref{lst:fmt-line} shows the \code{Format} coroutine which rearranges text in order to group characters into blocks of fixed size. The example takes advantage of resuming coroutines in the constructor to simplify the code and highlights the idea that interesting control flow can occur in the constructor.
    184186
    185187\begin{figure}
    186 \begin{cfacode}[tabsize=3,caption={Formatting text into lines of 5 blocks of 4 characters.},label={lst:fmt-line}]
     188\begin{cfacode}[tabsize=3]
    187189//format characters into blocks of 4 and groups of 5 blocks per line
    188190coroutine Format {
     
    191193};
    192194
    193 void  ?{}(Format& fmt) {
     195void  ?{}(Format & fmt) {
    194196        resume( fmt );                                                  //prime (start) coroutine
    195197}
    196198
    197 void ^?{}(Format& fmt) with fmt {
     199void ^?{}(Format & fmt) with fmt {
    198200        if ( fmt.g != 0 || fmt.b != 0 )
    199201        sout | endl;
    200202}
    201203
    202 void main(Format& fmt) with fmt {
     204void main(Format & fmt) with fmt {
    203205        for ( ;; ) {                                                    //for as many characters
    204206                for(g = 0; g < 5; g++) {                //groups of 5 blocks
     
    228230}
    229231\end{cfacode}
     232\caption{Formatting text into lines of 5 blocks of 4 characters.}
     233\label{lst:fmt-line}
    230234\end{figure}
    231235
    232236\subsection{Construction}
    233 One important design challenge for implementing 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 fully constructed 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.
    234 
    235 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. There are several solutions to this problem but the chosen options effectively forces the design of the coroutine.
     237One 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 fully constructed 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.
     238
     239The 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.
    236240
    237241Furthermore, \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:
     
    254258
    255259\begin{ccode}
    256 extern void async(/* omitted */, void (*func)(void*), void* obj);
    257 
    258 void noop(/* omitted */, void* obj){}
     260extern void async(/* omitted */, void (*func)(void *), void *obj);
     261
     262void noop(/* omitted */, void *obj){}
    259263
    260264void bar(){
    261265        int a;
    262         void _thunk0(int* _p0){
     266        void _thunk0(int *_p0){
    263267                /* omitted */
    264268                noop(/* omitted */, _p0);
    265269        }
    266270        /* omitted */
    267         async(/* omitted */, ((void (*)(void*))(&_thunk0)), (&a));
     271        async(/* omitted */, ((void (*)(void *))(&_thunk0)), (&a));
    268272}
    269273\end{ccode}
    270 The problem in this example is a storage management issue, the function pointer \code{_thunk0} is only valid until the end of the block, which limits the viable solutions because storing the function pointer for too long causes Undefined Behavior; i.e., the stack-based thunk being destroyed before it can be used. This challenge is an extension of challenges that come with second-class routines. Indeed, GCC nested routines also have the limitation that nested routine cannot be passed outside of the declaration scope. The case of coroutines and threads is simply an extension of this problem to multiple call-stacks.
     274The problem in this example is a storage management issue, the function pointer \code{_thunk0} is only valid until the end of the block, which limits the viable solutions because storing the function pointer for too long causes undefined behavior; i.e., the stack-based thunk being destroyed before it can be used. This challenge is an extension of challenges that come with second-class routines. Indeed, GCC nested routines also have the limitation that nested routine cannot be passed outside of the declaration scope. The case of coroutines and threads is simply an extension of this problem to multiple call-stacks.
    271275
    272276\subsection{Alternative: Composition}
    273 One solution to this challenge is to use composition/containment, where coroutine fields are added to manage the coroutine.
     277One solution to this challenge is to use composition/containement, where coroutine fields are added to manage the coroutine.
    274278
    275279\begin{cfacode}
     
    279283};
    280284
    281 void FibMain(void*) {
     285void FibMain(void *) {
    282286        //...
    283287}
    284288
    285 void ?{}(Fibonacci& this) {
     289void ?{}(Fibonacci & this) {
    286290        this.fn = 0;
    287291        //Call constructor to initialize coroutine
     
    289293}
    290294\end{cfacode}
    291 The downside of this approach is that users need to correctly construct the coroutine handle before using it. Like any other objects, the user must carefully choose construction order to prevent usage of objects not yet constructed. However, in the case of coroutines, users must also pass to the coroutine information about the coroutine main, like in the previous example. This opens the door for user errors and requires extra runtime storage to pass at runtime information that can be known statically.
     295The downside of this approach is that users need to correctly construct the coroutine handle before using it. Like any other objects, doing so the users carefully choose construction order to prevent usage of unconstructed objects. However, in the case of coroutines, users must also pass to the coroutine information about the coroutine main, like in the previous example. This opens the door for user errors and requires extra runtime storage to pass at runtime information that can be known statically.
    292296
    293297\subsection{Alternative: Reserved keyword}
     
    299303};
    300304\end{cfacode}
    301 The \code{coroutine} keyword means the compiler can find and inject code where needed. The downside of this approach is that it makes coroutine a special case in the language. Users wanting 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 still be constructed by users without using the language support. The reserved keywords are only present to improve ease of use for the common cases.
    302 
    303 \subsection{Alternative: Lambda Objects}
    304 
    305 For coroutines as for threads, many implementations are based on routine pointers or function objects~\cite{Butenhof97, ANSI14:C++, MS:VisualC++, BoostCoroutines15}. For example, Boost implements coroutines in terms of four functor object types:
     305The \code{coroutine} keyword means the compiler can find and inject code where needed. The downside of this approach is that it makes coroutine a special case in the language. Users wantint 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 still be constructed by users without using the language support. The reserved keywords are only present to improve ease of use for the common cases.
     306
     307\subsection{Alternative: Lamda Objects}
     308
     309For coroutines as for threads, many implementations are based on routine pointers or function objects\cite{Butenhof97, ANSI14:C++, MS:VisualC++, BoostCoroutines15}. For example, Boost implements coroutines in terms of four functor object types:
    306310\begin{cfacode}
    307311asymmetric_coroutine<>::pull_type
     
    314318A variation of this would be to use a simple function pointer in the same way pthread does for threads :
    315319\begin{cfacode}
    316 void foo( coroutine_t cid, void* arg ) {
    317         int* value = (int*)arg;
     320void foo( coroutine_t cid, void * arg ) {
     321        int * value = (int *)arg;
    318322        //Coroutine body
    319323}
     
    325329}
    326330\end{cfacode}
    327 This semantics is more common for thread interfaces but coroutines work equally well. As discussed in section \ref{threads}, this approach is superseded by static approaches in terms of expressivity.
     331This semantics is more common for thread interfaces than coroutines works equally well. As discussed in section \ref{threads}, this approach is superseeded by static approaches in terms of expressivity.
    328332
    329333\subsection{Alternative: Trait-based coroutines}
     
    333337\begin{cfacode}
    334338trait is_coroutine(dtype T) {
    335       void main(T& this);
    336       coroutine_desc* get_coroutine(T& this);
    337 };
    338 
    339 forall( dtype T | is_coroutine(T) ) void suspend(T&);
    340 forall( dtype T | is_coroutine(T) ) void resume (T&);
    341 \end{cfacode}
    342 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 implement the main routine.
     339      void main(T & this);
     340      coroutine_desc * get_coroutine(T & this);
     341};
     342
     343forall( dtype T | is_coroutine(T) ) void suspend(T &);
     344forall( dtype T | is_coroutine(T) ) void resume (T &);
     345\end{cfacode}
     346This 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.
    343347
    344348\begin{center}
     
    355359
    356360static inline
    357 coroutine_desc* get_coroutine(
    358         struct MyCoroutine& this
     361coroutine_desc * get_coroutine(
     362        struct MyCoroutine & this
    359363) {
    360364        return &this.__cor;
    361365}
    362366
    363 void main(struct MyCoroutine* this);
     367void main(struct MyCoroutine * this);
    364368\end{cfacode}
    365369\end{tabular}
    366370\end{center}
    367371
    368 The combination of these two approaches allows users new to coroutining and concurrency to have an easy and concise specification, while more advanced users have tighter control on memory layout and initialization.
     372The 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.
    369373
    370374\section{Thread Interface}\label{threads}
     
    375379\end{cfacode}
    376380
    377 As for coroutines, the keyword is a thin wrapper around a \CFA trait:
     381As for coroutines, the keyword is a thin wrapper arount a \CFA trait:
    378382
    379383\begin{cfacode}
     
    385389\end{cfacode}
    386390
    387 Obviously, for this thread implementation to be useful 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 supersedes 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
     391Obviously, 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
    388392\begin{cfacode}
    389393thread foo {};
     
    412416        this.func( this.arg );
    413417}
    414 
    415 void hello(/*unused*/ int) {
    416         sout | "Hello World!" | endl;
    417 }
    418 
    419 int main() {
    420         FuncRunner f = {hello, 42};
    421         return 0'
    422 }
    423418\end{cfacode}
    424419
     
    444439\end{cfacode}
    445440
    446 This semantic has several advantages over explicit semantics: a thread is always started and stopped exactly once, users cannot make any programming errors, and it naturally scales to multiple threads meaning basic synchronization is very simple.
     441This semantic has several advantages over explicit semantics: a thread is always started and stopped exaclty once, users cannot make any progamming errors, and it naturally scales to multiple threads meaning basic synchronisation is very simple.
    447442
    448443\begin{cfacode}
     
    452447
    453448//main
    454 void main(MyThread& this) {
     449void main(MyThread & this) {
    455450        //...
    456451}
     
    466461\end{cfacode}
    467462
    468 However, one of the drawbacks of this approach is that threads always form a lattice, i.e., they are always destroyed in the 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.
     463However, one of the drawbacks of this approach is that threads now always form a lattice, that is they are always destroyed in the 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.
    469464
    470465\begin{cfacode}
     
    473468};
    474469
    475 void main(MyThread& this) {
     470void main(MyThread & this) {
    476471        //...
    477472}
    478473
    479474void foo() {
    480         MyThread* long_lived;
     475        MyThread * long_lived;
    481476        {
    482477                //Start a thread at the beginning of the scope
  • doc/proposals/concurrency/text/cforall.tex

    r9c35431 rc6e2c18  
    11% ======================================================================
    22% ======================================================================
    3 \chapter{\CFA Overview}
     3\chapter{Cforall Overview}
    44% ======================================================================
    55% ======================================================================
     
    77The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency.
    88
    9 \CFA is an 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 receiver (e.g., {\tt this}), it does have some notion of objects\footnote{C defines the term objects as : ``region of data storage in the execution environment, the contents of which can represent
    10 values''~\cite[3.15]{C11}}, most importantly construction and destruction of objects. Most of the following code examples can be found 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 receiver (e.g., this), it does have some notion of objects\footnote{C defines the term objects as : ``region of data storage in the execution environment, the contents of which can represent
     10values''\cite[3.15]{C11}}, most importantly construction and destruction of objects. Most of the following code examples can be found on the \CFA website \cite{www-cfa}
    1111
    12 % ======================================================================
    1312\section{References}
    1413
    15 Like \CC, \CFA introduces rebind-able references providing multiple dereferencing as an alternative to pointers. In regards to concurrency, the semantic difference between pointers and references are not particularly relevant, but since this document uses mostly references, here is a quick overview of the semantics:
     14Like \CC, \CFA introduces rebindable references providing multiple dereferecing as an alternative to pointers. In regards to concurrency, the semantic difference between pointers and references are not particularly relevant, but since this document uses mostly references, here is a quick overview of the semantics:
    1615\begin{cfacode}
    1716int x, *p1 = &x, **p2 = &p1, ***p3 = &p2,
     
    2221*p3   = ...;                                            //change p2
    2322int y, z, & ar[3] = {x, y, z};          //initialize array of references
    24 typeof( ar[1]) p;                                       //is int, referenced object type
    25 typeof(&ar[1]) q;                                       //is int &, reference type
    26 sizeof( ar[1]) == sizeof(int);          //is true, referenced object size
    27 sizeof(&ar[1]) == sizeof(int *);        //is true, reference size
     23typeof( ar[1]) p;                                       //is int, i.e., the type of referenced object
     24typeof(&ar[1]) q;                                       //is int &, i.e., the type of reference
     25sizeof( ar[1]) == sizeof(int);          //is true, i.e., the size of referenced object
     26sizeof(&ar[1]) == sizeof(int *);        //is true, i.e., the size of a reference
    2827\end{cfacode}
    29 The important take away from this code example is that a reference offers a handle to an object, much like a pointer, but which is automatically dereferenced for convenience.
     28The important take away from this code example is that references offer a handle to an object, much like pointers, but which is automatically dereferenced for convinience.
    3029
    31 % ======================================================================
    3230\section{Overloading}
    3331
    34 Another important feature of \CFA is function overloading as in Java and \CC, where routines with the same name are selected based on the number 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.
     32Another important feature of \CFA is function overloading as in Java and \CC, where routines with the same name are selected based on the number 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.
    3533\begin{cfacode}
    3634//selection based on type and number of parameters
     
    5048This 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}, routine \code{main} is an example that benefits from overloading.
    5149
    52 % ======================================================================
    5350\section{Operators}
    5451Overloading 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 occur, e.g.:
     
    7067While concurrency does not use operator overloading directly, this feature is more important as an introduction for the syntax of constructors.
    7168
    72 % ======================================================================
    7369\section{Constructors/Destructors}
    7470Object 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 :
     
    8682}
    8783int main() {
    88         S x = {10}, y = {100};          //implicit calls: ?{}(x, 10), ?{}(y, 100)
     84        S x = {10}, y = {100};          //implict calls: ?{}(x, 10), ?{}(y, 100)
    8985        ...                                                     //use x and y
    9086        ^x{};  ^y{};                            //explicit calls to de-initialize
    9187        x{20};  y{200};                         //explicit calls to reinitialize
    9288        ...                                                     //reuse x and y
    93 }                                                               //implicit calls: ^?{}(y), ^?{}(x)
     89}                                                               //implict calls: ^?{}(y), ^?{}(x)
    9490\end{cfacode}
    9591The 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.
     
    10399delete(s);                              //deallocation, call destructor
    104100\end{cfacode}
    105 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.
     101Note 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.
    106102
    107 % ======================================================================
    108103\section{Parametric Polymorphism}
    109 Routines in \CFA can also be reused for multiple types. This capability is done using the \code{forall} clause, which gives \CFA its name. \code{forall} clauses allow separately compiled routines to support generic usage over multiple types. For example, the following sum function works for any type that supports construction from 0 and addition :
     104Routines in \CFA can also be reused for multiple types. This capability is done using the \code{forall} clause which gives \CFA its name. \code{forall} clauses allow separately compiled routines to support generic usage over multiple types. For example, the following sum function works for any type that supports construction from 0 and addition :
    110105\begin{cfacode}
    111106//constraint type, 0 and +
     
    135130\end{cfacode}
    136131
    137 Note that the type use for assertions can be either an \code{otype} or a \code{dtype}. Types declares as \code{otype} refer to ``complete'' objects, i.e., objects with a size, a default constructor, a copy constructor, a destructor and an assignment operator. Using \code{dtype} on the other hand has none of these assumptions but is extremely restrictive, it only guarantees the object is addressable.
    138 
    139 % ======================================================================
    140132\section{with Clause/Statement}
    141133Since \CFA lacks the concept of a receiver, certain functions end-up needing to repeat variable names often. To remove this inconvenience, \CFA provides the \code{with} statement, which opens an aggregate scope making its fields directly accessible (like Pascal).
     
    143135struct S { int i, j; };
    144136int mem(S & this) with (this)           //with clause
    145         i = 1;                                                  //this->i
    146         j = 2;                                                  //this->j
     137        i = 1;                                          //this->i
     138        j = 2;                                          //this->j
    147139}
    148140int foo() {
    149141        struct S1 { ... } s1;
    150142        struct S2 { ... } s2;
    151         with (s1)                                               //with statement
     143        with (s1)                                       //with statement
    152144        {
    153                 //access fields of s1 without qualification
     145                //access fields of s1
     146                //without qualification
    154147                with (s2)                                       //nesting
    155148                {
    156                         //access fields of s1 and s2 without qualification
     149                        //access fields of s1 and s2
     150                        //without qualification
    157151                }
    158152        }
    159         with (s1, s2)                                   //scopes open in parallel
     153        with (s1, s2)                           //scopes open in parallel
    160154        {
    161                 //access fields of s1 and s2 without qualification
     155                //access fields of s1 and s2
     156                //without qualification
    162157        }
    163158}
  • doc/proposals/concurrency/text/concurrency.tex

    r9c35431 rc6e2c18  
    44% ======================================================================
    55% ======================================================================
    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~\cite{CSP,Go} 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 library still has to take both paradigms into account.
    7 
    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 desirable to have a higher-level construct be the core concurrency paradigm~\cite{HPP:Study}.
    9 
    10 An approach that is worth mentioning because it is gaining in popularity is transactional memory~\cite{Herlihy93}. While this approach is even pursued by system languages like \CC~\cite{Cpp-Transactions}, 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.
     6Several tool can be used to solve concurrency challenges. Since many of these challenges appear with the use of mutable shared-state, some languages and libraries simply disallow mutable shared-state (Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, Akka (Scala)~\cite{Akka}). In these paradigms, interaction among concurrent objects relies on message passing~\cite{Thoth,Harmony,V-Kernel} or other paradigms closely relate to networking concepts (channels\cite{CSP,Go} for example). However, in languages that use routine calls as their core abstraction-mechanism, these approaches force a clear distinction between concurrent and non-concurrent paradigms (i.e., message passing versus routine call). This distinction in turn means that, in order to be effective, programmers need to learn two sets of designs patterns. While this distinction can be hidden away in library code, effective use of the librairy still has to take both paradigms into account.
     7
     8Approaches based on shared memory are more closely related to non-concurrent paradigms since they often rely on basic constructs like routine calls and shared objects. At the lowest level, concurrent paradigms are implemented as atomic operations and locks. Many such mechanisms have been proposed, including semaphores~\cite{Dijkstra68b} and path expressions~\cite{Campbell74}. However, for productivity reasons it is desireable to have a higher-level construct be the core concurrency paradigm~\cite{HPP:Study}.
     9
     10An approach that is worth mentioning because it is gaining in popularity is transactionnal memory~\cite{Dice10}[Check citation]. While this approach is even pursued by system languages like \CC\cite{Cpp-Transactions}, 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.
    1111
    1212One 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.
    1313
    1414\section{Basics}
    15 Non-determinism requires concurrent systems to offer support for mutual-exclusion and synchronization. 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.
     15Non-determinism requires concurrent systems to offer support for mutual-exclusion and synchronisation. Mutual-exclusion is the concept that only a fixed number of threads can access a critical section at any given time, where a critical section is a group of instructions on an associated portion of data that requires the restricted access. On the other hand, synchronization enforces relative ordering of execution and synchronization tools provide numerous mechanisms to establish timing relationships among threads.
    1616
    1717\subsection{Mutual-Exclusion}
    18 As mentioned 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 organizing for multiple locks to be used while preventing deadlocks. Easing composability is another feature higher-level mutual-exclusion mechanisms often offer.
     18As mentionned above, mutual-exclusion is the guarantee that only a fix number of threads can enter a critical section at once. However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use. Methods range from low-level locks, which are fast and flexible but require significant attention to be correct, to  higher-level mutual-exclusion methods, which sacrifice some performance in order to improve ease of use. Ease of use comes by either guaranteeing some problems cannot occur (e.g., being deadlock free) or by offering a more explicit coupling between data and corresponding critical section. For example, the \CC \code{std::atomic<T>} offers an easy way to express mutual-exclusion on a restricted set of operations (e.g.: reading/writing large types atomically). Another challenge with low-level locks is composability. Locks have restricted composability because it takes careful organising for multiple locks to be used while preventing deadlocks. Easing composability is another feature higher-level mutual-exclusion mechanisms often offer.
    1919
    2020\subsection{Synchronization}
    21 As for mutual-exclusion, low-level synchronization 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 a simpler solution to otherwise involved challenges. As mentioned above, synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}. Most of the time, synchronization happens within a critical section, where threads must acquire mutual-exclusion 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 is 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}. The classic example is the thread that finishes using a resource and unblocks a thread waiting to use the resource, but the unblocked thread must compete again to acquire the resource. 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 flag variables to detect barging threads are said to be using barging avoidance, while algorithms that baton-pass locks~\cite{Andrews89} between threads instead of releasing the locks are said to be using barging prevention.
     21As for mutual-exclusion, low-level synchronisation primitives often offer good performance and good flexibility at the cost of ease of use. Again, higher-level mechanism often simplify usage by adding better coupling between synchronization and data, e.g.: message passing, or offering simpler solution to otherwise involved challenges. As mentioned above, synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}. Most of the time, synchronisation happens within a critical section, where threads must acquire mutual-exclusion 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}. The classic exmaple is the thread that finishes using a ressource and unblocks a thread waiting to use the resource, but the unblocked thread must compete again to acquire the resource. 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.
    2222
    2323% ======================================================================
     
    2929\begin{cfacode}
    3030typedef /*some monitor type*/ monitor;
    31 int f(monitor& m);
     31int f(monitor & m);
    3232
    3333int main() {
     
    4242% ======================================================================
    4343% ======================================================================
    44 The above monitor example displays some of the intrinsic characteristics. First, it is necessary to use pass-by-reference over pass-by-value for monitor routines. This semantics is important, because at their core, monitors are implicit mutual-exclusion objects (locks), and these objects cannot be copied. Therefore, monitors are implicitly non-copy-able objects (\code{dtype}).
     44The above monitor example displays some of the intrinsic characteristics. First, it is necessary to use pass-by-reference over pass-by-value for monitor routines. This semantics is important because at their core, monitors are implicit mutual-exclusion objects (locks), and these objects cannot be copied. Therefore, monitors are implicitly non-copyable objects.
    4545
    4646Another aspect to consider is when a monitor acquires its mutual exclusion. For example, a monitor may need to be passed through multiple helper routines that do not acquire the monitor mutual-exclusion on entry. Pass through can occur for generic helper routines (\code{swap}, \code{sort}, etc.) or specific helper routines like the following to implement an atomic counter :
     
    7171\end{tabular}
    7272\end{center}
    73 Notice how the counter is used without any explicit synchronization and yet supports thread-safe semantics for both reading and writing, which is similar in usage to \CC \code{atomic} template.
    74 
    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 con\-structed should never be shared and therefore does not require mutual exclusion. Furthermore, it allows the implementation greater freedom when it initializes the monitor locking. 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 the same monitor multiple times without deadlock. For example, listing \ref{fig:search} uses recursion and \gls{multi-acq} to print values inside a binary tree.
     73Notice how the counter is used without any explicit synchronisation and yet supports thread-safe semantics for both reading and writting, which is similar in usage to \CC \code{atomic} template.
     74
     75Here, the constructor(\code{?\{\}}) uses the \code{nomutex} keyword to signify that it does not acquire the monitor mutual-exclusion when constructing. This semantics is because an object not yet con\-structed should never be shared and therefore does not require mutual exclusion. The prefix increment operator uses \code{mutex} to protect the incrementing process from race conditions. Finally, there is a conversion operator from \code{counter_t} to \code{size_t}. This conversion may or may not require the \code{mutex} keyword depending on whether or not reading a \code{size_t} is an atomic operation.
     76
     77For maximum usability, monitors use \gls{multi-acq} semantics, which means a single thread can acquire the same monitor multiple times without deadlock. For example, figure \ref{fig:search} uses recursion and \gls{multi-acq} to print values inside a binary tree.
    7878\begin{figure}
    79 \begin{cfacode}[caption={Recursive printing algorithm using \gls{multi-acq}.},label={fig:search}]
     79\label{fig:search}
     80\begin{cfacode}
    8081monitor printer { ... };
    8182struct tree {
     
    9192}
    9293\end{cfacode}
    93 \end{figure}
    94 
    95 Having both \code{mutex} and \code{nomutex} keywords is redundant based on the meaning of a routine having neither of these keywords. For example, it is reasonable that it should default to the safest option (\code{mutex}) when given a routine without qualifiers \code{void foo(counter_t & this)}, whereas assuming \code{nomutex} is unsafe and may cause subtle errors. On the other hand, \code{nomutex} is the ``normal'' parameter behaviour, it effectively states explicitly that ``this routine is not special''. Another alternative is making exactly one of these keywords mandatory, which provides 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}.
     94\caption{Recursive printing algorithm using \gls{multi-acq}.}
     95\end{figure}
     96
     97Having both \code{mutex} and \code{nomutex} keywords is redundant based on the meaning of a routine having neither of these keywords. For example, given a routine without qualifiers \code{void foo(counter_t & this)}, then it is reasonable that it should default to the safest option \code{mutex}, whereas assuming \code{nomutex} is unsafe and may cause subtle errors. In fact, \code{nomutex} is the ``normal'' parameter behaviour, with the \code{nomutex} keyword effectively stating explicitly that ``this routine is not special''. Another alternative is making exactly one of these keywords mandatory, which provides 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}.
    9698
    9799The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations:
    98100\begin{cfacode}
    99 int f1(monitor& mutex m);
     101int f1(monitor & mutex m);
    100102int f2(const monitor & mutex m);
    101 int f3(monitor** mutex m);
    102 int f4(monitor* mutex m []);
     103int f3(monitor ** mutex m);
     104int f4(monitor * mutex m []);
    103105int f5(graph(monitor*) & mutex m);
    104106\end{cfacode}
    105 The problem is to identify 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 identify 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 behaviour 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:
    106 \begin{cfacode}
    107 int f1(monitor& mutex m);   //Okay : recommended case
    108 int f2(monitor* mutex m);   //Okay : could be an array but probably not
    109 int f3(monitor mutex m []);  //Not Okay : Array of unknown length
    110 int f4(monitor** mutex m);  //Not Okay : Could be an array
    111 int f5(monitor* mutex m []); //Not Okay : Array of unknown length
     107The problem is to indentify which object(s) should be acquired. Furthermore, each object needs to be acquired only once. In the case of simple routines like \code{f1} and \code{f2} it is easy to identify an exhaustive list of objects to acquire on entry. Adding indirections (\code{f3}) still allows the compiler and programmer to indentify which object is acquired. However, adding in arrays (\code{f4}) makes it much harder. Array lengths are not necessarily known in C, and even then making sure objects are only acquired once becomes none-trivial. This problem can be extended to absurd limits like \code{f5}, which uses a graph of monitors. To make the issue tractable, this project imposes the requirement that a routine may only acquire one monitor per parameter and it must be the type of the parameter with at most one level of indirection (ignoring potential qualifiers). Also note that while routine \code{f3} can be supported, meaning that monitor \code{**m} is be acquired, passing an array to this routine would be type safe and yet result in undefined behavior because only the first element of the array is acquired. However, this ambiguity is part of the C type-system with respects to arrays. For this reason, \code{mutex} is disallowed in the context where arrays may be passed:
     108\begin{cfacode}
     109int f1(monitor & mutex m);   //Okay : recommanded case
     110int f2(monitor * mutex m);   //Okay : could be an array but probably not
     111int f3(monitor mutex m []);  //Not Okay : Array of unkown length
     112int f4(monitor ** mutex m);  //Not Okay : Could be an array
     113int f5(monitor * mutex m []); //Not Okay : Array of unkown length
    112114\end{cfacode}
    113115Note that not all array functions are actually distinct in the type system. However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic.
     
    121123f(a,b);
    122124\end{cfacode}
    123 While OO monitors could be extended with a mutex qualifier for multiple-monitor calls, no example of this feature could be found. The capability 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 acquisition is consistent across calls to different routines using the same monitors as arguments. This consistent ordering means acquiring multiple monitors is safe from deadlock when using \gls{bulk-acq}. However, users can still force the acquiring order. For example, notice which routines use \code{mutex}/\code{nomutex} and how this affects acquiring order:
    124 \begin{cfacode}
    125 void foo(A& mutex a, B& mutex b) { //acquire a & b
     125While OO monitors could be extended with a mutex qualifier for multiple-monitor calls, no example of this feature could be found. 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 different routines using the same monitors as arguments. This consistent ordering means acquiring multiple monitors in the way is safe from deadlock. However, users can still force the acquiring order. For example, notice which routines use \code{mutex}/\code{nomutex} and how this affects aquiring order:
     126\begin{cfacode}
     127void foo(A & mutex a, B & mutex b) { //acquire a & b
    126128        ...
    127129}
    128130
    129 void bar(A& mutex a, B& /*nomutex*/ b) { //acquire a
     131void bar(A & mutex a, B & /*nomutex*/ b) { //acquire a
    130132        ... foo(a, b); ... //acquire b
    131133}
    132134
    133 void baz(A& /*nomutex*/ a, B& mutex b) { //acquire b
     135void baz(A & /*nomutex*/ a, B & mutex b) { //acquire b
    134136        ... foo(a, b); ... //acquire a
    135137}
     
    137139The \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.
    138140
    139 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 difference means that calling these routines concurrently may lead to deadlock and is therefore Undefined Behavior. As shown~\cite{Lister77}, solving this problem requires:
     141However, such use leads to the lock acquiring order problem. In the example above, the user uses implicit ordering in the case of function \code{foo} but explicit ordering in the case of \code{bar} and \code{baz}. This subtle mistake means that calling these routines concurrently may lead to deadlock and is therefore undefined behavior. As shown\cite{Lister77}, solving this problem requires:
    140142\begin{enumerate}
    141143        \item Dynamically tracking of the monitor-call order.
    142144        \item Implement rollback semantics.
    143145\end{enumerate}
    144 While the first requirement is already a significant constraint on the system, implementing a general rollback semantics in a C-like language is still prohibitively complex~\cite{Dice10}. In \CFA, users simply need to be careful when acquiring multiple monitors at the same time or only use \gls{bulk-acq} of all the monitors. While \CFA provides only a partial solution, most systems provide no solution and the \CFA partial solution handles many useful cases.
     146While the first requirement is already a significant constraint on the system, implementing a general rollback semantics in a C-like language is still prohibitively complex \cite{Dice10}. 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. While \CFA provides only a partial solution, many system provide no solution and the \CFA partial solution handles many useful cases.
    145147
    146148For example, \gls{multi-acq} and \gls{bulk-acq} can be used together in interesting ways:
     
    155157}
    156158\end{cfacode}
    157 This example shows a trivial solution to the bank-account transfer-problem~\cite{BankTransfer}. Without \gls{multi-acq} and \gls{bulk-acq}, the solution to this problem is much more involved and requires careful engineering.
     159This example shows a trivial solution to the bank-account transfer-problem\cite{BankTransfer}. Without \gls{multi-acq} and \gls{bulk-acq}, the solution to this problem is much more involved and requires carefull engineering.
    158160
    159161\subsection{\code{mutex} statement} \label{mutex-stmt}
    160162
    161 The call semantics discussed above have one software engineering issue, only a named routine can acquire the mutual-exclusion of a set of monitor. \CFA offers the \code{mutex} statement to workaround the need for unnecessary names, avoiding a major software engineering problem~\cite{2FTwoHardThings}. Table \ref{lst:mutex-stmt} shows an example of the \code{mutex} statement, which introduces a new scope in which the mutual-exclusion of a set of monitor is acquired. Beyond naming, the \code{mutex} statement has no semantic difference from a routine call with \code{mutex} parameters.
    162 
    163 \begin{table}
     163The call semantics discussed aboved have one software engineering issue, only a named routine can acquire the mutual-exclusion of a set of monitor. \CFA offers the \code{mutex} statement to workaround the need for unnecessary names, avoiding a major software engineering problem\cite{2FTwoHardThings}. Listing \ref{lst:mutex-stmt} shows an example of the \code{mutex} statement, which introduces a new scope in which the mutual-exclusion of a set of monitor is acquired. Beyond naming, the \code{mutex} statement has no semantic difference from a routine call with \code{mutex} parameters.
     164
     165\begin{figure}
    164166\begin{center}
    165167\begin{tabular}{|c|c|}
     
    168170\begin{cfacode}[tabsize=3]
    169171monitor M {};
    170 void foo( M & mutex m1, M & mutex m2 ) {
     172void foo( M & mutex m ) {
    171173        //critical section
    172174}
    173175
    174 void bar( M & m1, M & m2 ) {
    175         foo( m1, m2 );
     176void bar( M & m ) {
     177        foo( m );
    176178}
    177179\end{cfacode}&\begin{cfacode}[tabsize=3]
    178180monitor M {};
    179 void bar( M & m1, M & m2 ) {
    180         mutex(m1, m2) {
     181void bar( M & m ) {
     182        mutex(m) {
    181183                //critical section
    182184        }
     
    189191\caption{Regular call semantics vs. \code{mutex} statement}
    190192\label{lst:mutex-stmt}
    191 \end{table}
     193\end{figure}
    192194
    193195% ======================================================================
     
    223225};
    224226\end{cfacode}
    225 Note that the destructor of a monitor must be a \code{mutex} routine to prevent deallocation while a thread is accessing the monitor. As with any object, calls to a monitor, using \code{mutex} or otherwise, is Undefined Behaviour after the destructor has run.
     227Note that the destructor of a monitor must be a \code{mutex} routine. This requirement ensures that the destructor has mutual-exclusion. As with any object, any call to a monitor, using \code{mutex} or otherwise, is Undefined Behaviour after the destructor has run.
    226228
    227229% ======================================================================
     
    230232% ======================================================================
    231233% ======================================================================
    232 In addition to mutual exclusion, the monitors at the core of \CFA's concurrency can also be used to achieve synchronization. With monitors, this capability is generally achieved with internal or external scheduling as in~\cite{Hoare74}. 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.
    233 
    234 First, here is a simple example of internal-scheduling :
     234In 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 \cite{Hoare74}. 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.
     235
     236First, here is a simple example of such a technique:
    235237
    236238\begin{cfacode}
     
    239241}
    240242
    241 void foo(A& mutex a1, A& mutex a2) {
     243void foo(A & mutex a) {
    242244        ...
    243245        //Wait for cooperation from bar()
    244         wait(a1.e);
     246        wait(a.e);
    245247        ...
    246248}
    247249
    248 void bar(A& mutex a1, A& mutex a2) {
     250void bar(A & mutex a) {
    249251        //Provide cooperation for foo()
    250252        ...
    251253        //Unblock foo
    252         signal(a1.e);
    253 }
    254 \end{cfacode}
    255 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, i.e., the signaller and signalled thread cannot be in the monitor simultaneously. The alternative is to return immediately after the call to \code{signal}, which is significantly more restrictive. Second, in \CFA, while it is common to store a \code{condition} as a field of the monitor, 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.
    256 
    257 An important aspect of the implementation is that \CFA does not allow barging, which means that once function \code{bar} releases the monitor, \code{foo} is guaranteed to resume immediately after (unless some other thread waited on the same condition). This guarantee offers the benefit of not having to loop around waits to recheck that a condition is 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.
     254        signal(a.e);
     255}
     256\end{cfacode}
     257
     258There 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. The alternative is to return immediately after the call to \code{signal}, which is significantly more restrictive. Second, in \CFA, while it is common to store a \code{condition} as a field of the monitor, 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.
     259
     260An important aspect of the implementation is that \CFA does not allow barging, which means that once function \code{bar} releases the monitor, \code{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.
    258261
    259262% ======================================================================
     
    262265% ======================================================================
    263266% ======================================================================
    264 It is easier to understand the problem of multi-monitor scheduling using a series of pseudo-code examples. Note that for simplicity in the following snippets of pseudo-code, waiting and signalling is done using an implicit condition variable, like Java built-in monitors. Indeed, \code{wait} statements always use the implicit condition variable as parameter and explicitly names the monitors (A and B) associated with the condition. Note that in \CFA, condition variables are tied to a \emph{group} of monitors on first use (called branding), which means that using internal scheduling with distinct sets of monitors requires one condition variable per set of monitors. The example below shows the simple case of having two threads (one for each column) and a single monitor A.
     267It is easier to understand the problem of multi-monitor scheduling using a series of pseudo-code. Note that for simplicity in the following snippets of pseudo-code, waiting and signalling is done using an implicit condition variable, like Java built-in monitors. Indeed, \code{wait} statements always use the implicit condition as paremeter and explicitly names the monitors (A and B) associated with the condition. Note that in \CFA, condition variables are tied to a set of monitors on first use (called branding) which means that using internal scheduling with distinct sets of monitors requires one condition variable per set of monitors.
    265268
    266269\begin{multicols}{2}
     
    281284\end{pseudo}
    282285\end{multicols}
    283 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.
     286The 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.
    284287
    285288A direct extension of the previous example is a \gls{bulk-acq} version:
     289
    286290\begin{multicols}{2}
    287291\begin{pseudo}
     
    290294release A & B
    291295\end{pseudo}
     296
    292297\columnbreak
     298
    293299\begin{pseudo}
    294300acquire A & B
     
    299305This version uses \gls{bulk-acq} (denoted using the {\sf\&} 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.
    300306
    301 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~\cite{Lister77}, which occurs when a \code{wait} is made by a thread that holds more than one monitor. For example, the following pseudo-code runs into the nested-monitor problem :
     307While 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 \cite{Lister77}, which occurs when a \code{wait} is made by a thread that holds more than one monitor. For example, the following pseudo-code runs into the nested-monitor problem :
    302308\begin{multicols}{2}
    303309\begin{pseudo}
     
    319325\end{pseudo}
    320326\end{multicols}
    321 The \code{wait} only releases monitor \code{B} so the signalling thread cannot acquire monitor \code{A} to get to the \code{signal}. Attempting release of all acquired monitors at the \code{wait} introduces a different set of problems, such as releasing monitor \code{C}, which has nothing to do with the \code{signal}.
    322 
    323 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~\cite{Lister77}.
     327
     328The \code{wait} only releases monitor \code{B} so the signalling thread cannot acquire monitor \code{A} to get to the \code{signal}. Attempting release of all acquired monitors at the \code{wait} results in another set of problems such as releasing monitor \code{C}, which has nothing to do with the \code{signal}.
     329
     330However, 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.
    324331
    325332\begin{multicols}{2}
     
    343350\end{multicols}
    344351
    345 This simple refactoring may not be possible, forcing more complex restructuring.
    346 
    347352% ======================================================================
    348353% ======================================================================
     
    351356% ======================================================================
    352357
    353 A larger example is presented to show complex issues for \gls{bulk-acq} and all the implementation options are analyzed. Listing \ref{lst:int-bulk-pseudo} shows an example where \gls{bulk-acq} adds a significant layer of complexity to the internal signalling semantics, and listing \ref{lst:int-bulk-cfa} shows the corresponding \CFA code to implement the pseudo-code in listing \ref{lst:int-bulk-pseudo}. For the purpose of translating the given pseudo-code into \CFA-code, any method of introducing a monitor is acceptable, e.g., \code{mutex} parameter, global variables, pointer parameters or using locals with the \code{mutex}-statement.
    354 
    355 \begin{figure}[!t]
     358A larger example is presented to show complex issuesfor \gls{bulk-acq} and all the implementation options are analyzed. Listing \ref{lst:int-bulk-pseudo} shows an example where \gls{bulk-acq} adds a significant layer of complexity to the internal signalling semantics, and listing \ref{lst:int-bulk-cfa} shows the corresponding \CFA code which implements the pseudo-code in listing \ref{lst:int-bulk-pseudo}. For the purpose of translating the given pseudo-code into \CFA-code any method of introducing monitor into context, other than a \code{mutex} parameter, is acceptable, e.g., global variables, pointer parameters or using locals with the \code{mutex}-statement.
     359
     360\begin{figure}[!b]
    356361\begin{multicols}{2}
    357362Waiting thread
     
    367372release A
    368373\end{pseudo}
     374
    369375\columnbreak
     376
    370377Signalling thread
    371 \begin{pseudo}[numbers=left, firstnumber=10,escapechar=|]
     378\begin{pseudo}[numbers=left, firstnumber=10]
    372379acquire A
    373380        //Code Section 5
    374381        acquire A & B
    375382                //Code Section 6
    376                 |\label{line:signal1}|signal A & B
     383                signal A & B
    377384                //Code Section 7
    378385        release A & B
    379386        //Code Section 8
    380 |\label{line:lastRelease}|release A
     387release A
    381388\end{pseudo}
    382389\end{multicols}
    383 \begin{cfacode}[caption={Internal scheduling with \gls{bulk-acq}},label={lst:int-bulk-pseudo}]
    384 \end{cfacode}
     390\caption{Internal scheduling with \gls{bulk-acq}}
     391\label{lst:int-bulk-pseudo}
     392\end{figure}
     393
     394\begin{figure}[!b]
    385395\begin{center}
    386396\begin{cfacode}[xleftmargin=.4\textwidth]
     
    403413}
    404414\end{cfacode}
     415
    405416\columnbreak
     417
    406418Signalling thread
    407419\begin{cfacode}
     
    417429\end{cfacode}
    418430\end{multicols}
    419 \begin{cfacode}[caption={Equivalent \CFA code for listing \ref{lst:int-bulk-pseudo}},label={lst:int-bulk-cfa}]
    420 \end{cfacode}
     431\caption{Equivalent \CFA code for listing \ref{lst:int-bulk-pseudo}}
     432\label{lst:int-bulk-cfa}
     433\end{figure}
     434
     435The complexity begins at 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 \code{A & B}'' (line 16), it must actually transfer ownership of monitor \code{B} to the waiting thread. This ownership trasnfer is required in order to prevent barging. Since the signalling thread still needs monitor \code{A}, simply waking up the waiting thread is not an option because it violates mutual exclusion. There are three options.
     436
     437\subsubsection{Delaying signals}
     438The 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 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.
    421439\begin{multicols}{2}
    422440Waiter
     
    432450
    433451Signaller
    434 \begin{pseudo}[numbers=left, firstnumber=6,escapechar=|]
     452\begin{pseudo}[numbers=left, firstnumber=6]
    435453acquire A
    436454        acquire A & B
    437455                signal A & B
    438456        release A & B
    439         |\label{line:secret}|//Secretly keep B here
     457        //Secretly keep B here
    440458release A
    441459//Wakeup waiter and transfer A & B
    442460\end{pseudo}
    443461\end{multicols}
    444 \begin{cfacode}[caption={Listing \ref{lst:int-bulk-pseudo}, with delayed signalling comments},label={lst:int-secret}]
    445 \end{cfacode}
    446 \end{figure}
    447 
    448 The complexity begins at 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 \code{A & B}'' (listing \ref{lst:int-bulk-pseudo} line \ref{line:signal1}), it must actually transfer ownership of monitor \code{B} to the waiting thread. This ownership transfer is required in order to prevent barging into \code{B} by another thread, since both the signalling and signalled threads still need monitor \code{A}. There are three options.
    449 
    450 \subsubsection{Delaying signals}
    451 The 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 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 multiple objects to a single group of objects, effectively making the existing single-monitor semantic viable by simply changing monitors to monitor groups. The naive approach to this solution is to only release monitors once every monitor in a group can be released. However, since some monitors are never released (i.e., the monitor of a thread), this interpretation means groups can grow but may never shrink. A more interesting interpretation is to only transfer groups as one but to recreate the groups on every operation, i.e., limit ownership transfer to one per \code{signal}/\code{release}.
    452 
    453 However, this solution can become much more complicated depending on what is executed while secretly holding B (listing \ref{lst:int-secret} line \ref{line:secret}).
    454 The goal in this solution is to avoid the need to transfer ownership of a subset of the condition monitors. However, listing \ref{lst:dependency} shows a slightly different example where a third thread is waiting on monitor \code{A}, using a different condition variable. Because the third thread is signalled when secretly holding \code{B}, the goal  becomes unreachable. Depending on the order of signals (listing \ref{lst:dependency} line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen :
    455 
    456 \paragraph{Case 1: thread $\alpha$ goes first.} In this case, the problem is that monitor \code{A} needs to be passed to thread $\beta$ when thread $\alpha$ is done with it.
    457 \paragraph{Case 2: thread $\beta$ goes first.} In this case, the problem is that monitor \code{B} needs to be retained and passed to thread $\alpha$ along with monitor \code{A}, which can be done directly or possibly using thread $\beta$ as an intermediate.
    458 \\
    459 
    460 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 \ref{line:signal-a} before line \ref{line:signal-ab} and get the reverse effect for listing \ref{lst:dependency}.
    461 
    462 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 homogeneous group and therefore effectively precludes this approach.
    463 
    464 \subsubsection{Dependency graphs}
    465 
    466 
     462However, 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:
    467463\begin{figure}
    468464\begin{multicols}{3}
     
    475471release A
    476472\end{pseudo}
     473
    477474\columnbreak
     475
    478476Thread $\gamma$
    479 \begin{pseudo}[numbers=left, firstnumber=6, escapechar=|]
     477\begin{pseudo}[numbers=left, firstnumber=1]
    480478acquire A
    481479        acquire A & B
    482                 |\label{line:signal-ab}|signal A & B
    483         |\label{line:release-ab}|release A & B
    484         |\label{line:signal-a}|signal A
    485 |\label{line:release-a}|release A
    486 \end{pseudo}
     480                signal A & B
     481        release A & B
     482        signal A
     483release A
     484\end{pseudo}
     485
    487486\columnbreak
     487
    488488Thread $\beta$
    489 \begin{pseudo}[numbers=left, firstnumber=12, escapechar=|]
     489\begin{pseudo}[numbers=left, firstnumber=1]
    490490acquire A
    491491        wait A
    492 |\label{line:release-aa}|release A
    493 \end{pseudo}
     492release A
     493\end{pseudo}
     494
    494495\end{multicols}
    495 \begin{cfacode}[caption={Pseudo-code for the three thread example.},label={lst:dependency}]
    496 \end{cfacode}
     496\caption{Dependency graph}
     497\label{lst:dependency}
     498\end{figure}
     499
     500The goal in this solution is to avoid the need to transfer ownership of a subset of the condition monitors. However, this goal is unreacheable in the previous example. Depending on the order of signals (line 12 and 15) two cases can happen.
     501
     502\paragraph{Case 1: thread 1 goes first.} In this case, the problem is that monitor A needs to be passed to thread 2 when thread 1 is done with it.
     503\paragraph{Case 2: thread 2 goes first.} In this case, the problem is that monitor B needs to be passed to thread 1, which can be done directly or using thread 2 as an intermediate.
     504\\
     505
     506Note 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.
     507
     508In 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 effectively precludes this approach.
     509
     510\subsubsection{Dependency graphs}
     511In the listing \ref{lst:int-bulk-pseudo} 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 \code{A & B} and then the waiter transfers back ownership of \code{A} when it releases it, then the problem is solved (\code{B} is no longer in use at this point). 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:
     512
     513\begin{multicols}{2}
     514\begin{pseudo}
     515acquire A
     516        acquire B
     517                acquire C
     518                        wait A & B & C
     519                release C
     520        release B
     521release A
     522\end{pseudo}
     523
     524\columnbreak
     525
     526\begin{pseudo}
     527acquire A
     528        acquire B
     529                acquire C
     530                        signal A & B & C
     531                release C
     532        release B
     533release A
     534\end{pseudo}
     535\end{multicols}
     536
     537\begin{figure}
    497538\begin{center}
    498539\input{dependency}
     
    502543\end{figure}
    503544
    504 In the listing \ref{lst:int-bulk-pseudo} pseudo-code, there is a solution that satisfies both barging prevention and mutual exclusion. If ownership of both monitors is transferred to the waiter when the signaller releases \code{A & B} and then the waiter transfers back ownership of \code{A} back to the signaller when it releases it, then the problem is solved (\code{B} is no longer in use at this point). Dynamically finding the correct order is therefore the second possible solution. The problem is effectively 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 close to polynomial. This complexity explosion can be seen in listing \ref{lst:explosion}, which is just a direct extension to three monitors, requires at least three ownership transfer and has multiple solutions. Furthermore, the presence of multiple solutions for ownership transfer can cause deadlock problems if a specific solution is not consistently picked; In the same way that multiple lock acquiring order can cause deadlocks.
     545Listing \ref{lst:dependency} is the three thread example rewritten for dependency graphs. Figure \ref{fig:dependency} shows the corresponding dependency graph that results, where every node is a statement of one of the three threads, and the arrows the dependency of that statement (e.g., $\alpha1$ must happen before $\alpha2$). The extra challenge is that this dependency graph is effectively post-mortem, but the runtime 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.
     546
     547\subsubsection{Partial signalling} \label{partial-sig}
     548Finally, the solution that is chosen for \CFA is to use partial signalling. Again using listing \ref{lst:int-bulk-pseudo}, 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. Furthermore, after being fully implemented, this solution does not appear to have any downsides worth mentionning.
     549
     550% ======================================================================
     551% ======================================================================
     552\subsection{Signalling: Now or Later}
     553% ======================================================================
     554% ======================================================================
    505555\begin{figure}
    506 \begin{multicols}{2}
    507 \begin{pseudo}
    508 acquire A
    509         acquire B
    510                 acquire C
    511                         wait A & B & C
    512                 release C
    513         release B
    514 release A
    515 \end{pseudo}
    516 
    517 \columnbreak
    518 
    519 \begin{pseudo}
    520 acquire A
    521         acquire B
    522                 acquire C
    523                         signal A & B & C
    524                 release C
    525         release B
    526 release A
    527 \end{pseudo}
    528 \end{multicols}
    529 \begin{cfacode}[caption={Extension to three monitors of listing \ref{lst:int-bulk-pseudo}},label={lst:explosion}]
    530 \end{cfacode}
    531 \end{figure}
    532 
    533 Listing \ref{lst:dependency} is the three threads example used in the delayed signals solution. Figure \ref{fig:dependency} shows the corresponding dependency graph that results, where every node is a statement of one of the three threads, and the arrows the dependency of that statement (e.g., $\alpha1$ must happen before $\alpha2$). The extra challenge is that this dependency graph is effectively post-mortem, but the runtime system needs to be able to build and solve these graphs as the dependency unfolds. Resolving dependency graphs being a complex and expensive endeavour, this solution is not the preferred one.
    534 
    535 \subsubsection{Partial signalling} \label{partial-sig}
    536 Finally, the solution that is chosen for \CFA is to use partial signalling. Again using listing \ref{lst:int-bulk-pseudo}, the partial signalling solution transfers ownership of monitor \code{B} at lines \ref{line:signal1} to the waiter but does not wake the waiting thread since it is still using monitor \code{A}. Only when it reaches line \ref{line:lastRelease} 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 released 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. Furthermore, after being fully implemented, this solution does not appear to have any significant downsides.
    537 
    538 While listing \ref{lst:dependency} is a complicated problem for previous solutions, it can be solved easily with partial signalling :
    539 \begin{itemize}
    540         \item When thread $\gamma$ reaches line \ref{line:release-ab} it transfers monitor \code{B} to thread $\alpha$ and continues to hold monitor \code{A}.
    541         \item When thread $\gamma$ reaches line \ref{line:release-a}  it transfers monitor \code{A} to thread $\beta$  and wakes it up.
    542         \item When thread $\beta$  reaches line \ref{line:release-aa} it transfers monitor \code{A} to thread $\alpha$ and wakes it up.
    543         \item Problem solved!
    544 \end{itemize}
    545 
    546 % ======================================================================
    547 % ======================================================================
    548 \subsection{Signalling: Now or Later}
    549 % ======================================================================
    550 % ======================================================================
    551 \begin{table}
    552556\begin{tabular}{|c|c|}
    553557\code{signal} & \code{signal_block} \\
     
    650654\end{tabular}
    651655\caption{Dating service example using \code{signal} and \code{signal_block}. }
    652 \label{tbl:datingservice}
    653 \end{table}
    654 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.
    655 
    656 The example in table \ref{tbl:datingservice} highlights the difference in behaviour. As mentioned, \code{signal} only transfers ownership once the current critical section exits, this behaviour requires additional synchronization when a two-way handshake is needed. To avoid this explicit synchronization, the \code{condition} type offers the \code{signal_block} routine, which handles the two-way handshake as shown in the example. This feature 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 either before or after the call.
     656\label{lst:datingservice}
     657\end{figure}
     658An 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}.
     659
     660The 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 requires 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 handles the two-way handshake 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.
    657661
    658662% ======================================================================
     
    723727\end{tabular}
    724728\end{center}
    725 This method is more constrained and explicit, which helps users reduce the non-deterministic 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 occurring. External scheduling can generally be done either in terms of control flow (e.g., Ada with \code{accept}, \uC with \code{_Accept}) or in terms of data (e.g., Go with channels). Of course, both of these paradigms have their own strengths 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 multiple-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.
     729This 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.
    726730
    727731For the \code{P} member above using internal scheduling, the call to \code{wait} only guarantees that \code{V} is the last routine to access the monitor, allowing a third routine, say \code{isInUse()}, acquire mutual exclusion several times while routine \code{P} is waiting. On the other hand, external scheduling guarantees that while routine \code{P} is waiting, no routine other than \code{V} can acquire the monitor.
     
    732736% ======================================================================
    733737% ======================================================================
    734 In \uC, a monitor class declaration includee an exhaustive list of monitor operations. Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user:
     738In \uC, monitor declarations include an exhaustive list of monitor operations. Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user:
    735739
    736740\begin{cfacode}
     
    748752\end{cfacode}
    749753
    750 Furthermore, external scheduling is an example where implementation constraints become visible from the interface. Here is the pseudo code for the entering phase of a monitor:
     754Furthermore, external scheduling is an example where implementation constraints become visible from the interface. Indeed, since there is no hard limit to the number of threads trying to acquire a monitor concurrently, performance is a significant concern. Here is the pseudo code for the entering phase of a monitor:
     755
    751756\begin{center}
    752757\begin{tabular}{l}
     
    763768\end{tabular}
    764769\end{center}
     770
    765771For 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:
    766772
     
    772778\end{figure}
    773779
    774 There are other alternatives to these pictures, but in the case of this picture, implementing a fast accept check is relatively easy. Restricted to a fixed number of mutex members, N, the accept check reduces to updating a bitmask when the acceptor queue changes, a check that executes in a single instruction even with a fairly large number (e.g., 128) of mutex members. This approach requires a dense unique ordering of routines with an upper-bound and that ordering must be consistent across translation units. For OO languages these constraints are common, since objects only offer adding member routines consistently across translation units via inheritence. However, in \CFA users can extend objects with mutex routines that are only visible in certain translation unit. This means that establishing a program-wide dense-ordering among mutex routines can only be done in the program linking phase, and still could have issues when using dynamically shared objects.
    775 
    776 The alternative is to alter the implementation like this:
     780There are other alternatives to these pictures, but in the case of this picture, implementing a fast accept check is relatively easy. Restricted to a fixed number of mutex members, N, the accept check reduces to updating a bitmask when the acceptor queue changes, 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 enumerates (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. It is 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.
     781The alternative is to alter the implementeation like this:
    777782
    778783\begin{center}
     
    780785\end{center}
    781786
    782 Here, the mutex routine called is associated with a thread on the entry queue while a list of acceptable routines is kept seperately. Generating a mask dynamically 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 accepted function-pointers replaces the single instruction bitmask compare with dereferencing a pointer followed by a linear search. Furthermore, supporting nested external scheduling (e.g., listing \ref{lst:nest-ext}) may now require additional searches for the \code{waitfor} statement to check if a routine is already queued.
     787Generating a mask dynamically 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 accepted function-pointers replaces the single instruction bitmask compare with dereferencing a pointer followed by a linear search. Furthermore, supporting nested external scheduling (e.g., listing \ref{lst:nest-ext}) may now require additionnal searches on calls to \code{waitfor} statement to check if a routine is already queued in.
    783788
    784789\begin{figure}
    785 \begin{cfacode}[caption={Example of nested external scheduling},label={lst:nest-ext}]
     790\begin{cfacode}
    786791monitor M {};
    787792void foo( M & mutex a ) {}
     
    795800
    796801\end{cfacode}
    797 \end{figure}
    798 
    799 Note that in the second picture, tasks need to always keep track of the monitors associated with mutex routines, and the routine mask needs to have both a function pointer and a set of monitors, as is be discussed in the next section. These details are omitted from the picture for the sake of simplicity.
    800 
    801 At this point, a decision must be made 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  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.
     802\caption{Example of nested external scheduling}
     803\label{lst:nest-ext}
     804\end{figure}
     805
     806Note that in the second picture, tasks need to always keep track of 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.
     807
     808At this point, a decision must be made 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.
    802809
    803810% ======================================================================
     
    814821
    815822void g(M & mutex b, M & mutex c) {
    816         waitfor(f); //two monitors M => unknown which to pass to f(M & mutex)
    817 }
    818 \end{cfacode}
     823        waitfor(f); //two monitors M => unkown which to pass to f(M & mutex)
     824}
     825\end{cfacode}
     826
    819827The obvious solution is to specify the correct monitor as follows:
    820828
     
    825833
    826834void g(M & mutex a, M & mutex b) {
    827         //wait for call to f with argument b
    828         waitfor(f, b);
    829 }
    830 \end{cfacode}
    831 This syntax is unambiguous. Both locks are acquired and kept by \code{g}. 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 behaviour can be extended to the multi-monitor \code{waitfor} statement as follows.
     835        waitfor( f, b );
     836}
     837\end{cfacode}
     838
     839This syntax is unambiguous. Both locks are acquired and kept by \code{g}. 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 \code{waitfor} statement as follows.
    832840
    833841\begin{cfacode}
     
    837845
    838846void g(M & mutex a, M & mutex b) {
    839         //wait for call to f with argument a and b
    840         waitfor(f, a, b);
     847        waitfor( f, a, b);
    841848}
    842849\end{cfacode}
     
    844851Note 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.
    845852
    846 An important behaviour to note is when a set of monitors only match partially :
     853An important behavior to note is when a set of monitors only match partially :
    847854
    848855\begin{cfacode}
     
    863870
    864871void bar() {
    865         f(a2, b); //fulfill cooperation
    866 }
    867 \end{cfacode}
    868 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 the order of parameters is irrelevant; \code{waitfor(f,a,b)} and \code{waitfor(f,b,a)} are indistinguishable waiting condition.
     872        f(a2, b); //fufill cooperation
     873}
     874\end{cfacode}
     875
     876While 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 irrelevant; \code{waitfor(f,a,b)} and \code{waitfor(f,b,a)} are indistinguishable waiting condition.
    869877
    870878% ======================================================================
     
    874882% ======================================================================
    875883
    876 Syntactically, the \code{waitfor} statement takes a function identifier and a set of monitors. While the set of monitors can be any list of expression, the function name is more restricted because the compiler validates at compile time the validity of the function type and the parameters used with the \code{waitfor} statement. It checks that the set of monitors passed in matches the requirements for a function call. Listing \ref{lst:waitfor} shows various usage of the waitfor statement and which are acceptable. The choice of the function type is made ignoring any non-\code{mutex} parameter. One limitation of the current implementation is that it does not handle overloading but overloading is possible.
     884Syntactically, the \code{waitfor} statement takes a function identifier and a set of monitors. While the set of monitors can be any list of expression, the function name is more restricted because the compiler validates at compile time the validity of the function type and the parameters used with the \code{waitfor} statement. It checks that the set of monitor passed in matches the requirements for a function call. Listing \ref{lst:waitfor} shows various usage of the waitfor statement and which are acceptable. The choice of the function type is made ignoring any non-\code{mutex} parameter. One limitation of the current implementation is that it does not handle overloading.
    877885\begin{figure}
    878 \begin{cfacode}[caption={Various correct and incorrect uses of the waitfor statement},label={lst:waitfor}]
     886\begin{cfacode}
    879887monitor A{};
    880888monitor B{};
     
    903911        waitfor(f4, a1);     //Incorrect : f4 ambiguous
    904912
    905         waitfor(f2, a1, b2); //Undefined Behaviour : b2 not mutex
    906 }
    907 \end{cfacode}
    908 \end{figure}
    909 
    910 Finally, for added flexibility, \CFA supports constructing a complex \code{waitfor} statement using the \code{or}, \code{timeout} and \code{else}. Indeed, multiple \code{waitfor} clauses can be chained together using \code{or}; this chain forms a single statement that uses baton-pass to any one function that fits one of the function+monitor set passed in. To enable users to tell which accepted function executed, \code{waitfor}s are followed by a statement (including the null statement \code{;}) or a compound statement, which is executed after the clause is triggered. A \code{waitfor} chain can also be followed by a \code{timeout}, to signify an upper bound on the wait, or an \code{else}, to signify that the call should be non-blocking, which checks for a matching function call already arrived and otherwise continues. Any and all of these clauses can be preceded by a \code{when} condition to dynamically toggle the accept clauses on or off based on some current state. Listing \ref{lst:waitfor2}, demonstrates several complex masks and some incorrect ones.
     913        waitfor(f2, a1, b2); //Undefined Behaviour : b2 may not acquired
     914}
     915\end{cfacode}
     916\caption{Various correct and incorrect uses of the waitfor statement}
     917\label{lst:waitfor}
     918\end{figure}
     919
     920Finally, for added flexibility, \CFA supports constructing complex \code{waitfor} mask using the \code{or}, \code{timeout} and \code{else}. Indeed, multiple \code{waitfor} can be chained together using \code{or}; this chain forms a single statement that uses baton-pass to any one function that fits one of the function+monitor set passed in. To eanble users to tell which accepted function is accepted, \code{waitfor}s are followed by a statement (including the null statement \code{;}) or a compound statement. When multiple \code{waitfor} are chained together, only the statement corresponding to the accepted function is executed. A \code{waitfor} chain can also be followed by a \code{timeout}, to signify an upper bound on the wait, or an \code{else}, to signify that the call should be non-blocking, that is only check of a matching function call already arrived and return immediately otherwise. Any and all of these clauses can be preceded by a \code{when} condition to dynamically construct the mask based on some current state. Listing \ref{lst:waitfor2}, demonstrates several complex masks and some incorrect ones.
    911921
    912922\begin{figure}
    913 \begin{cfacode}[caption={Various correct and incorrect uses of the or, else, and timeout clause around a waitfor statement},label={lst:waitfor2}]
     923\begin{cfacode}
    914924monitor A{};
    915925
     
    969979}
    970980\end{cfacode}
     981\caption{Various correct and incorrect uses of the or, else, and timeout clause around a waitfor statement}
     982\label{lst:waitfor2}
    971983\end{figure}
    972984
     
    978990An interesting use for the \code{waitfor} statement is destructor semantics. Indeed, the \code{waitfor} statement can accept any \code{mutex} routine, which includes the destructor (see section \ref{data}). However, with the semantics discussed until now, waiting for the destructor does not make any sense since using an object after its destructor is called is undefined behaviour. The simplest approach is to disallow \code{waitfor} on a destructor. However, a more expressive approach is to flip execution ordering when waiting for the destructor, meaning that waiting for the destructor allows the destructor to run after the current \code{mutex} routine, similarly to how a condition is signalled.
    979991\begin{figure}
    980 \begin{cfacode}[caption={Example of an executor which executes action in series until the destructor is called.},label={lst:dtor-order}]
     992\begin{cfacode}
    981993monitor Executer {};
    982994struct  Action;
     
    9931005}
    9941006\end{cfacode}
     1007\caption{Example of an executor which executes action in series until the destructor is called.}
     1008\label{lst:dtor-order}
    9951009\end{figure}
    9961010For example, listing \ref{lst:dtor-order} shows an example of an executor with an infinite loop, which waits for the destructor to break out of this loop. Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction.
  • doc/proposals/concurrency/text/future.tex

    r9c35431 rc6e2c18  
    1 
    2 \chapter{Conclusion}
    3 As mentionned in the introduction, this thesis provides a minimal concurrency \acrshort{api} that is simple, efficient and usable as the basis for higher-level features. The approach presented is based on a lighweight thread system for parallelism which sits on top of clusters of processors. This M:N model is jugded to be both more efficient and allow more flexibility for users. Furthermore, this document introduces monitors as the main concurrency tool for users. This thesis also offers a novel approach which allows using multiple monitors at once without running into the Nested Monitor Problem~\cite{Lister77}. It also offers a full implmentation of the concurrency runtime wirtten enterily in \CFA, effectively the largest \CFA code base to date.
    4 
    5 
    61% ======================================================================
    72% ======================================================================
    8 \section{Future Work}
     3\chapter{Future Work}
    94% ======================================================================
    105% ======================================================================
    116
    12 \subsection{Performance} \label{futur:perf}
    13 This thesis presents a first implementation of the \CFA runtime. Therefore, there is still significant work to do to improve performance. Many of the data structures and algorithms will change in the future to more efficient versions. For example, \CFA the number of monitors in a single \gls{bulk-acq} is only bound by the stack size, this is probably unnecessarily generous. It may be possible that limiting the number help increase performance. However, it is not obvious that the benefit would be significant.
     7\section{Flexible Scheduling} \label{futur:sched}
     8An important part of concurrency is scheduling. Different scheduling algorithm can affact peformance (both in terms of average and variation). However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs. One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted the to requirements of the workload. However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbirary scheduling algorithms to the scheduler. For example, a web server could attach Type-of-Service information to threads and have a ``ToS aware'' scheduling algorithm tailored to this specific web server. This path of flexible schedulers will be explored for \CFA.
    149
    15 \subsection{Flexible Scheduling} \label{futur:sched}
    16 An important part of concurrency is scheduling. Different scheduling algorithm can affect performance (both in terms of average and variation). However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs. One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted to the requirements of the workload. However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms to the scheduler. For example, a web server could attach Type-of-Service information to threads and have a ``ToS aware'' scheduling algorithm tailored to this specific web server. This path of flexible schedulers will be explored for \CFA.
     10\section{Non-Blocking IO} \label{futur:nbio}
     11While most of the parallelism tools
     12However, many modern workloads are not bound on computation but on IO operations, an common case being webservers and XaaS (anything as a service). These type of workloads often require significant engineering around amortising costs of blocking IO operations. While improving throughtput of these operations is outside what \CFA can do as a language, it can help users to make better use of the CPU time otherwise spent waiting on IO operations. The current trend is to use asynchronous programming using tools like callbacks and/or futurs and promises\cite. However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear
    1713
    18 \subsection{Non-Blocking IO} \label{futur:nbio}
    19 While most of the parallelism tools are aimed at data parallelism and control-flow parallelism, many modern workloads are not bound on computation but on IO operations, a common case being web-servers and XaaS (anything as a service). These type of workloads often require significant engineering around amortizing costs of blocking IO operations. At its core, Non-Blocking IO is a operating system level feature that allows queuing IO operations (e.g., network operations) and registering for notifications instead of waiting for requests to complete. In this context, the role of the language make Non-Blocking IO easily available and with low overhead. The current trend is to use asynchronous programming using tools like callbacks and/or futures and promises, which can be seen in frameworks like Node.js~\cite{NodeJs} for JavaScript, Spring MVC~\cite{SpringMVC} for Java and Django~\cite{Django} for Python. However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear.
     14\section{Other concurrency tools} \label{futur:tools}
     15While monitors offer a flexible and powerful concurent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package. Example of such tools can include simple locks and condition variables, futures and promises\cite{promises}, and executors. These additional features are useful when monitors offer a level of abstraction which is indaquate for certain tasks.
    2016
    21 \subsection{Other concurrency tools} \label{futur:tools}
    22 While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package. Example of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, executors and actors. These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks.
     17\section{Implicit threading} \label{futur:implcit}
     18Simpler applications can benefit greatly from having implicit parallelism. That is, parallelism that does not rely on the user to write concurrency. This type of parallelism can be achieved both at the language level and at the library level. The cannonical example of implcit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithm\cite{uC++book}. Listing \ref{lst:parfor} shows three different code examples that accomplish pointwise sums of large arrays. Note that none of these example explicitly declare any concurrency or parallelism objects.
    2319
    24 \subsection{Implicit threading} \label{futur:implcit}
    25 Simpler applications can benefit greatly from having implicit parallelism. That is, parallelism that does not rely on the user to write concurrency. This type of parallelism can be achieved both at the language level and at the library level. The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithm~\cite{uC++book}. Table \ref{lst:parfor} shows three different code examples that accomplish point-wise sums of large arrays. Note that none of these examples explicitly declare any concurrency or parallelism objects.
    26 
    27 \begin{table}
     20\begin{figure}
    2821\begin{center}
    2922\begin{tabular}[t]{|c|c|c|}
     
    10699\caption{For loop to sum numbers: Sequential, using library parallelism and language parallelism.}
    107100\label{lst:parfor}
    108 \end{table}
     101\end{figure}
    109102
    110 Implicit parallelism is a restrictive solution and therefore has its limitations. However, it is a quick and simple approach to parallelism, which may very well be sufficient for smaller applications and reduces the amount of boiler-plate needed to start benefiting from parallelism in modern CPUs.
     103Implicit parallelism is a general solution and therefore has its limitations. However, it is a quick and simple approach to parallelism which may very well be sufficient for smaller applications and reduces the amount of boiler-plate that is needed to start benefiting from parallelism in modern CPUs.
    111104
    112105
  • doc/proposals/concurrency/text/internals.tex

    r9c35431 rc6e2c18  
    11
    22\chapter{Behind the scene}
    3 There are several challenges specific to \CFA when implementing concurrency. These challenges are a direct result of \gls{bulk-acq} and loose object-definitions. These two constraints are the root cause of most design decisions in the implementation. Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs. This approach avoids 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.
    4 
    5 The main memory concern for concurrency is queues. All blocking operations are made by parking threads onto queues and all queues are designed with intrusive nodes, where each not has pre-allocated link fields for chaining, to avoid the need for memory allocation. Since several concurrency operations can use an unbound amount of memory (depending on \gls{bulk-acq}), statically defining information in the intrusive fields of threads is insufficient.The only way to use a variable amount of memory without requiring memory allocation is to pre-allocate large buffers of memory eagerly and store the information in these buffers. Conveniently, the callstack fits that description and is easy to use, which is why it is used heavily in the implementation of internal scheduling, particularly variable-length arrays. 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 array. The threads and the condition both have a fixed amount of memory, while mutex-routines and the actual blocking call allow for an unbound amount, within the stack size.
    6 
    7 Note that since the major contributions of this thesis are extending monitor semantics to \gls{bulk-acq} and loose object definitions, any challenges that are not resulting of these characteristics of \CFA are considered as solved problems and therefore not discussed.
     3There are several challenges specific to \CFA when implementing concurrency. These challenges are a direct result of \gls{bulk-acq} and loose object-definitions. These two constraints are the root cause of most design decisions in the implementation. Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs. 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.
     4
     5The main memory concern for concurrency is queues. All blocking operations are made by parking threads onto queues. The queue design needs to be intrusive\cite{IntrusiveData} to avoid the need for memory allocation, which entails that all the nodes need specific fields to keep track of all needed information. Since many concurrency operations can use an unbound amount of memory (depending on \gls{bulk-acq}), statically defining 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 variable length arrays, which are used extensively.
     6
     7Since 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. 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 the later is preferable in terms of performance).
     8
     9Note that since the major contributions of this thesis are extending monitor semantics to \gls{bulk-acq} and loose object definitions, any challenges that are not resulting of these characteristiques of \CFA are considered as solved problems and therefore not discussed further.
    810
    911% ======================================================================
     
    1315% ======================================================================
    1416
    15 The first step towards the monitor implementation is simple mutex-routines. In the single monitor case, mutual-exclusion is done using the entry/exit procedure in listing \ref{lst:entry1}. The entry/exit procedures do not have to be extended to support multiple monitors. Indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlock~\cite{Havender68}. In \CFA, ordering of monitor acquisition relies on memory ordering. This approach is sufficient because all objects are guaranteed to have distinct non-overlapping memory layouts and mutual-exclusion for a monitor is only defined for its lifetime, meaning that destroying a monitor while it is acquired is Undefined Behavior. When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer-array and sorted based on pointer values. This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively.
     17The first step towards the monitor implementation is simple mutex-routines using monitors. In the single monitor case, this is done using the entry/exit procedure highlighted in listing \ref{lst:entry1}. This entry/exit procedure does not actually have to be extended to support multiple monitors, indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlocks\cite{Havender68}. In \CFA, ordering of monitor relies on memory ordering, this is sufficient because all objects are guaranteed to have distinct non-overlaping memory layouts and mutual-exclusion for a monitor is only defined for its lifetime, meaning that destroying a monitor while it is acquired is undefined behavior. When a mutex call is made, the concerned monitors are agregated into a variable-length pointer array and sorted based on pointer values. This array presists for the entire duration of the mutual-exclusion and its ordering reused extensively.
    1618\begin{figure}
    1719\begin{multicols}{2}
     
    3537\end{pseudo}
    3638\end{multicols}
    37 \begin{pseudo}[caption={Initial entry and exit routine for monitors},label={lst:entry1}]
    38 \end{pseudo}
     39\caption{Initial entry and exit routine for monitors}
     40\label{lst:entry1}
    3941\end{figure}
    4042
     
    4244Depending on the choice of semantics for when monitor locks are acquired, interaction between monitors and \CFA's concept of polymorphism can be more complex to support. However, it is shown that entry-point locking solves most of the issues.
    4345
    44 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. It is important to present the difference between the two acquiring options : \glspl{callsite-locking} 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:
    45 \begin{table}[H]
     46First 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. 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:
     47\begin{figure}[H]
    4648\begin{center}
    4749\begin{tabular}{|c|c|c|}
     
    9597\end{center}
    9698\caption{Call-site vs entry-point locking for mutex calls}
    97 \label{tbl:locking-site}
    98 \end{table}
    99 
    100 Note the \code{mutex} keyword relies on the type system, which means that in cases where a generic monitor-routine is desired, writing the mutex routine is possible with the proper trait, e.g.:
     99\label{fig:locking-site}
     100\end{figure}
     101
     102Note the \code{mutex} keyword relies on the type system, which means that in cases where a generic monitor routine is desired, writing the mutex routine is possible with the proper trait, for example:
    101103\begin{cfacode}
    102104//Incorrect: T may not be monitor
     
    109111\end{cfacode}
    110112
    111 Both entry-point and \gls{callsite-locking} are feasible implementations. The current \CFA implementations uses entry-point locking because it requires less work when using \gls{raii}, effectively transferring the burden of implementation to object construction/destruction. It is harder to use \gls{raii} for call-site locking, as it does not necessarily have an existing scope that matches exactly the scope of the mutual exclusion, i.e.: the function body. For example, the monitor call can appear in the middle of an expression. Furthermore, entry-point locking requires less code generation since any useful routine multiple times, but there is only one entry-point for many call-sites.
     113Both entry-point and callsite locking are feasible implementations. The current \CFA implementations uses entry-point locking because it requires less work when using \gls{raii}, effectively transferring the burden of implementation to object construction/destruction. The same could be said of callsite locking, the difference being that the later does not necessarily have an existing scope that matches exactly the scope of the mutual exclusion, i.e.: the function body. Furthermore, entry-point locking requires less code generation since any useful routine is called at least as often as it is define, there can be only one entry-point but many callsites.
    112114
    113115% ======================================================================
     
    117119% ======================================================================
    118120
    119 Figure \ref{fig:system1} shows a high-level picture if the \CFA runtime system in regards to concurrency. Each component of the picture is explained in details in the flowing sections.
     121Figure \ref{fig:system1} shows a high-level picture if the \CFA runtime system in regards to concurrency. Each component of the picture is explained in details in the fllowing sections.
    120122
    121123\begin{figure}
     
    128130
    129131\subsection{Context Switching}
    130 As mentioned in section \ref{coroutine}, coroutines are a stepping stone for implementing threading, because they share the same mechanism for context-switching between different stacks. To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific function call. This assumption means that the context-switch only has to copy the callee-saved registers onto the stack and then switch the stack registers with the ones of the target coroutine/thread. Note that the instruction pointer can be left untouched since the context-switch is always inside the same function. Threads however do not context-switch between each other directly. They context-switch to the scheduler. This method is called a 2-step context-switch and has the advantage of having a clear distinction between user code and the kernel where scheduling and other system operation happen. Obviously, this doubles the context-switch cost because threads must context-switch to an intermediate stack. The alternative 1-step context-switch uses the stack of the ``from'' thread to schedule and then context-switches directly to the ``to'' thread. However, the performance of the 2-step context-switch is still superior to a \code{pthread_yield} (see section \ref{results}). Additionally, for users in need for optimal performance, it is important to note that having a 2-step context-switch as the default does not prevent \CFA from offering a 1-step context-switch (akin to the Microsoft \code{SwitchToFiber}~\cite{switchToWindows} routine). This option is not currently present in \CFA but the changes required to add it are strictly additive.
     132As mentionned in section \ref{coroutine}, coroutines are a stepping stone for implementing threading. This is because they share the same mechanism for context-switching between different stacks. To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific function call. This assumption means that the context-switch only has to copy the callee-saved registers onto the stack and then switch the stack registers with the ones of the target coroutine/thread. Note that the instruction pointer can be left untouched since the context-switch is always inside the same function. Threads however do not context-switch between each other directly. They context-switch to the scheduler. This method is called a 2-step context-switch and has the advantage of having a clear distinction between user code and the kernel where scheduling and other system operation happen. Obiously, this has the cost of doubling the context-switch cost because threads must context-switch to an intermediate stack. However, the performance of the 2-step context-switch is still superior to a \code{pthread_yield}(see section \ref{results}). additionally, for users in need for optimal performance, it is important to note that having a 2-step context-switch as the default does not prevent \CFA from offering a 1-step context-switch to use manually (or as part of monitors). This option is not currently present in \CFA but the changes required to add it are strictly additive.
    131133
    132134\subsection{Processors}
    133 Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically pthreads in the current implementation of \CFA. Indeed, any parallelism must go through operating-system libraries. However, \glspl{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism. Indeed, processor \glspl{kthread} simply fetch a \gls{uthread} from the scheduler and run it; they are effectively executers for user-threads. The main benefit of this approach is that it offers a well defined boundary between kernel code and user code, for example, kernel thread quiescing, scheduling and interrupt handling. Processors internally use coroutines to take advantage of the existing context-switching semantics.
     135Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically pthreads in the current implementation of \CFA. Indeed, any parallelism must go through operating-system librairies. However, \glspl{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism. Indeed, processor \glspl{kthread} simply fetch a \glspl{uthread} from the scheduler and run, they are effectively executers for user-threads. The main benefit of this approach is that it offers a well defined boundary between kernel code and user code, for example, kernel thread quiescing, scheduling and interrupt handling. Processors internally use coroutines to take advantage of the existing context-switching semantics.
    134136
    135137\subsection{Stack management}
    136 One of the challenges of this system is to reduce the footprint as much as possible. Specifically, all pthreads created also have a stack created with them, which should be used as much as possible. Normally, coroutines also create there own stack to run on, however, in the case of the coroutines used for processors, these coroutines run directly on the \gls{kthread} stack, effectively stealing the processor stack. The exception to this rule is the Main Processor, i.e. the initial \gls{kthread} that is given to any program. In order to respect C user-expectations, the stack of the initial kernel thread, the main stack of the program, is used by the main user thread rather than the main processor, which can grow very large
     138One of the challenges of this system is to reduce the footprint as much as possible. Specifically, all pthreads created also have a stack created with them, which should be used as much as possible. Normally, coroutines also create there own stack to run on, however, in the case of the coroutines used for processors, these coroutines run directly on the kernel thread stack, effectively stealing the processor stack. The exception to this rule is the Main Processor, i.e. the initial kernel thread that is given to any program. In order to respect user expectations, the stack of the initial kernel thread, the main stack of the program, is used by the main user thread rather than the main processor.
    137139
    138140\subsection{Preemption} \label{preemption}
    139 Finally, an important aspect for any complete threading system is preemption. As mentioned in chapter \ref{basics}, preemption introduces an extra degree of uncertainty, which enables users to have multiple threads interleave transparently, rather than having to cooperate among threads for proper scheduling and CPU distribution. Indeed, preemption is desirable because it adds a degree of isolation among threads. In a fully cooperative system, any thread that runs a long loop can starve other threads, while in a preemptive system, starvation can still occur but it does not rely on every thread having to yield or block on a regular basis, which reduces significantly a programmer burden. Obviously, preemption is not optimal for every workload, however any preemptive system can become a cooperative system by making the time-slices extremely large. Therefore, \CFA uses a preemptive threading system.
    140 
    141 Preemption in \CFA is based on kernel timers, which are used to run a discrete-event simulation. Every processor keeps track of the current time and registers an expiration time with the preemption system. When the preemption system receives a change in preemption, it inserts the time in a sorted order and sets a kernel timer for the closest one, effectively stepping through preemption events on each signal sent by the timer. These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread. This results in an implementation problem, because when delivering signals to a process, the kernel can deliver the signal to any kernel thread for which the signal is not blocked, i.e. :
     141Finally, an important aspect for any complete threading system is preemption. As mentionned in chapter \ref{basics}, preemption introduces an extra degree of uncertainty, which enables users to have multiple threads interleave transparently, rather than having to cooperate among threads for proper scheduling and CPU distribution. Indeed, preemption is desireable because it adds a degree of isolation among threads. In a fully cooperative system, any thread that runs into a long loop can starve other threads, while in a preemptive system starvation can still occur but it does not rely on every thread having to yield or block on a regular basis, which reduces significantly a programmer burden. Obviously, preemption is not optimal for every workload, however any preemptive system can become a cooperative system by making the time-slices extremely large. Which is why \CFA uses a preemptive threading system.
     142
     143Preemption in \CFA is based on kernel timers, which are used to run a discrete-event simulation. Every processor keeps track of the current time and registers an expiration time with the preemption system. When the preemption system receives a change in preemption, it sorts these expiration times in a list and sets a kernel timer for the closest one, effectively stepping between preemption events on each signals sent by the timer. These timers use the linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread. This results in an implementation problem,because when delivering signals to a process, the kernel documentation states that the signal can be delivered to any kernel thread for which the signal is not blocked i.e. :
    142144\begin{quote}
    143145A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked. If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.
    144146SIGNAL(7) - Linux Programmer's Manual
    145147\end{quote}
    146 For the sake of simplicity and in order to prevent the case of having two threads receiving alarms simultaneously, \CFA programs block the {\tt SIGALRM} signal on every kernel thread except one. Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread.
    147 
    148 Involuntary context-switching is done by sending signal {\tt SIGUSER1} to the corresponding proces\-sor and having the thread yield from inside the signal handler. This approach effectively context-switches away from the signal-handler back to the kernel and the signal-handler frame is eventually unwound when the thread is scheduled again. As a result, a signal-handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread). It is important to note that signal-handlers save and restore signal masks because user-thread migration can cause a signal mask to migrate from one kernel thread to another. This behaviour is only a problem if all kernel threads, among which a user thread can migrate, differ in terms of signal masks\footnote{Sadly, official POSIX documentation is silent on what distinguishes ``async-signal-safe'' functions from other functions.}. However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel-alarm thread can cause deadlocks. For this reason, the alarm thread is in a tight loop around a system call to \code{sigwaitinfo}, requiring very little CPU time for preemption. One final detail about the alarm thread is how to wake it when additional communication is required (e.g., on thread termination). This unblocking is also done using {\tt SIGALRM}, but sent through the \code{pthread_sigqueue}. Indeed, \code{sigwait} can differentiate signals sent from \code{pthread_sigqueue} from signals sent from alarms or the kernel.
     148For the sake of simplicity and in order to prevent the case of having two threads receiving alarms simultaneously, \CFA programs block the {\tt SIGALRM} signal on every thread except one. Now because of how involontary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread.
     149
     150Involuntary context-switching is done by sending signal {\tt SIGUSER1} to the corresponding processor and having the thread yield from inside the signal handler. Effectively context-switching away from the signal-handler back to the kernel and the signal-handler frame is eventually unwound when the thread is scheduled again. This approach means that a signal-handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread). It is important to note that signal-handlers save and restore signal masks because user-thread migration can cause signal mask to migrate from one kernel thread to another. This behaviour is only a problem if all kernel threads among which a user thread can migrate differ in terms of signal masks\footnote{Sadly, official POSIX documentation is silent on what distiguishes ``async-signal-safe'' functions from other functions}. However, since the kernel thread hanlding preemption requires a different signal mask, executing user threads on the kernel alarm thread can cause deadlocks. For this reason, the alarm thread is on a tight loop around a system call to \code{sigwaitinfo}, requiring very little CPU time for preemption. One final detail about the alarm thread is how to wake it when additional communication is required (e.g., on thread termination). This unblocking is also done using {\tt SIGALRM}, but sent throught the \code{pthread_sigqueue}. Indeed, \code{sigwait} can differentiate signals sent from \code{pthread_sigqueue} from signals sent from alarms or the kernel.
    149151
    150152\subsection{Scheduler}
    151 Finally, an aspect that was not mentioned yet is the scheduling algorithm. Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling. Further discussion on scheduling is present in section \ref{futur:sched}.
     153Finally, an aspect that was not mentionned yet is the scheduling algorithm. Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling. Further discussion on scheduling is present in section \label{futur:sched}.
    152154
    153155% ======================================================================
     
    163165\end{center}
    164166\caption{Traditional illustration of a monitor}
    165 \end{figure}
    166 
    167 This picture has several components, the two most important being the entry-queue and the AS-stack. The entry-queue is an (almost) FIFO list where threads waiting to enter are parked, while the acceptor-signaler (AS) stack is a FILO list used for threads that have been signalled or otherwise marked as running next.
    168 
    169 For \CFA, this picture does not have support for blocking multiple monitors on a single condition. To support \gls{bulk-acq} two changes to this picture are required. First, it is no longer helpful to attach the condition to \emph{a single} monitor. Secondly, the thread waiting on the condition has to be separated across multiple monitors, seen in figure \ref{fig:monitor_cfa}.
     167\label{fig:monitor}
     168\end{figure}
     169
     170This picture has several components, the two most important being the entry-queue and the AS-stack. The entry-queue is an (almost) FIFO list where threads waiting to enter are parked, while the acceptor-signalor (AS) stack is a FILO list used for threads that have been signalled or otherwise marked as running next.
     171
     172For \CFA, this picture does not have support for blocking multiple monitors on a single condition. To support \gls{bulk-acq} two changes to this picture are required. First, it is non longer helpful to attach the condition to a single monitor. Secondly, the thread waiting on the conditions has to be seperated multiple monitors, which yields :
    170173
    171174\begin{figure}[H]
     
    177180\end{figure}
    178181
    179 This picture and the proper entry and leave algorithms (see listing \ref{lst:entry2}) is the fundamental implementation of internal scheduling. Note that when a thread is moved from the condition to the AS-stack, it is conceptually split the thread into N pieces, where N is the number of monitors specified in the parameter list. The thread is woken up when all the pieces have popped from the AS-stacks and made active. In this picture, the threads are split into halves but this is only because there are two monitors. For a specific signaling operation every monitor needs a piece of thread on its AS-stack.
     182This picture and the proper entry and leave algorithms is the fundamental implementation of internal scheduling (see listing \ref{lst:entry2}). Note that when threads are moved from the condition to the AS-stack, it splits the thread into to pieces. The thread is woken up when all the pieces have moved from the AS-stacks to the active thread seat. In this picture, the threads are split into halves but this is only because there are two monitors in this picture. For a specific signaling operation every monitor needs a piece of thread on its AS-stack.
    180183
    181184\begin{figure}[b]
     
    206209\end{pseudo}
    207210\end{multicols}
    208 \begin{pseudo}[caption={Entry and exit routine for monitors with internal scheduling},label={lst:entry2}]
    209 \end{pseudo}
    210 \end{figure}
    211 
    212 Some important things to notice about the exit routine. The solution discussed in \ref{intsched} can be seen in the exit routine of listing \ref{lst:entry2}. Basically, the solution boils down to having a separate 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 transferred ownership. This solution is deadlock safe as well as preventing any potential barging. The data structure used for the AS-stack are reused extensively for external scheduling, but in the case of internal scheduling, the data is allocated using variable-length arrays on the call-stack of the \code{wait} and \code{signal_block} routines.
     211\caption{Entry and exit routine for monitors with internal scheduling}
     212\label{lst:entry2}
     213\end{figure}
     214
     215Some important things to notice about the exit routine. The solution discussed in \ref{intsched} can be seen in the exit routine of listing \ref{lst:entry2}. 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 transferred ownership. This solution is deadlock safe as well as preventing any potential barging. The data structure used for the AS-stack are reused extensively for external scheduling, but in the case of internal scheduling, the data is allocated using variable-length arrays on the callstack of the \code{wait} and \code{signal_block} routines.
    213216
    214217\begin{figure}[H]
     
    220223\end{figure}
    221224
    222 Figure \ref{fig:structs} shows a high-level representation of these data-structures. The main idea behind them is that, a thread cannot contain an arbitrary number of intrusive stacks for linking onto monitor. The \code{condition node} is the data structure that is queued onto a condition variable and, when signaled, the condition queue is popped and each \code{condition criterion} are moved to the AS-stack. Once all the criterion have be popped from their respective AS-stacks, the thread is woken-up, which is what is shown in listing \ref{lst:entry2}.
     225Figure \ref{fig:structs} shows a high level representation of these data-structures. The main idea behind them is that, while figure \ref{fig:monitor_cfa} is a nice illustration in theory, in practice breaking a threads into multiple pieces to put unto intrusive stacks does not make sense. The \code{condition node} is the data structure that is queued into a condition variable and, when signaled, the condition queue is popped and each \code{condition criterion} are moved to the AS-stack. Once all the criterion have be popped from their respective AS-stacks, the thread is woken-up, which is what is shown in listing \ref{lst:entry2}.
    223226
    224227% ======================================================================
     
    227230% ======================================================================
    228231% ======================================================================
    229 Similarly to internal scheduling, external scheduling for multiple monitors relies on the idea that waiting-thread queues are no longer specific to a single monitor, as mentioned in section \ref{extsched}. For internal scheduling, these queues are part of condition variables, which are still unique for a given scheduling operation (e.g., no signal statement uses multiple conditions). However, in the case of external scheduling, there is no equivalent object which is associated with \code{waitfor} statements. This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired. These monitors being the only objects that have sufficient lifetime and are available on both sides of the \code{waitfor} statement. This requires an algorithm to choose which monitor holds the relevant queue. It is also important that said algorithm be independent of the order in which users list parameters. The proposed algorithm is to fall back on monitor lock ordering (sorting by address) and specify that the monitor that is acquired first is the one with the relevant waiting queue. This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint.
     232Similarly to internal scheduling, external scheduling for multiple monitors relies on the idea that waiting-thread queues are no longer specific to a single monitor, as mentionned in section \ref{extsched}. For internal scheduling, these queues are part of condition variables which are still unique for a given scheduling operation (e.g., no single statment uses multiple conditions). However, in the case of external scheduling, there is no equivalent object which is associated with \code{waitfor} statements. This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired. The monitors being the only objects that have sufficient lifetime and are available on both sides of the \code{waitfor} statment. This requires an algorithm to choose which monitor holds the relevant queue. It is also important that said algorithm be independent of the order in which users list parameters. The proposed algorithm is to fall back on monitor lock ordering and specify that the monitor that is acquired first is the one with the relevant wainting queue. This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint.
    230233
    231234This algorithm choice has two consequences :
    232235\begin{itemize}
    233         \item The queue of the monitor with the lowest address is no longer a true FIFO queue because threads can be moved to the front of the queue. These queues need to contain a set of monitors for each of the waiting threads. Therefore, another thread whose set contains the same lowest address monitor but different lower priority monitors may arrive first but enter the critical section after a thread with the correct pairing.
    234         \item The queue of the lowest priority monitor is both required and potentially unused. Indeed, since it is not known at compile time which monitor is the monitor with have the lowest address, every monitor needs to have the correct queues even though it is possible that some queues go unused for the entire duration of the program, for example if a monitor is only used in a specific pair.
     236        \item The queue of the highest priority monitor is no longer a true FIFO queue because threads can be moved to the front of the queue. These queues need to contain a set of monitors for each of the waiting threads. Therefore, another thread whose set contains the same highest priority monitor but different lower priority monitors may arrive first but enter the critical section after a thread with the correct pairing.
     237        \item The queue of the lowest priority monitor is both required and potentially unused. Indeed, since it is not known at compile time which monitor will be the lowest priority monitor, every monitor needs to have the correct queues even though it is possible that some queues will go unused for the entire duration of the program, for example if a monitor is only used in a specific pair.
    235238\end{itemize}
     239
    236240Therefore, the following modifications need to be made to support external scheduling :
    237241\begin{itemize}
    238         \item The threads waiting on the entry-queue need to keep track of which routine it is trying to enter, and using which set of monitors. The \code{mutex} routine already has all the required information on its stack so the thread only needs to keep a pointer to that information.
    239         \item The monitors need to keep a mask of acceptable routines. This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it. It also needs storage to keep track of which routine was accepted. Since this information is not specific to any monitor, the monitors actually contain a pointer to an integer on the stack of the waiting thread. Note that if a thread has acquired two monitors but executes a \code{waitfor} with only one monitor as a parameter, setting the mask of acceptable routines to both monitors will not cause any problems since the extra monitor will not change ownership regardless. This becomes relevant when \code{when} clauses affect the number of monitors passed to a \code{waitfor} statement.
     242        \item The threads waiting on the entry-queue need to keep track of which routine is trying to enter, and using which set of monitors. The \code{mutex} routine already has all the required information on its stack so the thread only needs to keep a pointer to that information.
     243        \item The monitors need to keep a mask of acceptable routines. This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it. It also needs storage to keep track of which routine was accepted. Since this information is not specific to any monitor, the monitors actually contain a pointer to an integer on the stack of the waiting thread. Note that the complete mask can be pushed to any owned monitors, regardless of \code{when} statements, the \code{waitfor} statement is used in a context where the thread already has full ownership of (at least) every concerned monitor and therefore monitors will refuse all calls no matter what.
    240244        \item The entry/exit routine need to be updated as shown in listing \ref{lst:entry3}.
    241245\end{itemize}
    242246
    243247\subsection{External scheduling - destructors}
    244 Finally, to support the ordering inversion of destructors, the code generation needs to be modified to use a special entry routine. This routine is needed because of the storage requirements of the call order inversion. Indeed, when waiting for the destructors, storage is need for the waiting context and the lifetime of said storage needs to outlive the waiting operation it is needed for. For regular \code{waitfor} statements, the call-stack of the routine itself matches this requirement but it is no longer the case when waiting for the destructor since it is pushed on to the AS-stack for later. The waitfor semantics can then be adjusted correspondingly, as seen in listing \ref{lst:entry-dtor}
     248Finally, to support the ordering inversion of destructors, the code generation needs to be modified to use a special entry routine. This routine is needed because of the storage requirements of the call order inversion. Indeed, when waiting for the destructors, storage is need for the waiting context and the lifetime of said storage needs to outlive the waiting operation it is needed for. For regular \code{waitfor} statements, the callstack of the routine itself matches this requirement but it is no longer the case when waiting for the destructor since it is pushed on to the AS-stack for later. The waitfor semantics can then be adjusted correspondingly, as seen in listing \ref{lst:entry-dtor}
    245249
    246250\begin{figure}
     
    276280\end{pseudo}
    277281\end{multicols}
    278 \begin{pseudo}[caption={Entry and exit routine for monitors with internal scheduling and external scheduling},label={lst:entry3}]
    279 \end{pseudo}
     282\caption{Entry and exit routine for monitors with internal scheduling and external scheduling}
     283\label{lst:entry3}
    280284\end{figure}
    281285
     
    322326\end{pseudo}
    323327\end{multicols}
    324 \begin{pseudo}[caption={Pseudo code for the \code{waitfor} routine and the \code{mutex} entry routine for destructors},label={lst:entry-dtor}]
    325 \end{pseudo}
    326 \end{figure}
     328\caption{Pseudo code for the \code{waitfor} routine and the \code{mutex} entry routine for destructors}
     329\label{lst:entry-dtor}
     330\end{figure}
  • doc/proposals/concurrency/text/parallelism.tex

    r9c35431 rc6e2c18  
    77% #       #     # #     # #     # ####### ####### ####### ####### ###  #####  #     #
    88\chapter{Parallelism}
    9 Historically, computer performance was about processor speeds and instructions count. However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}. In this decade, it is not longer reasonable to create a high-performance application without caring about parallelism. Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization. The lowest-level approach of parallelism is to use \glspl{kthread} in combination with semantics like \code{fork}, \code{join}, etc. However, since these have significant costs and limitations, \glspl{kthread} are now mostly used as an implementation tool rather than a user oriented one. There are several alternatives to solve these issues that all have strengths and weaknesses. While there are many variations of the presented paradigms, most of these variations do not actually change the guarantees or the semantics, they simply move costs in order to achieve better performance for certain workloads.
     9Historically, computer performance was about processor speeds and instructions count. However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}. In this decade, it is not longer reasonnable to create a high-performance application without caring about parallelism. Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization. The lowest-level approach of parallelism is to use \glspl{kthread} in combination with semantics like \code{fork}, \code{join}, etc. However, since these have significant costs and limitations, \glspl{kthread} are now mostly used as an implementation tool rather than a user oriented one. There are several alternatives to solve these issues that all have strengths and weaknesses. While there are many variations of the presented paradigms, most of these variations do not actually change the guarantees or the semantics, they simply move costs in order to achieve better performance for certain workloads.
    1010
    11 \section{Paradigms}
     11\section{Paradigm}
    1212\subsection{User-level threads}
    13 A direct improvement on the \gls{kthread} approach is to use \glspl{uthread}. These threads offer most of the same features that the operating system already provide but can be used on a much larger scale. This approach is the most powerful solution as it allows all the features of multi-threading, while removing several of the more expensive costs of kernel threads. The down side is that almost none of the low-level threading problems are hidden; users still have to think about data races, deadlocks and synchronization issues. These issues can be somewhat alleviated by a concurrency toolkit with strong guarantees but the parallelism toolkit offers very little to reduce complexity in itself.
     13A direct improvement on the \gls{kthread} approach is to use \glspl{uthread}. These threads offer most of the same features that the operating system already provide but can be used on a much larger scale. This approach is the most powerfull solution as it allows all the features of multi-threading, while removing several of the more expensive costs of kernel threads. The down side is that almost none of the low-level threading problems are hidden; users still have to think about data races, deadlocks and synchronization issues. These issues can be somewhat alleviated by a concurrency toolkit with strong garantees but the parallelism toolkit offers very little to reduce complexity in itself.
    1414
    1515Examples of languages that support \glspl{uthread} are Erlang~\cite{Erlang} and \uC~\cite{uC++book}.
    1616
    1717\subsection{Fibers : user-level threads without preemption} \label{fibers}
    18 A popular variant of \glspl{uthread} is what is often referred to as \glspl{fiber}. However, \glspl{fiber} do not present meaningful semantical differences with \glspl{uthread}. The significant difference between \glspl{uthread} and \glspl{fiber} is the lack of \gls{preemption} in the latter. Advocates of \glspl{fiber} list their high performance and ease of implementation as majors strengths but the performance difference between \glspl{uthread} and \glspl{fiber} is controversial, and the ease of implementation, while true, is a weak argument in the context of language design. Therefore this proposal largely ignores fibers.
     18A popular varient of \glspl{uthread} is what is often refered to as \glspl{fiber}. However, \glspl{fiber} do not present meaningful semantical differences with \glspl{uthread}. The significant difference between \glspl{uthread} and \glspl{fiber} is the lack of \gls{preemption} in the later one. Advocates of \glspl{fiber} list their high performance and ease of implementation as majors strenghts of \glspl{fiber} but the performance difference between \glspl{uthread} and \glspl{fiber} is controversial, and the ease of implementation, while true, is a weak argument in the context of language design. Therefore this proposal largely ignores fibers.
    1919
    2020An example of a language that uses fibers is Go~\cite{Go}
     
    2626
    2727\subsection{Paradigm performance}
    28 While the choice between the three paradigms listed above may have significant performance implication, it is difficult to pin-down the performance implications of choosing 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 guarantees that the \gls{pool} based system has the best performance thanks to the lower memory overhead (i.e., no 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 utilization, 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 amortized by the actual work done.
     28While 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., no 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.
    2929
    3030\section{The \protect\CFA\ Kernel : Processors, Clusters and Threads}\label{kernel}
    31 A \gls{cfacluster} is a group of \gls{kthread} executed in isolation. \Glspl{uthread} are scheduled on the \glspl{kthread} of a given \gls{cfacluster}, allowing organization between \glspl{uthread} and \glspl{kthread}. It is important that \glspl{kthread} belonging to a same \glspl{cfacluster} have homogeneous settings, otherwise migrating a \gls{uthread} from one \gls{kthread} to the other can cause issues. A \gls{cfacluster} also offers a plugable scheduler that can optimize the workload generated by the \glspl{uthread}.
    3231
    33 \Glspl{cfacluster} have not been fully implemented in the context of this thesis, currently \CFA only supports one \gls{cfacluster}, the initial one.
     32\Glspl{cfacluster} have not been fully implmented in the context of this thesis, currently \CFA only supports one \gls{cfacluster}, the initial one. The objective of \gls{cfacluster} is to group \gls{kthread} with identical settings together. \Glspl{uthread} can be scheduled on a \glspl{kthread} of a given \gls{cfacluster}, allowing organization between \glspl{kthread} and \glspl{uthread}. It is important that \glspl{kthread} belonging to a same \glspl{cfacluster} have homogenous settings, otherwise migrating a \gls{uthread} from one \gls{kthread} to the other can cause issues.
    3433
    3534\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 heterogeneous setups. For example, a system using \acrshort{numa} configurations may benefit from users being able to tie clusters and\/or kernel threads to certain CPU cores. OS support for CPU affinity is now common~\cite{affinityLinux, affinityWindows, affinityFreebsd, affinityNetbsd, affinityMacosx} which means it is both possible and desirable for \CFA to offer an abstraction mechanism for portable CPU affinity.
     35While 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 \cite{affinityLinux, affinityWindows, affinityFreebsd, affinityNetbsd, affinityMacosx} which means it is both possible and desirable for \CFA to offer an abstraction mechanism for portable CPU affinity.
    3736
    38 \subsection{Paradigms}\label{cfaparadigms}
    39 Given these building blocks, it is possible to reproduce all three of the popular paradigms. Indeed, \glspl{uthread} is the default paradigm in \CFA. However, disabling \gls{preemption} on the \gls{cfacluster} means \glspl{cfathread} effectively become \glspl{fiber}. Since several \glspl{cfacluster} with different scheduling policy can coexist in the same application, this allows \glspl{fiber} and \glspl{uthread} to coexist in the runtime of an application. Finally, it is possible to build executors for thread pools from \glspl{uthread} or \glspl{fiber}, which includes specialize jobs like actors~\cite{Actors}.
     37% \subsection{Paradigms}\label{cfaparadigms}
     38% Given these building blocks, it is possible to reproduce all three of the popular paradigms. Indeed, \glspl{uthread} is the default paradigm in \CFA. However, disabling \gls{preemption} on the \gls{cfacluster} means \glspl{cfathread} effectively become \glspl{fiber}. Since several \glspl{cfacluster} with different scheduling policy can coexist in the same application, this allows \glspl{fiber} and \glspl{uthread} to coexist in the runtime of an application. Finally, it is possible to build executors for thread pools from \glspl{uthread} or \glspl{fiber}.
  • doc/proposals/concurrency/text/results.tex

    r9c35431 rc6e2c18  
    55% ======================================================================
    66\section{Machine setup}
    7 Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks. All tests where made on this machine.
    8 \begin{table}[H]
     7Table \ref{tab:machine} shows the characteristiques of the machine used to run the benchmarks. All tests where made on this machine.
     8\begin{figure}[H]
    99\begin{center}
    1010\begin{tabular}{| l | r | l | r |}
     
    2525\hline
    2626\hline
    27 Operating system                & Ubuntu 16.04.3 LTS    & Kernel                & Linux 4.4-97-generic \\
    28 \hline
    29 Compiler                        & GCC 6.3               & Translator    & CFA 1 \\
    30 \hline
    31 Java version            & OpenJDK-9             & Go version    & 1.9.2 \\
     27Operating system                & Ubuntu 16.04.3 LTS    & Kernel                & Linux 4.4.0-97-generic \\
     28\hline
     29Compiler                        & gcc 6.3.0             & Translator    & CFA 1.0.0 \\
    3230\hline
    3331\end{tabular}
     
    3533\caption{Machine setup used for the tests}
    3634\label{tab:machine}
    37 \end{table}
     35\end{figure}
    3836
    3937\section{Micro benchmarks}
     
    4139\begin{pseudo}
    4240#define BENCH(run, result)
    43         before = gettime();
     41        gettime();
    4442        run;
    45         after  = gettime();
     43        gettime();
    4644        result = (after - before) / N;
    4745\end{pseudo}
    48 The method used to get time is \code{clock_gettime(CLOCK_THREAD_CPUTIME_ID);}. Each benchmark is using many iterations of a simple call to measure the cost of the call. The specific number of iteration depends on the specific benchmark.
     46The method used to get time is \code{clock_gettime(CLOCK_THREAD_CPUTIME_ID);}. Each benchmark is using many interations of a simple call to measure the cost of the call. The specific number of interation dependes on the specific benchmark.
    4947
    5048\subsection{Context-switching}
    51 The first interesting benchmark is to measure how long context-switches take. The simplest approach to do this is to yield on a thread, which executes a 2-step context switch. In order to make the comparison fair, coroutines also execute a 2-step context-switch (\gls{uthread} to \gls{kthread} then \gls{kthread} to \gls{uthread}), which is a resume/suspend cycle instead of a yield. Listing \ref{lst:ctx-switch} shows the code for coroutines and threads whith the results in table \ref{tab:ctx-switch}. All omitted tests are functionally identical to one of these tests.
     49The first interesting benchmark is to measure how long context-switches take. The simplest approach to do this is to yield on a thread, which executes a 2-step context switch. In order to make the comparison fair, coroutines also execute a 2-step context-switch, which is a resume/suspend cycle instead of a yield. Listing \ref{lst:ctx-switch} shows the code for coroutines and threads. All omitted tests are functionally identical to one of these tests. The results can be shown in table \ref{tab:ctx-switch}.
    5250\begin{figure}
    5351\begin{multicols}{2}
     
    9088\end{cfacode}
    9189\end{multicols}
    92 \begin{cfacode}[caption={\CFA benchmark code used to measure context-switches for coroutines and threads.},label={lst:ctx-switch}]
    93 \end{cfacode}
    94 \end{figure}
    95 
    96 \begin{table}
    97 \begin{center}
    98 \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
    99 \cline{2-4}
    100 \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
    101 \hline
    102 Kernel Thread   & 241.5 & 243.86        & 5.08 \\
    103 \CFA Coroutine  & 38            & 38            & 0    \\
    104 \CFA Thread             & 103           & 102.96        & 2.96 \\
    105 \uC Coroutine   & 46            & 45.86 & 0.35 \\
    106 \uC Thread              & 98            & 99.11 & 1.42 \\
    107 Goroutine               & 150           & 149.96        & 3.16 \\
    108 Java Thread             & 289           & 290.68        & 8.72 \\
    109 \hline
    110 \end{tabular}
    111 \end{center}
    112 \caption{Context Switch comparison. All numbers are in nanoseconds(\si{\nano\second})}
     90\caption{\CFA benchmark code used to measure context-switches for coroutines and threads.}
     91\label{lst:ctx-switch}
     92\end{figure}
     93
     94\begin{figure}
     95\begin{center}
     96\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     97\cline{2-4}
     98\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
     99\hline
     100Kernel Threads          & 239           & 242.57        & 5.54 \\
     101\CFA Coroutines         & 38            & 38            & 0    \\
     102\CFA Threads            & 102           & 102.39        & 1.57 \\
     103\uC Coroutines          & 46            & 46.68 & 0.47 \\
     104\uC Threads                     & 98            & 99.39 & 1.52 \\
     105\hline
     106\end{tabular}
     107\end{center}
     108\caption{Context Switch comparaison. All numbers are in nanoseconds(\si{\nano\second})}
    113109\label{tab:ctx-switch}
    114 \end{table}
     110\end{figure}
    115111
    116112\subsection{Mutual-exclusion}
    117 The next interesting benchmark is to measure the overhead to enter/leave a critical-section. For monitors, the simplest approach is to measure how long it takes to enter and leave a monitor routine. Listing \ref{lst:mutex} shows the code for \CFA. To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a pthread mutex lock are also measured. The results can be shown in table \ref{tab:mutex}.
    118 
    119 \begin{figure}
    120 \begin{cfacode}[caption={\CFA benchmark code used to measure mutex routines.},label={lst:mutex}]
     113The next interesting benchmark is to measure the overhead to enter/leave a critical-section. For monitors, the simplest appraoch is to measure how long it takes enter and leave a monitor routine. Listing \ref{lst:mutex} shows the code for \CFA. To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a pthread mutex lock are also mesured. The results can be shown in table \ref{tab:mutex}.
     114
     115\begin{figure}
     116\begin{cfacode}
    121117monitor M {};
    122118void __attribute__((noinline)) call( M & mutex m /*, m2, m3, m4*/ ) {}
     
    133129}
    134130\end{cfacode}
    135 \end{figure}
    136 
    137 \begin{table}
    138 \begin{center}
    139 \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
    140 \cline{2-4}
    141 \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
    142 \hline
    143 C routine                                               & 2             & 2             & 0    \\
    144 FetchAdd + FetchSub                             & 26            & 26            & 0    \\
    145 Pthreads Mutex Lock                             & 31            & 31.86 & 0.99 \\
    146 \uC \code{monitor} member routine               & 30            & 30            & 0    \\
    147 \CFA \code{mutex} routine, 1 argument   & 41            & 41.57 & 0.9  \\
    148 \CFA \code{mutex} routine, 2 argument   & 76            & 76.96 & 1.57 \\
    149 \CFA \code{mutex} routine, 4 argument   & 145           & 146.68        & 3.85 \\
    150 Java synchronized routine                       & 27            & 28.57 & 2.6  \\
    151 \hline
    152 \end{tabular}
    153 \end{center}
    154 \caption{Mutex routine comparison. All numbers are in nanoseconds(\si{\nano\second})}
     131\caption{\CFA benchmark code used to measure mutex routines.}
     132\label{lst:mutex}
     133\end{figure}
     134
     135\begin{figure}
     136\begin{center}
     137\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     138\cline{2-4}
     139\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
     140\hline
     141C routine                                               & 2             & 2             & 0      \\
     142Pthreads Mutex Lock                             & 31            & 31.86 & 0.99   \\
     143\uC \code{monitor} member routine               & 30            & 30            & 0      \\
     144\CFA \code{mutex} routine, 1 argument   & 46            & 46.14 & 0.74  \\
     145\CFA \code{mutex} routine, 2 argument   & 82            & 83            & 1.93  \\
     146\CFA \code{mutex} routine, 4 argument   & 165           & 161.15        & 54.04  \\
     147\hline
     148\end{tabular}
     149\end{center}
     150\caption{Mutex routine comparaison. All numbers are in nanoseconds(\si{\nano\second})}
    155151\label{tab:mutex}
    156 \end{table}
     152\end{figure}
    157153
    158154\subsection{Internal scheduling}
    159 The internal-scheduling benchmark measures the cost of waiting on and signalling a condition variable. Listing \ref{lst:int-sched} shows the code for \CFA, with results table \ref{tab:int-sched}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
    160 
    161 \begin{figure}
    162 \begin{cfacode}[caption={Benchmark code for internal scheduling},label={lst:int-sched}]
     155The Internal scheduling benchmark measures the cost of waiting on and signaling a condition variable. Listing \ref{lst:int-sched} shows the code for \CFA. The results can be shown in table \ref{tab:int-sched}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
     156
     157\begin{figure}
     158\begin{cfacode}
    163159volatile int go = 0;
    164160condition c;
     
    191187}
    192188\end{cfacode}
    193 \end{figure}
    194 
    195 \begin{table}
    196 \begin{center}
    197 \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
    198 \cline{2-4}
    199 \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
    200 \hline
    201 \uC \code{signal}                                       & 322           & 323   & 3.36   \\
    202 \CFA \code{signal}, 1 \code{monitor}    & 352.5 & 353.11        & 3.66   \\
    203 \CFA \code{signal}, 2 \code{monitor}    & 430           & 430.29        & 8.97   \\
    204 \CFA \code{signal}, 4 \code{monitor}    & 594.5 & 606.57        & 18.33  \\
    205 Java \code{notify}                              & 13831.5       & 15698.21      & 4782.3 \\
    206 \hline
    207 \end{tabular}
    208 \end{center}
    209 \caption{Internal scheduling comparison. All numbers are in nanoseconds(\si{\nano\second})}
     189\caption{Benchmark code for internal scheduling}
     190\label{lst:int-sched}
     191\end{figure}
     192
     193\begin{figure}
     194\begin{center}
     195\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     196\cline{2-4}
     197\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
     198\hline
     199\uC \code{signal}                                       & 322           & 322.57        & 2.77  \\
     200\CFA \code{signal}, 1 \code{monitor}    & 1145  & 1163.64       & 27.52 \\
     201\CFA \code{signal}, 2 \code{monitor}    & 1531  & 1550.75       & 32.77 \\
     202\CFA \code{signal}, 4 \code{monitor}    & 2288.5        & 2326.86       & 54.73 \\
     203\hline
     204\end{tabular}
     205\end{center}
     206\caption{Internal scheduling comparaison. All numbers are in nanoseconds(\si{\nano\second})}
    210207\label{tab:int-sched}
    211 \end{table}
     208\end{figure}
    212209
    213210\subsection{External scheduling}
    214 The Internal scheduling benchmark measures the cost of the \code{waitfor} statement (\code{_Accept} in \uC). Listing \ref{lst:ext-sched} shows the code for \CFA, with results in table \ref{tab:ext-sched}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
    215 
    216 \begin{figure}
    217 \begin{cfacode}[caption={Benchmark code for external scheduling},label={lst:ext-sched}]
     211The Internal scheduling benchmark measures the cost of the \code{waitfor} statement (\code{_Accept} in \uC). Listing \ref{lst:ext-sched} shows the code for \CFA. The results can be shown in table \ref{tab:ext-sched}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests.
     212
     213\begin{figure}
     214\begin{cfacode}
    218215volatile int go = 0;
    219216monitor M {};
     
    245242}
    246243\end{cfacode}
    247 \end{figure}
    248 
    249 \begin{table}
    250 \begin{center}
    251 \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
    252 \cline{2-4}
    253 \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
    254 \hline
    255 \uC \code{Accept}                                       & 350           & 350.61        & 3.11  \\
    256 \CFA \code{waitfor}, 1 \code{monitor}   & 358.5 & 358.36        & 3.82  \\
    257 \CFA \code{waitfor}, 2 \code{monitor}   & 422           & 426.79        & 7.95  \\
    258 \CFA \code{waitfor}, 4 \code{monitor}   & 579.5 & 585.46        & 11.25 \\
    259 \hline
    260 \end{tabular}
    261 \end{center}
    262 \caption{External scheduling comparison. All numbers are in nanoseconds(\si{\nano\second})}
     244\caption{Benchmark code for external scheduling}
     245\label{lst:ext-sched}
     246\end{figure}
     247
     248\begin{figure}
     249\begin{center}
     250\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     251\cline{2-4}
     252\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
     253\hline
     254\uC \code{Accept}                                       & 349           & 339.32        & 3.14  \\
     255\CFA \code{waitfor}, 1 \code{monitor}   & 1155.5        & 1142.04       & 25.23 \\
     256\CFA \code{waitfor}, 2 \code{monitor}   & 1361  & 1376.75       & 28.81 \\
     257\CFA \code{waitfor}, 4 \code{monitor}   & 1941.5        & 1957.07       & 34.7  \\
     258\hline
     259\end{tabular}
     260\end{center}
     261\caption{External scheduling comparaison. All numbers are in nanoseconds(\si{\nano\second})}
    263262\label{tab:ext-sched}
    264 \end{table}
     263\end{figure}
    265264
    266265\subsection{Object creation}
    267 Finally, the last benchmark measurs the cost of creation for concurrent objects. Listing \ref{lst:creation} shows the code for pthreads and \CFA threads, with results shown in table \ref{tab:creation}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests. The only note here is that the call-stacks of \CFA coroutines are lazily created, therefore without priming the coroutine, the creation cost is very low.
    268 
    269 \begin{figure}
    270 \begin{center}
     266Finaly, the last benchmark measured is the cost of creation for concurrent objects. Listing \ref{lst:creation} shows the code for pthreads and \CFA threads. The results can be shown in table \ref{tab:creation}. As with all other benchmarks, all omitted tests are functionally identical to one of these tests. The only note here is that the callstacks of \CFA coroutines are lazily created, therefore without priming the coroutine, the creation cost is very low.
     267
     268\begin{figure}
     269\begin{multicols}{2}
    271270pthread
    272 \begin{ccode}
     271\begin{cfacode}
    273272int main() {
    274273        BENCH(
    275274                for(size_t i=0; i<n; i++) {
    276275                        pthread_t thread;
    277                         if(pthread_create(&thread,NULL,foo,NULL)<0) {
     276                        if(pthread_create(
     277                                &thread,
     278                                NULL,
     279                                foo,
     280                                NULL
     281                        ) < 0) {
    278282                                perror( "failure" );
    279283                                return 1;
    280284                        }
    281285
    282                         if(pthread_join(thread, NULL)<0) {
     286                        if(pthread_join(
     287                                thread,
     288                                NULL
     289                        ) < 0) {
    283290                                perror( "failure" );
    284291                                return 1;
     
    289296        printf("%llu\n", result);
    290297}
    291 \end{ccode}
    292 
    293 
    294 
     298\end{cfacode}
     299\columnbreak
    295300\CFA Threads
    296301\begin{cfacode}
     
    302307                result
    303308        )
    304         printf("%llu\n", result);
    305 }
    306 \end{cfacode}
    307 \end{center}
    308 \begin{cfacode}[caption={Benchmark code for pthreads and \CFA to measure object creation},label={lst:creation}]
    309 \end{cfacode}
    310 \end{figure}
    311 
    312 \begin{table}
    313 \begin{center}
    314 \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
    315 \cline{2-4}
    316 \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
    317 \hline
    318 Pthreads                        & 26996 & 26984.71      & 156.6  \\
    319 \CFA Coroutine Lazy     & 6             & 5.71  & 0.45   \\
    320 \CFA Coroutine Eager    & 708           & 706.68        & 4.82   \\
    321 \CFA Thread                     & 1173.5        & 1176.18       & 15.18  \\
    322 \uC Coroutine           & 109           & 107.46        & 1.74   \\
    323 \uC Thread                      & 526           & 530.89        & 9.73   \\
    324 Goroutine                       & 2520.5        & 2530.93       & 61,56  \\
    325 Java Thread                     & 91114.5       & 92272.79      & 961.58 \\
    326 \hline
    327 \end{tabular}
    328 \end{center}
    329 \caption{Creation comparison. All numbers are in nanoseconds(\si{\nano\second})}
     309
     310        printf("%llu\n", result);
     311}
     312\end{cfacode}
     313\end{multicols}
     314\caption{Bechmark code for pthreads and \CFA to measure object creation}
     315\label{lst:creation}
     316\end{figure}
     317
     318\begin{figure}
     319\begin{center}
     320\begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |}
     321\cline{2-4}
     322\multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\
     323\hline
     324Pthreads                        & 26974.5       & 26977 & 124.12 \\
     325\CFA Coroutines Lazy    & 5             & 5             & 0      \\
     326\CFA Coroutines Eager   & 335.0 & 357.67        & 34.2   \\
     327\CFA Threads            & 1122.5        & 1109.86       & 36.54  \\
     328\uC Coroutines          & 106           & 107.04        & 1.61   \\
     329\uC Threads                     & 525.5 & 533.04        & 11.14  \\
     330\hline
     331\end{tabular}
     332\end{center}
     333\caption{Creation comparaison. All numbers are in nanoseconds(\si{\nano\second})}
    330334\label{tab:creation}
    331 \end{table}
     335\end{figure}
  • doc/proposals/concurrency/text/together.tex

    r9c35431 rc6e2c18  
    77
    88\section{Threads as monitors}
    9 As it was subtly alluded in section \ref{threads}, \code{thread}s in \CFA are in fact monitors, which means that all monitor 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 \begin{figure}[H]
    11 \begin{cfacode}[caption={Toy simulator using \code{thread}s and \code{monitor}s.},label={lst:engine-v1}]
     9As it was subtely alluded in section \ref{threads}, \code{threads} in \CFA are in fact monitors, which means that all monitor 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\begin{cfacode}
    1211// Visualization declaration
    1312thread Renderer {} renderer;
     
    2120void draw( Renderer & mutex this, Frame * frame );
    2221
    23 // Simulation loop
     22// Simualation loop
    2423void main( Simulator & this ) {
    2524        while( true ) {
     
    3736}
    3837\end{cfacode}
    39 \end{figure}
    4038One of the obvious complaints of the previous code snippet (other than its toy-like simplicity) is that it does not handle exit conditions and just goes on forever. Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner :
    41 \begin{figure}[H]
    42 \begin{cfacode}[caption={Same toy simulator with proper termination condition.},label={lst:engine-v2}]
     39\begin{cfacode}
    4340// Visualization declaration
    4441thread Renderer {} renderer;
     
    5249void draw( Renderer & mutex this, Frame * frame );
    5350
    54 // Simulation loop
     51// Simualation loop
    5552void main( Simulator & this ) {
    5653        while( true ) {
     
    7976// Call destructor for renderer to signify shutdown
    8077\end{cfacode}
    81 \end{figure}
    8278
    8379\section{Fibers \& Threads}
    84 As mentioned in section \ref{preemption}, \CFA uses preemptive threads by default but can use fibers on demand. Currently, using fibers is done by adding the following line of code to the program~:
     80As mentionned in section \ref{preemption}, \CFA uses preemptive threads by default but can use fibers on demand. Currently, using fibers is done by adding the following line of code to the program~:
    8581\begin{cfacode}
    8682unsigned int default_preemption() {
     
    8884}
    8985\end{cfacode}
    90 This function is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice, i.e., no preemption. However, once clusters are fully implemented, it will be possible to create fibers and \glspl{uthread} in the same system, as in listing \ref{lst:fiber-uthread}
     86This function is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice i.e. no preemption. However, once clusters are fully implemented, it will be possible to create fibers and uthreads in on the same system :
    9187\begin{figure}
    92 \begin{cfacode}[caption={Using fibers and \glspl{uthread} side-by-side in \CFA},label={lst:fiber-uthread}]
     88\begin{cfacode}
    9389//Cluster forward declaration
    9490struct cluster;
  • doc/proposals/concurrency/thesis.tex

    r9c35431 rc6e2c18  
    8282\rfoot{v\input{version}}
    8383
     84%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    8485
     86\begin{document}
     87% \linenumbers
    8588
    86 %======================================================================
    87 %   L O G I C A L    D O C U M E N T -- the content of your thesis
    88 %======================================================================
    89 \begin{document}
     89\title{Concurrency in \CFA}
     90\author{Thierry Delisle \\
     91School of Computer Science, University of Waterloo, \\ Waterloo, Ontario, Canada
     92}
    9093
    91 % For a large document, it is a good idea to divide your thesis
    92 % into several files, each one containing one chapter.
    93 % To illustrate this idea, the "front pages" (i.e., title page,
    94 % declaration, borrowers' page, abstract, acknowledgements,
    95 % dedication, table of contents, list of tables, list of figures,
    96 % nomenclature) are contained within the file "thesis-frontpgs.tex" which is
    97 % included into the document by the following statement.
    98 %----------------------------------------------------------------------
    99 % FRONT MATERIAL
    100 %----------------------------------------------------------------------
    101 \input{frontpgs}
     94\maketitle
    10295
    103 %----------------------------------------------------------------------
    104 % MAIN BODY
    105 %----------------------------------------------------------------------
     96\tableofcontents
    10697
    10798\input{intro}
     
    123114\input{future}
    124115
     116\chapter{Conclusion}
     117
     118\section*{Acknowledgements}
     119
    125120\clearpage
    126121\printglossary[type=\acronymtype]
  • doc/proposals/concurrency/version

    r9c35431 rc6e2c18  
    1 0.11.280
     10.11.129
  • doc/refrat/refrat.tex

    r9c35431 rc6e2c18  
    1111%% Created On       : Wed Apr  6 14:52:25 2016
    1212%% Last Modified By : Peter A. Buhr
    13 %% Last Modified On : Tue Aug 15 18:46:31 2017
    14 %% Update Count     : 106
     13%% Last Modified On : Sun Aug  6 10:25:31 2017
     14%% Update Count     : 105
    1515%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    1616
     
    492492
    493493\begin{rationale}
    494 The use of ``©?©'' in identifiers means that some C programs are not \CFA programs.
    495 For instance, the sequence of characters ``©(i < 0)?--i:i©'' is legal in a C program, but a \CFA compiler detects a syntax error because it treats ``©?--©'' as an identifier, not as the two tokens ``©?©'' and ``©--©''.
     494The use of ``©?©'' in identifiers means that some C programs are not \CFA programs.  For instance, the sequence of characters ``©(i < 0)?--i:i©'' is legal in a C program, but a
     495\CFA compiler detects a syntax error because it treats ``©?--©'' as an identifier, not as the two tokens ``©?©'' and ``©--©''.
    496496\end{rationale}
    497497
  • doc/user/user.tex

    r9c35431 rc6e2c18  
    1111%% Created On       : Wed Apr  6 14:53:29 2016
    1212%% Last Modified By : Peter A. Buhr
    13 %% Last Modified On : Mon Nov 27 18:09:59 2017
    14 %% Update Count     : 3143
     13%% Last Modified On : Sun Aug  6 10:24:21 2017
     14%% Update Count     : 3036
    1515%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    1616
     
    5959\CFAStyle                                                                                               % use default CFA format-style
    6060\lstnewenvironment{C++}[1][]                            % use C++ style
    61 {\lstset{language=C++,moredelim=**[is][\protect\color{red}]{®}{®},#1}}
     61{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{®}{®}#1}}
    6262{}
    6363
     
    777777  case 7:
    778778        ...
    779         ®break®                                         §\C{// explicit end of switch (redundant)
     779        ®break®                                         §\C{// redundant explicit end of switch
    780780  default:
    781781        j = 3;
     
    806806                ®int k = 0;®                    §\C{// allowed at different nesting levels}§
    807807                ...
    808           ®case 2:®                                     §\C{// disallow case in nested statements}§
    809808        }
    810809  ...
     
    963962\end{cfa}
    964963
    965 The components in the "with" clause
    966 
    967   with a, b, c { ... }
    968 
    969 serve 2 purposes: each component provides a type and object. The type must be a
    970 structure type. Enumerations are already opened, and I think a union is opened
    971 to some extent, too. (Or is that just unnamed unions?) The object is the target
    972 that the naked structure-fields apply to. The components are open in "parallel"
    973 at the scope of the "with" clause/statement, so opening "a" does not affect
    974 opening "b", etc. This semantic is different from Pascal, which nests the
    975 openings.
    976 
    977 Having said the above, it seems reasonable to allow a "with" component to be an
    978 expression. The type is the static expression-type and the object is the result
    979 of the expression. Again, the type must be an aggregate. Expressions require
    980 parenthesis around the components.
    981 
    982   with( a, b, c ) { ... }
    983 
    984 Does this now make sense?
    985 
    986 Having written more CFA code, it is becoming clear to me that I *really* want
    987 the "with" to be implemented because I hate having to type all those object
    988 names for fields. It's a great way to drive people away from the language.
    989 
    990964
    991965\section{Exception Handling}
     
    1003977try {
    1004978        f(...);
    1005 } catch( E e ; §boolean-predicate§ ) {                  §\C[8cm]{// termination handler}§
     979} catch( E e : §boolean-predicate§ ) {                  §\C[8cm]{// termination handler}§
    1006980        // recover and continue
    1007 } catchResume( E e ; §boolean-predicate§ ) {    §\C{// resumption handler}\CRT§
     981} catchResume( E e : §boolean-predicate§ ) {    §\C{// resumption handler}\CRT§
    1008982        // repair and return
    1009983} finally {
     
    18981872\end{cfa}
    18991873This syntax allows a prototype declaration to be created by cutting and pasting source text from the routine definition header (or vice versa).
    1900 Like C, it is possible to declare multiple routine-prototypes in a single declaration, where the return type is distributed across \emph{all} routine names in the declaration list (see~\VRef{s:Declarations}), \eg:
    1901 \begin{cfa}
    1902 C :             const double bar1(), bar2( int ), bar3( double );
    1903 §\CFA§: [const double] foo(), foo( int ), foo( double ) { return 3.0; }
    1904 \end{cfa}
    1905 \CFA allows the last routine in the list to define its body.
    1906 
     1874It is possible to declare multiple routine-prototypes in a single declaration, but the entire type specification is distributed across \emph{all} routine names in the declaration list (see~\VRef{s:Declarations}), \eg:
     1875\begin{quote2}
     1876\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
     1877\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
     1878\begin{cfa}
     1879[ int ] f( int ), g;
     1880\end{cfa}
     1881&
     1882\begin{cfa}
     1883int f( int ), g( int );
     1884\end{cfa}
     1885\end{tabular}
     1886\end{quote2}
    19071887Declaration qualifiers can only appear at the start of a \CFA routine declaration,\footref{StorageClassSpecifier} \eg:
    19081888\begin{cfa}
     
    22552235\label{s:MRV_Functions}
    22562236
    2257 In C and most programming languages, functions return at most one value;
    2258 however, many operations have multiple outcomes, some exceptional (see~\VRef{s:ExceptionHandling}).
     2237In standard C, functions can return at most one value.
    22592238To emulate functions with multiple return values, \emph{\Index{aggregation}} and/or \emph{\Index{aliasing}} is used.
    2260 
    2261 In the former approach, a record type is created combining all of the return values.
    2262 For example, consider C's \Indexc{div} function, which returns the quotient and remainder for a division of an integer value.
    2263 \begin{cfa}
    2264 typedef struct { int quot, rem; } div_t;        §\C[7cm]{// from include stdlib.h}§
    2265 div_t div( int num, int den );
    2266 div_t qr = div( 13, 5 );                                        §\C{// return quotient/remainder aggregate}§
    2267 printf( "%d %d\n", qr.quot, qr.rem );           §\C{// print quotient/remainder}§
    2268 \end{cfa}
    2269 This approach requires a name for the return type and fields, where \Index{naming} is a common programming-language issue.
    2270 That is, naming creates an association that must be managed when reading and writing code.
    2271 While effective when used sparingly, this approach does not scale when functions need to return multiple combinations of types.
    2272 
    2273 In the latter approach, additional return values are passed as pointer parameters.
    2274 A pointer parameter is assigned inside the routine to emulate a return.
    2275 For example, consider C's \Indexc{modf} function, which returns the integral and fractional part of a floating-point value.
    2276 \begin{cfa}
    2277 double modf( double x, double * i );            §\C{// from include math.h}§
    2278 double intp, frac = modf( 13.5, &intp );        §\C{// return integral and fractional components}§
    2279 printf( "%g %g\n", intp, frac );                        §\C{// print integral/fractional components}§
    2280 \end{cfa}
    2281 This approach requires allocating storage for the return values, which complicates the call site with a sequence of variable declarations leading to the call.
    2282 Also, while a disciplined use of ©const© can give clues about whether a pointer parameter is used as an \Index{out parameter}, it is not obvious from the routine signature whether the callee expects such a parameter to be initialized before the call.
    2283 Furthermore, while many C routines that accept pointers are safe for a ©NULL© argument, there are many C routines that are not null-safe.
    2284 Finally, C does not provide a mechanism to state that a parameter is going to be used as an additional return value, which makes the job of ensuring that a value is returned more difficult for the compiler.
     2239In the former situation, the function designer creates a record type that combines all of the return values into a single type.
     2240For example, consider a function returning the most frequently occurring letter in a string, and its frequency.
     2241This example is complex enough to illustrate that an array is insufficient, since arrays are homogeneous, and demonstrates a potential pitfall that exists with aliasing.
     2242\begin{cfa}
     2243struct mf_ret {
     2244        int freq;
     2245        char ch;
     2246};
     2247
     2248struct mf_ret most_frequent(const char * str) {
     2249        char freqs [26] = { 0 };
     2250        struct mf_ret ret = { 0, 'a' };
     2251        for (int i = 0; str[i] != '\0'; ++i) {
     2252                if (isalpha(str[i])) {        // only count letters
     2253                        int ch = tolower(str[i]);   // convert to lower case
     2254                        int idx = ch-'a';
     2255                        if (++freqs[idx] > ret.freq) {  // update on new max
     2256                          ret.freq = freqs[idx];
     2257                          ret.ch = ch;
     2258                        }
     2259                }
     2260        }
     2261        return ret;
     2262}
     2263
     2264const char * str = "hello world";
     2265struct mf_ret ret = most_frequent(str);
     2266printf("%s -- %d %c\n", str, ret.freq, ret.ch);
     2267\end{cfa}
     2268Of note, the designer must come up with a name for the return type and for each of its fields.
     2269Unnecessary naming is a common programming language issue, introducing verbosity and a complication of the user's mental model.
     2270That is, adding another named type creates another association in the programmer's mind that needs to be kept track of when reading and writing code.
     2271As such, this technique is effective when used sparingly, but can quickly get out of hand if many functions need to return different combinations of types.
     2272
     2273In the latter approach, the designer simulates multiple return values by passing the additional return values as pointer parameters.
     2274The pointer parameters are assigned inside of the routine body to emulate a return.
     2275Using the same example,
     2276\begin{cfa}
     2277int most_frequent(const char * str, char * ret_ch) {
     2278        char freqs [26] = { 0 };
     2279        int ret_freq = 0;
     2280        for (int i = 0; str[i] != '\0'; ++i) {
     2281                if (isalpha(str[i])) {        // only count letters
     2282                        int ch = tolower(str[i]);   // convert to lower case
     2283                        int idx = ch-'a';
     2284                        if (++freqs[idx] > ret_freq) {  // update on new max
     2285                          ret_freq = freqs[idx];
     2286                          *ret_ch = ch;   // assign to out parameter
     2287                        }
     2288                }
     2289        }
     2290        return ret_freq;  // only one value returned directly
     2291}
     2292
     2293const char * str = "hello world";
     2294char ch;                            // pre-allocate return value
     2295int freq = most_frequent(str, &ch); // pass return value as out parameter
     2296printf("%s -- %d %c\n", str, freq, ch);
     2297\end{cfa}
     2298Notably, using this approach, the caller is directly responsible for allocating storage for the additional temporary return values, which complicates the call site with a sequence of variable declarations leading up to the call.
     2299Also, while a disciplined use of ©const© can give clues about whether a pointer parameter is going to be used as an out parameter, it is not immediately obvious from only the routine signature whether the callee expects such a parameter to be initialized before the call.
     2300Furthermore, while many C routines that accept pointers are designed so that it is safe to pass ©NULL© as a parameter, there are many C routines that are not null-safe.
     2301On a related note, C does not provide a standard mechanism to state that a parameter is going to be used as an additional return value, which makes the job of ensuring that a value is returned more difficult for the compiler.
     2302Interestingly, there is a subtle bug in the previous example, in that ©ret_ch© is never assigned for a string that does not contain any letters, which can lead to undefined behaviour.
     2303In this particular case, it turns out that the frequency return value also doubles as an error code, where a frequency of 0 means the character return value should be ignored.
    22852304Still, not every routine with multiple return values should be required to return an error code, and error codes are easily ignored, so this is not a satisfying solution.
    22862305As with the previous approach, this technique can simulate multiple return values, but in practice it is verbose and error prone.
    22872306
    2288 \CFA allows functions to return multiple values by extending the function declaration syntax.
     2307In \CFA, functions can be declared to return multiple values with an extension to the function declaration syntax.
    22892308Multiple return values are declared as a comma-separated list of types in square brackets in the same location that the return type appears in standard C function declarations.
    2290 \begin{cfa}
    2291 [ char, int, double ] f( ... );
    2292 \end{cfa}
    22932309The ability to return multiple values from a function requires a new syntax for the return statement.
    22942310For consistency, the return statement in \CFA accepts a comma-separated list of expressions in square brackets.
    2295 \begin{cfa}
    2296 return [ c, i, d ];
    2297 \end{cfa}
    2298 The expression resolution ensures the correct form is used depending on the values being returned and the return type of the current function.
     2311The expression resolution phase of the \CFA translator ensures that the correct form is used depending on the values being returned and the return type of the current function.
    22992312A multiple-returning function with return type ©T© can return any expression that is implicitly convertible to ©T©.
    2300 
    2301 A common use of a function's output is input to another function.
    2302 \CFA allows this case, without any new syntax;
    2303 a multiple-returning function can be used in any of the contexts where an expression is allowed.
    2304 When a function call is passed as an argument to another call, the best match of actual arguments to formal parameters is evaluated given all possible expression interpretations in the current scope.
    2305 \begin{cfa}
    2306 void g( int, int );                                                     §\C{// 1}§
    2307 void g( double, double );                                       §\C{// 2}§
    2308 g( div( 13, 5 ) );                                                      §\C{// select 1}§
    2309 g( modf( 13.5 ) );                                                      §\C{// select 2}§
    2310 \end{cfa}
    2311 In this case, there are two overloaded ©g© routines.
    2312 Both calls to ©g© expect two arguments that are matched by the two return values from ©div© and ©modf©. respectively, which are fed directly to the first and second parameters of ©g©.
    2313 As well, both calls to ©g© have exact type matches for the two different versions of ©g©, so these exact matches are chosen.
    2314 When type matches are not exact, conversions are used to find a best match.
    2315 
    2316 The previous examples can be rewritten passing the multiple returned-values directly to the ©printf© function call.
    2317 \begin{cfa}
    2318 [ int, int ] div( int x, int y );                       §\C{// from include stdlib}§
    2319 printf( "%d %d\n", div( 13, 5 ) );                      §\C{// print quotient/remainder}§
    2320 
    2321 [ double, double ] modf( double x );            §\C{// from include math}§
    2322 printf( "%g %g\n", modf( 13.5 ) );                      §\C{// print integral/fractional components}§
    2323 \end{cfa}
    2324 This approach provides the benefits of compile-time checking for appropriate return statements as in aggregation, but without the required verbosity of declaring a new named type.
    2325 
    2326 Finally, the addition of multiple-return-value functions necessitates a syntax for retaining the multiple values at the call-site versus their temporary existence during a call.
     2313Using the running example, the ©most_frequent© function can be written using multiple return values as such,
     2314\begin{cfa}
     2315[int, char] most_frequent(const char * str) {
     2316        char freqs [26] = { 0 };
     2317        int ret_freq = 0;
     2318        char ret_ch = 'a';  // arbitrary default value for consistent results
     2319        for (int i = 0; str[i] != '\0'; ++i) {
     2320                if (isalpha(str[i])) {        // only count letters
     2321                        int ch = tolower(str[i]);   // convert to lower case
     2322                        int idx = ch-'a';
     2323                        if (++freqs[idx] > ret_freq) {  // update on new max
     2324                          ret_freq = freqs[idx];
     2325                          ret_ch = ch;
     2326                        }
     2327                }
     2328        }
     2329        return [ret_freq, ret_ch];
     2330}
     2331\end{cfa}
     2332This approach provides the benefits of compile-time checking for appropriate return statements as in aggregation, but without the required verbosity of declaring a new named type, which precludes the bug seen with out-parameters.
     2333
     2334The addition of multiple-return-value functions necessitates a syntax for accepting multiple values at the call-site.
    23272335The simplest mechanism for retaining a return value in C is variable assignment.
    2328 By assigning the multiple return-values into multiple variables, the values can be retrieved later.
     2336By assigning the return value into a variable, its value can be retrieved later at any point in the program.
    23292337As such, \CFA allows assigning multiple values from a function into multiple variables, using a square-bracketed list of lvalue expressions on the left side.
    23302338\begin{cfa}
    2331 int quot, rem;
    2332 [ quot, rem ] = div( 13, 5 );                           §\C{// assign multiple variables}§
    2333 printf( "%d %d\n", quot, rem );                         §\C{// print quotient/remainder}\CRT§
    2334 \end{cfa}
    2335 Here, the multiple return-values are matched in much the same way as passing multiple return-values to multiple parameters in a call.
    2336 
    2337 
    2338 \subsection{Expressions}
    2339 
     2339const char * str = "hello world";
     2340int freq;
     2341char ch;
     2342[freq, ch] = most_frequent(str);  // assign into multiple variables
     2343printf("%s -- %d %c\n", str, freq, ch);
     2344\end{cfa}
     2345It is also common to use a function's output as the input to another function.
     2346\CFA also allows this case, without any new syntax.
     2347When a function call is passed as an argument to another call, the expression resolver attempts to find the best match of actual arguments to formal parameters given all of the possible expression interpretations in the current scope \cite{Bilson03}.
     2348For example,
     2349\begin{cfa}
     2350void process(int);       // (1)
     2351void process(char);      // (2)
     2352void process(int, char); // (3)
     2353void process(char, int); // (4)
     2354
     2355process(most_frequent("hello world"));  // selects (3)
     2356\end{cfa}
     2357In this case, there is only one option for a function named ©most_frequent© that takes a string as input.
     2358This function returns two values, one ©int© and one ©char©.
     2359There are four options for a function named ©process©, but only two that accept two arguments, and of those the best match is (3), which is also an exact match.
     2360This expression first calls ©most_frequent("hello world")©, which produces the values ©3© and ©'l'©, which are fed directly to the first and second parameters of (3), respectively.
     2361
     2362\section{Tuple Expressions}
    23402363Multiple-return-value functions provide \CFA with a new syntax for expressing a combination of expressions in the return statement and a combination of types in a function signature.
    2341 These notions are generalized to provide \CFA with \newterm{tuple expression}s and \newterm{tuple type}s.
     2364These notions can be generalized to provide \CFA with \emph{tuple expressions} and \emph{tuple types}.
    23422365A tuple expression is an expression producing a fixed-size, ordered list of values of heterogeneous types.
    2343 The type of a tuple expression is the tuple of the subexpression types, or a tuple type.
    2344 
     2366The type of a tuple expression is the tuple of the subexpression types, or a \emph{tuple type}.
    23452367In \CFA, a tuple expression is denoted by a comma-separated list of expressions enclosed in square brackets.
    23462368For example, the expression ©[5, 'x', 10.5]© has type ©[int, char, double]©.
     
    23492371The order of evaluation of the components in a tuple expression is unspecified, to allow a compiler the greatest flexibility for program optimization.
    23502372It is, however, guaranteed that each component of a tuple expression is evaluated for side-effects, even if the result is not used.
    2351 Multiple-return-value functions can equivalently be called \newterm{tuple-returning functions}.
    2352 
    2353 
    2354 \subsection{Variables}
    2355 
    2356 The previous call of ©div© still requires the preallocation of multiple return-variables in a manner similar to the aliasing example.
    2357 In \CFA, it is possible to overcome this restriction by declaring a \newterm{tuple variable}.
    2358 \begin{cfa}
    2359 [int, int] ®qr® = div( 13, 5 );                 §\C{// initialize tuple variable}§
    2360 printf( "%d %d\n", ®qr® );                              §\C{// print quotient/remainder}§
    2361 \end{cfa}
    2362 It is now possible to match the multiple return-values to a single variable, in much the same way as \Index{aggregation}.
    2363 As well, the components of the tuple value are passed as separate parameters to ©printf©, allowing direct printing of tuple variables.
    2364 One way to access the individual components of a tuple variable is with assignment.
    2365 \begin{cfa}
    2366 [ quot, rem ] = qr;                                             §\C{// assign multiple variables}§
    2367 \end{cfa}
    2368 
     2373Multiple-return-value functions can equivalently be called \emph{tuple-returning functions}.
     2374
     2375\subsection{Tuple Variables}
     2376The call-site of the ©most_frequent© routine has a notable blemish, in that it required the preallocation of return variables in a manner similar to the aliasing example, since it is impossible to declare multiple variables of different types in the same declaration in standard C.
     2377In \CFA, it is possible to overcome this restriction by declaring a \emph{tuple variable}.
     2378\begin{cfa}[emph=ret, emphstyle=\color{red}]
     2379const char * str = "hello world";
     2380[int, char] ret = most_frequent(str);  // initialize tuple variable
     2381printf("%s -- %d %c\n", str, ret);
     2382\end{cfa}
     2383It is now possible to accept multiple values into a single piece of storage, in much the same way that it was previously possible to pass multiple values from one function call to another.
     2384These variables can be used in any of the contexts where a tuple expression is allowed, such as in the ©printf© function call.
     2385As in the ©process© example, the components of the tuple value are passed as separate parameters to ©printf©, allowing very simple printing of tuple expressions.
     2386One way to access the individual components is with a simple assignment, as in previous examples.
     2387\begin{cfa}
     2388int freq;
     2389char ch;
     2390[freq, ch] = ret;
     2391\end{cfa}
     2392
     2393\begin{sloppypar}
    23692394In addition to variables of tuple type, it is also possible to have pointers to tuples, and arrays of tuples.
    23702395Tuple types can be composed of any types, except for array types, since array assignment is disallowed, which makes tuple assignment difficult when a tuple contains an array.
    23712396\begin{cfa}
    2372 [ double, int ] di;
    2373 [ double, int ] * pdi
    2374 [ double, int ] adi[10];
     2397[double, int] di;
     2398[double, int] * pdi
     2399[double, int] adi[10];
    23752400\end{cfa}
    23762401This examples declares a variable of type ©[double, int]©, a variable of type pointer to ©[double, int]©, and an array of ten ©[double, int]©.
    2377 
    2378 
    2379 \subsection{Indexing}
    2380 
    2381 It is also possible to access a single component of a tuple-valued expression without creating temporary variables.
    2382 Given a tuple-valued expression $e$np and a compile-time constant integer $i$ where $0 \leq i < n$, where $n$ is the number of components in $e$, $e.i$ accesses the $i^{\:th}$ component of $e$, \eg:
     2402\end{sloppypar}
     2403
     2404\subsection{Tuple Indexing}
     2405
     2406At times, it is desirable to access a single component of a tuple-valued expression without creating unnecessary temporary variables to assign to.
     2407Given a tuple-valued expression ©e© and a compile-time constant integer $i$ where $0 \leq i < n$, where $n$ is the number of components in ©e©, ©e.i© accesses the $i$\textsuperscript{th} component of ©e©.
     2408For example,
    23832409\begin{cfa}
    23842410[int, double] x;
     
    23912417p->0 = 5;                                                               §\C{// access int component of tuple pointed-to by p}§
    23922418g( x.1, x.0 );                                                  §\C{// rearrange x to pass to g}§
    2393 double z = [ x, f() ].0.1;                              §\C{// access second component of first component of tuple expression}§
    2394 \end{cfa}
    2395 Tuple-index expressions can occur on any tuple-typed expression, including tuple-returning functions, square-bracketed tuple expressions, and other tuple-index expressions, provided the retrieved component is also a tuple.
     2419double z = [x, f()].0.1;                                §\C{// access second component of first component of tuple expression}§
     2420\end{cfa}
     2421As seen above, tuple-index expressions can occur on any tuple-typed expression, including tuple-returning functions, square-bracketed tuple expressions, and other tuple-index expressions, provided the retrieved component is also a tuple.
    23962422This feature was proposed for \KWC but never implemented \cite[p.~45]{Till89}.
    23972423
    2398 
    23992424\subsection{Flattening and Structuring}
    2400 
    24012425As evident in previous examples, tuples in \CFA do not have a rigid structure.
    24022426In function call contexts, tuples support implicit flattening and restructuring conversions.
     
    24412465There is only a single definition of ©f©, and 3 arguments with only single interpretations.
    24422466First, the argument alternative list ©[5, 10.2], 4© is flattened to produce the argument list ©5, 10.2, 4©.
    2443 Next, the parameter matching algorithm begins, with $P =$© int© and $A =$© int©, which unifies exactly.
    2444 Moving to the next parameter and argument, $P =$© [double, int]© and $A =$© double©.
    2445 This time, the parameter is a tuple type, so the algorithm applies recursively with $P' =$© double© and $A =$© double©, which unifies exactly.
    2446 Then $P' =$© int© and $A =$© double©, which again unifies exactly.
     2467Next, the parameter matching algorithm begins, with $P = $©int© and $A = $©int©, which unifies exactly.
     2468Moving to the next parameter and argument, $P = $©[double, int]© and $A = $©double©.
     2469This time, the parameter is a tuple type, so the algorithm applies recursively with $P' = $©double© and $A = $©double©, which unifies exactly.
     2470Then $P' = $©int© and $A = $©double©, which again unifies exactly.
    24472471At this point, the end of $P'$ has been reached, so the arguments ©10.2, 4© are structured into the tuple expression ©[10.2, 4]©.
    24482472Finally, the end of the parameter list $P$ has also been reached, so the final expression is ©f(5, [10.2, 4])©.
    24492473
    2450 
    2451 \subsection{Assignment}
     2474\section{Tuple Assignment}
    24522475\label{s:TupleAssignment}
    2453 
    2454 An assignment where the left side of the assignment operator has a tuple type is called \newterm{tuple assignment}.
    2455 There are two kinds of tuple assignment depending on whether the right side of the assignment operator has a non-tuple or tuple type, called \newterm[mass assignment]{mass} and \newterm[multiple assignment]{multiple} assignment, respectively.
     2476An assignment where the left side of the assignment operator has a tuple type is called tuple assignment.
     2477There are two kinds of tuple assignment depending on whether the right side of the assignment operator has a tuple type or a non-tuple type, called \emph{Multiple} and \emph{Mass} Assignment, respectively.
    24562478\begin{cfa}
    24572479int x;
    24582480double y;
    24592481[int, double] z;
    2460 [y, x] = 3.14;                                                  §\C{// mass assignment}§
    2461 [x, y] = z;                                                         §\C{// multiple assignment}§
    2462 z = 10;                                                         §\C{// mass assignment}§
    2463 z = [x, y];                                                             §\C{// multiple assignment}§
     2482[y, x] = 3.14;  // mass assignment
     2483[x, y] = z;     // multiple assignment
     2484z = 10;         // mass assignment
     2485z = [x, y];     // multiple assignment
    24642486\end{cfa}
    24652487Let $L_i$ for $i$ in $[0, n)$ represent each component of the flattened left side, $R_i$ represent each component of the flattened right side of a multiple assignment, and $R$ represent the right side of a mass assignment.
     
    24682490For example, the following is invalid because the number of components on the left does not match the number of components on the right.
    24692491\begin{cfa}
    2470 [ int, int ] x, y, z;
    2471 [ x, y ] = z;                                              §\C{// multiple assignment, invalid 4 != 2}§
     2492[int, int] x, y, z;
     2493[x, y] = z;   // multiple assignment, invalid 4 != 2
    24722494\end{cfa}
    24732495Multiple assignment assigns $R_i$ to $L_i$ for each $i$.
     
    24852507\begin{cfa}
    24862508int x = 10, y = 20;
    2487 [ x, y ] = [ y, x ];
     2509[x, y] = [y, x];
    24882510\end{cfa}
    24892511After executing this code, ©x© has the value ©20© and ©y© has the value ©10©.
     
    25042526        int a, b;
    25052527        double c, d;
    2506         [ void ] f( [ int, int ] );
    2507         f( [ c, a ] = [ b, d ] = 1.5 );  // assignments in parameter list
     2528        [void] f([int, int]);
     2529        f([c, a] = [b, d] = 1.5);  // assignments in parameter list
    25082530\end{cfa}
    25092531The tuple expression begins with a mass assignment of ©1.5© into ©[b, d]©, which assigns ©1.5© into ©b©, which is truncated to ©1©, and ©1.5© into ©d©, producing the tuple ©[1, 1.5]© as a result.
     
    25112533Finally, the tuple ©[1, 1]© is used as an expression in the call to ©f©.
    25122534
    2513 
    2514 \subsection{Construction}
    2515 
     2535\subsection{Tuple Construction}
    25162536Tuple construction and destruction follow the same rules and semantics as tuple assignment, except that in the case where there is no right side, the default constructor or destructor is called on each component of the tuple.
    25172537As constructors and destructors did not exist in previous versions of \CFA or in \KWC, this is a primary contribution of this thesis to the design of tuples.
     
    25492569The initialization of ©s© with ©t© works by default because ©t© is flattened into its components, which satisfies the generated field constructor ©?{}(S *, int, double)© to initialize the first two values.
    25502570
    2551 
    2552 \subsection{Member-Access Expression}
     2571\section{Member-Access Tuple Expression}
    25532572\label{s:MemberAccessTuple}
    2554 
    2555 Tuples may be used to select multiple fields of a record by field name.
     2573It is possible to access multiple fields from a single expression using a \emph{Member-Access Tuple Expression}.
    25562574The result is a single tuple-valued expression whose type is the tuple of the types of the members.
    25572575For example,
    25582576\begin{cfa}
    2559 struct S { char x; int y; double z; } s;
     2577struct S { int x; double y; char * z; } s;
    25602578s.[x, y, z];
    25612579\end{cfa}
    2562 Here, the type of ©s.[ x, y, z ]© is ©[ char, int, double ]©.
    2563 A member tuple expression has the form \emph{e}©.[x, y, z];© where \emph{e} is an expression with type ©T©, where ©T© supports member access expressions, and ©x, y, z© are all members of ©T© with types ©T$_x$©, ©T$_y$©, and ©T$_z$© respectively.
    2564 Then the type of \emph{e}©.[x, y, z]© is ©[T$_x$, T$_y$, T$_z$]©.
    2565 
    2566 A member-access tuple may be used anywhere a tuple can be used, \eg:
    2567 \begin{cfa}
    2568 s.[ y, z, x ] = [ 3, 3.2, 'x' ];                §\C{// equivalent to s.x = 'x', s.y = 3, s.z = 3.2}§
    2569 f( s.[ y, z ] );                                                §\C{// equivalent to f( s.y, s.z )}§
    2570 \end{cfa}
    2571 Note, the fields appearing in a record-field tuple may be specified in any order;
    2572 also, it is unnecessary to specify all the fields of a struct in a multiple record-field tuple.
    2573 
    2574 Since tuple-index expressions are a form of member-access expression, it is possible to use tuple-index expressions in conjunction with member-access expressions to restructure a tuple (\eg, rearrange components, drop components, duplicate components, etc.).
    2575 \begin{cfa}
    2576 [ int, int, long, double ] x;
    2577 void f( double, long );
    2578 
    2579 f( x.[ 0, 3 ] );                                                §\C{// f( x.0, x.3 )}§
    2580 x.[ 0, 1 ] = x.[ 1, 0 ];                                §\C{// [ x.0, x.1 ] = [ x.1, x.0 ]}§
    2581 [ long, int, long ] y = x.[ 2, 0, 2 ];
    2582 \end{cfa}
    2583 
    2584 It is possible for a member tuple expression to contain other member access expressions, \eg:
     2580Here, the type of ©s.[x, y, z]© is ©[int, double, char *]©.
     2581A member tuple expression has the form ©a.[x, y, z];© where ©a© is an expression with type ©T©, where ©T© supports member access expressions, and ©x, y, z© are all members of ©T© with types ©T$_x$©, ©T$_y$©, and ©T$_z$© respectively.
     2582Then the type of ©a.[x, y, z]© is ©[T_x, T_y, T_z]©.
     2583
     2584Since tuple index expressions are a form of member-access expression, it is possible to use tuple-index expressions in conjunction with member tuple expressions to manually restructure a tuple (\eg, rearrange components, drop components, duplicate components, etc.).
     2585\begin{cfa}
     2586[int, int, long, double] x;
     2587void f(double, long);
     2588
     2589f(x.[0, 3]);          // f(x.0, x.3)
     2590x.[0, 1] = x.[1, 0];  // [x.0, x.1] = [x.1, x.0]
     2591[long, int, long] y = x.[2, 0, 2];
     2592\end{cfa}
     2593
     2594It is possible for a member tuple expression to contain other member access expressions.
     2595For example,
    25852596\begin{cfa}
    25862597struct A { double i; int j; };
    25872598struct B { int * k; short l; };
    25882599struct C { int x; A y; B z; } v;
    2589 v.[ x, y.[ i, j ], z.k ];
    2590 \end{cfa}
    2591 This expression is equivalent to ©[ v.x, [ v.y.i, v.y.j ], v.z.k ]©.
    2592 That is, the aggregate expression is effectively distributed across the tuple allowing simple and easy access to multiple components in an aggregate without repetition.
     2600v.[x, y.[i, j], z.k];
     2601\end{cfa}
     2602This expression is equivalent to ©[v.x, [v.y.i, v.y.j], v.z.k]©.
     2603That is, the aggregate expression is effectively distributed across the tuple, which allows simple and easy access to multiple components in an aggregate, without repetition.
    25932604It is guaranteed that the aggregate expression to the left of the ©.© in a member tuple expression is evaluated exactly once.
    2594 As such, it is safe to use member tuple expressions on the result of a function with side-effects.
    2595 \begin{cfa}
    2596 [ int, float, double ] f();
    2597 [ double, float ] x = f().[ 2, 1 ];             §\C{// f() called once}§
     2605As such, it is safe to use member tuple expressions on the result of a side-effecting function.
     2606\begin{cfa}
     2607[int, float, double] f();
     2608[double, float] x = f().[2, 1];
    25982609\end{cfa}
    25992610
     
    26012612Since \CFA permits these tuple-access expressions using structures, unions, and tuples, \emph{member tuple expression} or \emph{field tuple expression} is more appropriate.
    26022613
    2603 
    2604 \subsection{Casting}
    2605 
     2614It is possible to extend member-access expressions further.
     2615Currently, a member-access expression whose member is a name requires that the aggregate is a structure or union, while a constant integer member requires the aggregate to be a tuple.
     2616In the interest of orthogonal design, \CFA could apply some meaning to the remaining combinations as well.
     2617For example,
     2618\begin{cfa}
     2619struct S { int x, y; } s;
     2620[S, S] z;
     2621
     2622s.x;  // access member
     2623z.0;  // access component
     2624
     2625s.1;  // ???
     2626z.y;  // ???
     2627\end{cfa}
     2628One possibility is for ©s.1© to select the second member of ©s©.
     2629Under this interpretation, it becomes possible to not only access members of a struct by name, but also by position.
     2630Likewise, it seems natural to open this mechanism to enumerations as well, wherein the left side would be a type, rather than an expression.
     2631One benefit of this interpretation is familiarity, since it is extremely reminiscent of tuple-index expressions.
     2632On the other hand, it could be argued that this interpretation is brittle in that changing the order of members or adding new members to a structure becomes a brittle operation.
     2633This problem is less of a concern with tuples, since modifying a tuple affects only the code that directly uses the tuple, whereas modifying a structure has far reaching consequences for every instance of the structure.
     2634
     2635As for ©z.y©, one interpretation is to extend the meaning of member tuple expressions.
     2636That is, currently the tuple must occur as the member, \ie to the right of the dot.
     2637Allowing tuples to the left of the dot could distribute the member across the elements of the tuple, in much the same way that member tuple expressions distribute the aggregate across the member tuple.
     2638In this example, ©z.y© expands to ©[z.0.y, z.1.y]©, allowing what is effectively a very limited compile-time field-sections map operation, where the argument must be a tuple containing only aggregates having a member named ©y©.
     2639It is questionable how useful this would actually be in practice, since structures often do not have names in common with other structures, and further this could cause maintainability issues in that it encourages programmers to adopt very simple naming conventions to maximize the amount of overlap between different types.
     2640Perhaps more useful would be to allow arrays on the left side of the dot, which would likewise allow mapping a field access across the entire array, producing an array of the contained fields.
     2641The immediate problem with this idea is that C arrays do not carry around their size, which would make it impossible to use this extension for anything other than a simple stack allocated array.
     2642
     2643Supposing this feature works as described, it would be necessary to specify an ordering for the expansion of member-access expressions versus member-tuple expressions.
     2644\begin{cfa}
     2645struct { int x, y; };
     2646[S, S] z;
     2647z.[x, y];  // ???
     2648// => [z.0, z.1].[x, y]
     2649// => [z.0.x, z.0.y, z.1.x, z.1.y]
     2650// or
     2651// => [z.x, z.y]
     2652// => [[z.0, z.1].x, [z.0, z.1].y]
     2653// => [z.0.x, z.1.x, z.0.y, z.1.y]
     2654\end{cfa}
     2655Depending on exactly how the two tuples are combined, different results can be achieved.
     2656As such, a specific ordering would need to be imposed to make this feature useful.
     2657Furthermore, this addition moves a member-tuple expression's meaning from being clear statically to needing resolver support, since the member name needs to be distributed appropriately over each member of the tuple, which could itself be a tuple.
     2658
     2659A second possibility is for \CFA to have named tuples, as they exist in Swift and D.
     2660\begin{cfa}
     2661typedef [int x, int y] Point2D;
     2662Point2D p1, p2;
     2663p1.x + p1.y + p2.x + p2.y;
     2664p1.0 + p1.1 + p2.0 + p2.1;  // equivalent
     2665\end{cfa}
     2666In this simpler interpretation, a tuple type carries with it a list of possibly empty identifiers.
     2667This approach fits naturally with the named return-value feature, and would likely go a long way towards implementing it.
     2668
     2669Ultimately, the first two extensions introduce complexity into the model, with relatively little perceived benefit, and so were dropped from consideration.
     2670Named tuples are a potentially useful addition to the language, provided they can be parsed with a reasonable syntax.
     2671
     2672
     2673\section{Casting}
    26062674In C, the cast operator is used to explicitly convert between types.
    26072675In \CFA, the cast operator has a secondary use, which is type ascription, since it forces the expression resolution algorithm to choose the lowest cost conversion to the target type.
     
    26572725That is, it is invalid to cast ©[int, int]© to ©[int, int, int]©.
    26582726
    2659 
    2660 \subsection{Polymorphism}
    2661 
     2727\section{Polymorphism}
    26622728Due to the implicit flattening and structuring conversions involved in argument passing, ©otype© and ©dtype© parameters are restricted to matching only with non-tuple types.
    26632729The integration of polymorphism, type assertions, and monomorphic specialization of tuple-assertions are a primary contribution of this thesis to the design of tuples.
     
    27122778Until this point, it has been assumed that assertion arguments must match the parameter type exactly, modulo polymorphic specialization (\ie, no implicit conversions are applied to assertion arguments).
    27132779This decision presents a conflict with the flexibility of tuples.
    2714 
    2715 
    2716 \subsubsection{Assertion Inference}
    2717 
     2780\subsection{Assertion Inference}
    27182781\begin{cfa}
    27192782int f([int, double], double);
     
    28392902Unfortunately, C's syntax for subscripts precluded treating them as tuples.
    28402903The C subscript list has the form ©[i][j]...© and not ©[i, j, ...]©.
    2841 Therefore, there is no syntactic way for a routine returning multiple values to specify the different subscript values, \eg ©f[ g() ]© always means a single subscript value because there is only one set of brackets.
     2904Therefore, there is no syntactic way for a routine returning multiple values to specify the different subscript values, \eg ©f[g()]© always means a single subscript value because there is only one set of brackets.
    28422905Fixing this requires a major change to C because the syntactic form ©M[i, j, k]© already has a particular meaning: ©i, j, k© is a comma expression.
    28432906\end{rationale}
     
    28882951
    28892952
    2890 \subsection{Mass Assignment}
     2953\section{Mass Assignment}
    28912954
    28922955\CFA permits assignment to several variables at once using mass assignment~\cite{CLU}.
     
    29282991
    29292992
    2930 \subsection{Multiple Assignment}
     2993\section{Multiple Assignment}
    29312994
    29322995\CFA also supports the assignment of several values at once, known as multiple assignment~\cite{CLU,Galletly96}.
     
    29693032
    29703033
    2971 \subsection{Cascade Assignment}
     3034\section{Cascade Assignment}
    29723035
    29733036As in C, \CFA mass and multiple assignments can be cascaded, producing cascade assignment.
     
    29853048\end{cfa}
    29863049As in C, the rightmost assignment is performed first, \ie assignment parses right to left.
     3050
     3051
     3052\section{Field Tuples}
     3053
     3054Tuples may be used to select multiple fields of a record by field name.
     3055Its general form is:
     3056\begin{cfa}
     3057§\emph{expr}§ . [ §\emph{fieldlist}§ ]
     3058§\emph{expr}§ -> [ §\emph{fieldlist}§ ]
     3059\end{cfa}
     3060\emph{expr} is any expression yielding a value of type record, \eg ©struct©, ©union©.
     3061Each element of \emph{ fieldlist} is an element of the record specified by \emph{expr}.
     3062A record-field tuple may be used anywhere a tuple can be used. An example of the use of a record-field tuple is
     3063the following:
     3064\begin{cfa}
     3065struct s {
     3066        int f1, f2;
     3067        char f3;
     3068        double f4;
     3069} v;
     3070v.[ f3, f1, f2 ] = ['x', 11, 17 ];      §\C{// equivalent to v.f3 = 'x', v.f1 = 11, v.f2 = 17}§
     3071f( v.[ f3, f1, f2 ] );                          §\C{// equivalent to f( v.f3, v.f1, v.f2 )}§
     3072\end{cfa}
     3073Note, the fields appearing in a record-field tuple may be specified in any order;
     3074also, it is unnecessary to specify all the fields of a struct in a multiple record-field tuple.
     3075
     3076If a field of a ©struct© is itself another ©struct©, multiple fields of this subrecord can be specified using a nested record-field tuple, as in the following example:
     3077\begin{cfa}
     3078struct inner {
     3079        int f2, f3;
     3080};
     3081struct outer {
     3082        int f1;
     3083        struct inner i;
     3084        double f4;
     3085} o;
     3086
     3087o.[ f1, i.[ f2, f3 ], f4 ] = [ 11, 12, 13, 3.14159 ];
     3088\end{cfa}
    29873089
    29883090
  • src/Concurrency/Waitfor.cc

    r9c35431 rc6e2c18  
    416416                                makeAccStatement( acceptables, index, "is_dtor", detectIsDtor( clause.target.function )                                    , indexer ),
    417417                                makeAccStatement( acceptables, index, "func"   , new CastExpr( clause.target.function, fptr_t )                            , indexer ),
    418                                 makeAccStatement( acceptables, index, "data"   , new VariableExpr( monitors )                                              , indexer ),
     418                                makeAccStatement( acceptables, index, "list"   , new VariableExpr( monitors )                                              , indexer ),
    419419                                makeAccStatement( acceptables, index, "size"   , new ConstantExpr( Constant::from_ulong( clause.target.arguments.size() ) ), indexer ),
    420420                                setter->clone()
  • src/GenPoly/InstantiateGeneric.cc

    r9c35431 rc6e2c18  
    2121#include <vector>                      // for vector
    2222
    23 #include "CodeGen/OperatorTable.h"
    2423#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
    2524#include "Common/ScopedMap.h"          // for ScopedMap
     
    2827#include "Common/utility.h"            // for deleteAll, cloneAll
    2928#include "GenPoly.h"                   // for isPolyType, typesPolyCompatible
    30 #include "InitTweak/InitTweak.h"
    3129#include "ResolvExpr/typeops.h"
    3230#include "ScopedSet.h"                 // for ScopedSet, ScopedSet<>::iterator
     
    156154
    157155        /// Add cast to dtype-static member expressions so that type information is not lost in GenericInstantiator
    158         struct FixDtypeStatic final : public WithGuards, public WithVisitorRef<FixDtypeStatic>, public WithShortCircuiting, public WithStmtsToAdd {
     156        struct FixDtypeStatic final {
    159157                Expression * postmutate( MemberExpr * memberExpr );
    160 
    161                 void premutate( ApplicationExpr * appExpr );
    162                 void premutate( AddressExpr * addrExpr );
    163158
    164159                template<typename AggrInst>
    165160                Expression * fixMemberExpr( AggrInst * inst, MemberExpr * memberExpr );
    166 
    167                 bool isLvalueArg = false;
    168161        };
    169162
     
    508501                if ( isDtypeStatic( baseParams ) ) {
    509502                        if ( ! ResolvExpr::typesCompatible( memberExpr->result, memberExpr->member->get_type(), SymTab::Indexer() ) ) {
    510                                 // type of member and type of expression differ
    511                                 Type * concType = memberExpr->result->clone();
    512                                 if ( isLvalueArg ) {
    513                                         // result must be C lvalue, so make a new reference variable with the correct actual type to replace the member expression
    514                                         //   forall(dtype T)
    515                                         //   struct Ptr {
    516                                         //     T * x
    517                                         //   };
    518                                         //   Ptr(int) p;
    519                                         //   int i;
    520                                         //   p.x = &i;
    521                                         // becomes
    522                                         //   int *& _dtype_static_member_0 = (int **)&p.x;
    523                                         //   _dtype_static_member_0 = &i;
    524                                         // Note: this currently creates more temporaries than is strictly necessary, since it does not check for duplicate uses of the same member expression.
    525                                         static UniqueName tmpNamer( "_dtype_static_member_" );
    526                                         Expression * init = new CastExpr( new AddressExpr( memberExpr ), new PointerType( Type::Qualifiers(), concType->clone() ) );
    527                                         ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), new ReferenceType( Type::Qualifiers(), concType ), new SingleInit( init ) );
    528                                         stmtsToAddBefore.push_back( new DeclStmt( noLabels, tmp ) );
    529                                         return new VariableExpr( tmp );
    530                                 } else {
    531                                         // can simply add a cast to actual type
    532                                         return new CastExpr( memberExpr, concType );
    533                                 }
     503                                // type of member and type of expression differ, so add cast to actual type
     504                                return new CastExpr( memberExpr, memberExpr->result->clone() );
    534505                        }
    535506                }
     
    549520        }
    550521
    551         void FixDtypeStatic::premutate( ApplicationExpr * appExpr ) {
    552                 GuardValue( isLvalueArg );
    553                 isLvalueArg = false;
    554                 DeclarationWithType * function = InitTweak::getFunction( appExpr );
    555                 if ( function->linkage == LinkageSpec::Intrinsic && CodeGen::isAssignment( function->name ) ) {
    556                         // explicitly visit children because only the first argument must be a C lvalue.
    557                         visit_children = false;
    558                         appExpr->env = maybeMutate( appExpr->env, *visitor );
    559                         appExpr->result = maybeMutate( appExpr->result, *visitor );
    560                         appExpr->function = maybeMutate( appExpr->function, *visitor );
    561                         isLvalueArg = true;
    562                         for ( Expression * arg : appExpr->args ) {
    563                                 arg = maybeMutate( arg, *visitor );
    564                                 isLvalueArg = false;
    565                         }
    566                 }
    567         }
    568 
    569         void FixDtypeStatic::premutate( AddressExpr * ) {
    570                 // argument of & must be C lvalue
    571                 GuardValue( isLvalueArg );
    572                 isLvalueArg = true;
    573         }
    574522} // namespace GenPoly
    575523
  • src/Parser/ParseNode.h

    r9c35431 rc6e2c18  
    1010// Created On       : Sat May 16 13:28:16 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Nov 27 17:33:35 2017
    13 // Update Count     : 824
     12// Last Modified On : Sat Sep 23 18:11:22 2017
     13// Update Count     : 821
    1414//
    1515
     
    292292        DeclarationNode * set_extension( bool exten ) { extension = exten; return this; }
    293293  public:
    294         DeclarationNode * get_last() { return (DeclarationNode *)ParseNode::get_last(); }
    295 
    296294        struct Variable_t {
    297295//              const std::string * name;
  • src/Parser/parser.yy

    r9c35431 rc6e2c18  
    1010// Created On       : Sat Sep  1 20:22:55 2001
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Nov 27 17:23:35 2017
    13 // Update Count     : 2992
     12// Last Modified On : Sun Nov 26 11:36:36 2017
     13// Update Count     : 2969
    1414//
    1515
     
    13641364                        $$ = $3->addQualifiers( $1 )->addQualifiers( $2 );
    13651365                }
    1366         | cfa_function_declaration pop ',' push identifier_or_type_name '(' push cfa_parameter_type_list_opt pop ')'
    1367                 {
    1368                         // Append the return type at the start (left-hand-side) to each identifier in the list.
    1369                         DeclarationNode * ret = new DeclarationNode;
    1370                         ret->type = maybeClone( $1->type->base );
    1371                         $$ = $1->appendList( DeclarationNode::newFunction( $5, ret, $8, nullptr, true ) );
     1366        | cfa_function_declaration pop ',' push identifier_or_type_name
     1367                {
     1368                        typedefTable.addToEnclosingScope( *$5, TypedefTable::ID );
     1369                        $$ = $1->appendList( $1->cloneType( $5 ) );
    13721370                }
    13731371        ;
     
    24182416                        typedefTable.addToEnclosingScope( TypedefTable::ID );
    24192417                        typedefTable.leaveScope();
    2420                         // Add the function body to the last identifier in the function definition list, i.e., foo3:
    2421                         //   [const double] foo1(), foo2( int ), foo3( double ) { return 3.0; }
    2422                         $1->get_last()->addFunctionBody( $3 );
    2423                         $$ = $1;
     2418                        $$ = $1->addFunctionBody( $3 );
    24242419                }
    24252420        | declaration_specifier function_declarator with_clause_opt compound_statement
  • src/ResolvExpr/AlternativeFinder.cc

    r9c35431 rc6e2c18  
    897897                // sum cost and accumulate actuals
    898898                std::list<Expression*>& args = appExpr->get_args();
    899                 Cost cost = func.cost;
     899                Cost cost = Cost::zero;
    900900                const ArgPack* pack = &result;
    901901                while ( pack->expr ) {
  • src/SynTree/Expression.cc

    r9c35431 rc6e2c18  
    356356        Type * res = member->get_type()->clone();
    357357        sub.apply( res );
    358         result = res;
    359         result->set_lvalue( true );
    360         result->get_qualifiers() |= aggregate->result->get_qualifiers();
     358        set_result( res );
     359        get_result()->set_lvalue( true );
    361360}
    362361
  • src/benchmark/Makefile.am

    r9c35431 rc6e2c18  
    9494        ctxswitch-cfa_thread.run        \
    9595        ctxswitch-upp_coroutine.run     \
    96         ctxswitch-upp_thread.run        \
    97         ctxswitch-goroutine.run         \
    98         ctxswitch-java_thread.run
     96        ctxswitch-upp_thread.run
    9997
    10098ctxswitch-cfa_coroutine$(EXEEXT):
     
    113111        @@BACKEND_CC@ ctxswitch/pthreads.c  -DBENCH_N=50000000  -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    114112
    115 ctxswitch-goroutine$(EXEEXT):
    116         @go build -o a.out ctxswitch/goroutine.go
    117 
    118 ctxswitch-java_thread$(EXEEXT):
    119         @javac ctxswitch/JavaThread.java
    120         @echo "#!/bin/sh" > a.out
    121         @echo "cd ctxswitch && java JavaThread" >> a.out
    122         @chmod a+x a.out
    123 
    124113## =========================================================================================================
    125114mutex$(EXEEXT) :\
    126115        mutex-function.run      \
    127         mutex-fetch_add.run     \
    128116        mutex-pthread_lock.run  \
    129117        mutex-upp.run           \
    130118        mutex-cfa1.run          \
    131119        mutex-cfa2.run          \
    132         mutex-cfa4.run          \
    133         mutex-java_thread.run
     120        mutex-cfa4.run
    134121
    135122mutex-function$(EXEEXT):
    136123        @@BACKEND_CC@ mutex/function.c    -DBENCH_N=500000000   -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    137124
    138 mutex-fetch_add$(EXEEXT):
    139         @@BACKEND_CC@ mutex/fetch_add.c   -DBENCH_N=500000000   -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    140 
    141125mutex-pthread_lock$(EXEEXT):
    142126        @@BACKEND_CC@ mutex/pthreads.c    -DBENCH_N=50000000    -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
     
    153137mutex-cfa4$(EXEEXT):
    154138        @${CC}        mutex/cfa4.c        -DBENCH_N=5000000     -I. -nodebug -lrt -quiet @CFA_FLAGS@ ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    155 
    156 mutex-java_thread$(EXEEXT):
    157         @javac mutex/JavaThread.java
    158         @echo "#!/bin/sh" > a.out
    159         @echo "cd mutex && java JavaThread" >> a.out
    160         @chmod a+x a.out
    161139
    162140## =========================================================================================================
     
    165143        signal-cfa1.run         \
    166144        signal-cfa2.run         \
    167         signal-cfa4.run         \
    168         signal-java_thread.run
     145        signal-cfa4.run
    169146
    170147signal-upp$(EXEEXT):
     
    179156signal-cfa4$(EXEEXT):
    180157        @${CC}        schedint/cfa4.c     -DBENCH_N=500000      -I. -nodebug -lrt -quiet @CFA_FLAGS@ ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    181 
    182 signal-java_thread$(EXEEXT):
    183         @javac schedint/JavaThread.java
    184         @echo "#!/bin/sh" > a.out
    185         @echo "cd schedint && java JavaThread" >> a.out
    186         @chmod a+x a.out
    187 
    188158
    189159## =========================================================================================================
     
    213183        creation-cfa_thread.run                 \
    214184        creation-upp_coroutine.run              \
    215         creation-upp_thread.run                 \
    216         creation-goroutine.run                  \
    217         creation-java_thread.run
     185        creation-upp_thread.run
    218186
    219187creation-cfa_coroutine$(EXEEXT):
     
    234202creation-pthread$(EXEEXT):
    235203        @@BACKEND_CC@ creation/pthreads.c  -DBENCH_N=250000     -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    236 
    237 creation-goroutine$(EXEEXT):
    238         @go build -o a.out creation/goroutine.go
    239 
    240 creation-java_thread$(EXEEXT):
    241         @javac creation/JavaThread.java
    242         @echo "#!/bin/sh" > a.out
    243         @echo "cd creation && java JavaThread" >> a.out
    244         @chmod a+x a.out
    245204
    246205## =========================================================================================================
  • src/benchmark/Makefile.in

    r9c35431 rc6e2c18  
    507507        ctxswitch-cfa_thread.run        \
    508508        ctxswitch-upp_coroutine.run     \
    509         ctxswitch-upp_thread.run        \
    510         ctxswitch-goroutine.run         \
    511         ctxswitch-java_thread.run
     509        ctxswitch-upp_thread.run
    512510
    513511ctxswitch-cfa_coroutine$(EXEEXT):
     
    526524        @@BACKEND_CC@ ctxswitch/pthreads.c  -DBENCH_N=50000000  -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    527525
    528 ctxswitch-goroutine$(EXEEXT):
    529         @go build -o a.out ctxswitch/goroutine.go
    530 
    531 ctxswitch-java_thread$(EXEEXT):
    532         @javac ctxswitch/JavaThread.java
    533         @echo "#!/bin/sh" > a.out
    534         @echo "cd ctxswitch && java JavaThread" >> a.out
    535         @chmod a+x a.out
    536 
    537526mutex$(EXEEXT) :\
    538527        mutex-function.run      \
    539         mutex-fetch_add.run     \
    540528        mutex-pthread_lock.run  \
    541529        mutex-upp.run           \
    542530        mutex-cfa1.run          \
    543531        mutex-cfa2.run          \
    544         mutex-cfa4.run          \
    545         mutex-java_thread.run
     532        mutex-cfa4.run
    546533
    547534mutex-function$(EXEEXT):
    548535        @@BACKEND_CC@ mutex/function.c    -DBENCH_N=500000000   -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    549536
    550 mutex-fetch_add$(EXEEXT):
    551         @@BACKEND_CC@ mutex/fetch_add.c   -DBENCH_N=500000000   -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    552 
    553537mutex-pthread_lock$(EXEEXT):
    554538        @@BACKEND_CC@ mutex/pthreads.c    -DBENCH_N=50000000    -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
     
    565549mutex-cfa4$(EXEEXT):
    566550        @${CC}        mutex/cfa4.c        -DBENCH_N=5000000     -I. -nodebug -lrt -quiet @CFA_FLAGS@ ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    567 
    568 mutex-java_thread$(EXEEXT):
    569         @javac mutex/JavaThread.java
    570         @echo "#!/bin/sh" > a.out
    571         @echo "cd mutex && java JavaThread" >> a.out
    572         @chmod a+x a.out
    573551
    574552signal$(EXEEXT) :\
     
    589567signal-cfa4$(EXEEXT):
    590568        @${CC}        schedint/cfa4.c     -DBENCH_N=500000      -I. -nodebug -lrt -quiet @CFA_FLAGS@ ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    591 
    592 signal-java_thread$(EXEEXT):
    593         @javac schedint/JavaThread.java
    594         @echo "#!/bin/sh" > a.out
    595         @echo "cd schedint && java JavaThread" >> a.out
    596         @chmod a+x a.out
    597569
    598570waitfor$(EXEEXT) :\
     
    620592        creation-cfa_thread.run                 \
    621593        creation-upp_coroutine.run              \
    622         creation-upp_thread.run                 \
    623         creation-goroutine.run                  \
    624         creation-java_thread.run
     594        creation-upp_thread.run
    625595
    626596creation-cfa_coroutine$(EXEEXT):
     
    641611creation-pthread$(EXEEXT):
    642612        @@BACKEND_CC@ creation/pthreads.c  -DBENCH_N=250000     -I. -lrt -pthread                    ${AM_CFLAGS} ${CFLAGS} ${ccflags}
    643 
    644 creation-goroutine$(EXEEXT):
    645         @go build -o a.out creation/goroutine.go
    646 
    647 creation-java_thread$(EXEEXT):
    648         @javac creation/JavaThread.java
    649         @echo "#!/bin/sh" > a.out
    650         @echo "cd creation && java JavaThread" >> a.out
    651         @chmod a+x a.out
    652613
    653614compile$(EXEEXT) :\
  • src/benchmark/bench.h

    r9c35431 rc6e2c18  
    11#pragma once
    22
    3 #if defined(__cforall)
     3#if defined(__CFORALL__)
    44extern "C" {
    55#endif
     
    88        #include <sys/times.h>                                  // times
    99        #include <time.h>
    10 #if defined(__cforall)
     10#if defined(__CFORALL__)
    1111}
    1212#endif
  • src/libcfa/Makefile.am

    r9c35431 rc6e2c18  
    100100        math                            \
    101101        gmp                             \
    102         bits/containers.h               \
    103102        bits/defs.h             \
    104103        bits/locks.h            \
  • src/libcfa/Makefile.in

    r9c35431 rc6e2c18  
    264264        containers/result containers/vector concurrency/coroutine \
    265265        concurrency/thread concurrency/kernel concurrency/monitor \
    266         ${shell echo stdhdr/*} math gmp bits/containers.h bits/defs.h \
    267         bits/locks.h concurrency/invoke.h libhdr.h libhdr/libalign.h \
     266        ${shell echo stdhdr/*} math gmp bits/defs.h bits/locks.h \
     267        concurrency/invoke.h libhdr.h libhdr/libalign.h \
    268268        libhdr/libdebug.h libhdr/libtools.h
    269269HEADERS = $(nobase_cfa_include_HEADERS)
     
    437437        math                            \
    438438        gmp                             \
    439         bits/containers.h               \
    440439        bits/defs.h             \
    441440        bits/locks.h            \
  • src/libcfa/bits/containers.h

    r9c35431 rc6e2c18  
    1515#pragma once
    1616
    17 #include "bits/defs.h"
     17#include <stddef.h>
     18
    1819#include "libhdr.h"
    19 
    20 //-----------------------------------------------------------------------------
    21 // Array
    22 //-----------------------------------------------------------------------------
    23 
    24 #ifdef __cforall
    25         forall(dtype T)
    26 #else
    27         #define T void
    28 #endif
    29 struct __small_array {
    30         T *           data;
    31         __lock_size_t size;
    32 };
    33 #undef T
    34 
    35 #ifdef __cforall
    36         #define __small_array_t(T) __small_array(T)
    37 #else
    38         #define __small_array_t(T) struct __small_array
    39 #endif
    40 
    41 #ifdef __cforall
    42         // forall(otype T | sized(T))
    43         // static inline void ?{}(__small_array(T) & this) {}
    44 
    45         forall(dtype T | sized(T))
    46         static inline T& ?[?]( __small_array(T) & this, __lock_size_t idx) {
    47                 return ((typeof(this.data))this.data)[idx];
    48         }
    49 
    50         forall(dtype T | sized(T))
    51         static inline T& ?[?]( const __small_array(T) & this, __lock_size_t idx) {
    52                 return ((typeof(this.data))this.data)[idx];
    53         }
    54 
    55         forall(dtype T | sized(T))
    56         static inline T* begin( const __small_array(T) & this ) {
    57                 return ((typeof(this.data))this.data);
    58         }
    59 
    60         forall(dtype T | sized(T))
    61         static inline T* end( const __small_array(T) & this ) {
    62                 return ((typeof(this.data))this.data) + this.size;
    63         }
    64 #endif
    6520
    6621//-----------------------------------------------------------------------------
     
    6823//-----------------------------------------------------------------------------
    6924
    70 #ifdef __cforall
     25#ifdef __CFORALL__
    7126        trait is_node(dtype T) {
    7227                T*& get_next( T& );
     
    7732// Stack
    7833//-----------------------------------------------------------------------------
    79 #ifdef __cforall
     34#ifdef __CFORALL__
    8035        forall(dtype TYPE | is_node(TYPE))
    8136        #define T TYPE
     
    8641        T * top;
    8742};
    88 #undef T
    8943
    90 #ifdef __cforall
     44#ifdef __CFORALL__
    9145#define __stack_t(T) __stack(T)
    9246#else
     
    9448#endif
    9549
    96 #ifdef __cforall
     50#ifdef __CFORALL__
    9751        forall(dtype T | is_node(T))
    98         static inline void ?{}( __stack(T) & this ) {
    99                 (this.top){ NULL };
     52        void ?{}( __stack(T) & this ) {
     53                this.top = NULL;
    10054        }
    10155
    10256        forall(dtype T | is_node(T) | sized(T))
    103         static inline void push( __stack(T) & this, T * val ) {
     57        void push( __stack(T) & this, T * val ) {
    10458                verify( !get_next( *val ) );
    10559                get_next( *val ) = this.top;
     
    10862
    10963        forall(dtype T | is_node(T) | sized(T))
    110         static inline T * pop( __stack(T) & this ) {
     64        T * pop( __stack(T) & this ) {
    11165                T * top = this.top;
    11266                if( top ) {
     
    12175// Queue
    12276//-----------------------------------------------------------------------------
    123 #ifdef __cforall
    124         forall(dtype TYPE | is_node(TYPE))
     77#ifdef __CFORALL__
     78        forall(dtype T | is_node(T))
    12579        #define T TYPE
    12680#else
     
    13185        T ** tail;
    13286};
    133 #undef T
    13487
    135 #ifdef __cforall
    136 #define __queue_t(T) __queue(T)
    137 #else
    138 #define __queue_t(T) struct __queue
    139 #endif
    140 
    141 #ifdef __cforall
     88#ifdef __CFORALL__
    14289        forall(dtype T | is_node(T))
    143         static inline void ?{}( __queue(T) & this ) {
    144                 (this.head){ NULL };
    145                 (this.tail){ &this.head };
     90        void ?{}( __queue(T) & this ) {
     91                this.head = NULL;
     92                this.tail = &this.head;
    14693        }
    14794
    14895        forall(dtype T | is_node(T) | sized(T))
    149         static inline void append( __queue(T) & this, T * val ) {
     96        void append( __queue(T) & this, T * val ) {
    15097                verify(this.tail != NULL);
    15198                *this.tail = val;
     
    154101
    155102        forall(dtype T | is_node(T) | sized(T))
    156         static inline T * pop_head( __queue(T) & this ) {
     103        T * pop_head( __queue(T) & this ) {
    157104                T * head = this.head;
    158105                if( head ) {
     
    167114
    168115        forall(dtype T | is_node(T) | sized(T))
    169         static inline T * remove( __queue(T) & this, T ** it ) {
     116        T * remove( __queue(T) & this, T ** it ) {
    170117                T * val = *it;
    171118                verify( val );
  • src/libcfa/bits/defs.h

    r9c35431 rc6e2c18  
    1717
    1818#include <stdbool.h>
    19 #include <stddef.h>
    2019#include <stdint.h>
    2120
     
    2322#define likely  (x)    __builtin_expect(!!(x), 1)
    2423#define thread_local _Thread_local
    25 
    26 typedef void (*fptr_t)();
    27 typedef int_fast16_t __lock_size_t;
    28 
    29 #ifdef __cforall
    30 #define __cfa_anonymous_object
    31 #else
    32 #define __cfa_anonymous_object __cfa_anonymous_object
    33 #endif
  • src/libcfa/bits/locks.h

    r9c35431 rc6e2c18  
    5656} __ALIGN__;
    5757
    58 #ifdef __cforall
     58#ifdef __CFORALL__
    5959        extern void yield( unsigned int );
    6060        extern thread_local struct thread_desc *    volatile this_thread;
  • src/libcfa/concurrency/invoke.h

    r9c35431 rc6e2c18  
    1414//
    1515
    16 #include "bits/containers.h"
    1716#include "bits/defs.h"
    1817#include "bits/locks.h"
    1918
    20 #ifdef __cforall
     19#ifdef __CFORALL__
    2120extern "C" {
    2221#endif
     
    2625#define _INVOKE_H_
    2726
    28         #ifdef __cforall
     27        typedef void (*fptr_t)();
     28        typedef int_fast16_t __lock_size_t;
     29
     30        struct __thread_queue_t {
     31                struct thread_desc * head;
     32                struct thread_desc ** tail;
     33        };
     34
     35        struct __condition_stack_t {
     36                struct __condition_criterion_t * top;
     37        };
     38
     39        #ifdef __CFORALL__
    2940        extern "Cforall" {
    30                 static inline struct thread_desc             * & get_next( struct thread_desc             & this );
    31                 static inline struct __condition_criterion_t * & get_next( struct __condition_criterion_t & this );
     41                void ?{}( struct __thread_queue_t & );
     42                void append( struct __thread_queue_t &, struct thread_desc * );
     43                struct thread_desc * pop_head( struct __thread_queue_t & );
     44                struct thread_desc * remove( struct __thread_queue_t &, struct thread_desc ** );
     45
     46                void ?{}( struct __condition_stack_t & );
     47                void push( struct __condition_stack_t &, struct __condition_criterion_t * );
     48                struct __condition_criterion_t * pop( struct __condition_stack_t & );
    3249        }
    3350        #endif
     
    83100
    84101                // list of acceptable functions, null if any
    85                 __small_array_t(struct __acceptable_t) __cfa_anonymous_object;
     102                struct __acceptable_t * clauses;
     103
     104                // number of acceptable functions
     105                __lock_size_t size;
    86106        };
    87107
     
    94114
    95115                // queue of threads that are blocked waiting for the monitor
    96                 __queue_t(struct thread_desc) entry_queue;
     116                struct __thread_queue_t entry_queue;
    97117
    98118                // stack of conditions to run next once we exit the monitor
    99                 __stack_t(struct __condition_criterion_t) signal_stack;
     119                struct __condition_stack_t signal_stack;
    100120
    101121                // monitor routines can be called recursively, we need to keep track of that
     
    111131        struct __monitor_group_t {
    112132                // currently held monitors
    113                 __small_array_t(monitor_desc*) __cfa_anonymous_object;
     133                struct monitor_desc ** list;
     134
     135                // number of currently held monitors
     136                __lock_size_t size;
    114137
    115138                // last function that acquired monitors
     
    136159     };
    137160
    138      #ifdef __cforall
     161     #ifdef __CFORALL__
    139162     extern "Cforall" {
    140                 static inline thread_desc * & get_next( thread_desc & this ) {
    141                         return this.next;
     163                static inline monitor_desc * ?[?]( const __monitor_group_t & this, ptrdiff_t index ) {
     164                        return this.list[index];
    142165                }
    143166
    144                 static inline struct __condition_criterion_t * & get_next( struct __condition_criterion_t & this );
    145 
    146                 static inline void ?{}(__monitor_group_t & this) {
    147                         (this.data){NULL};
    148                         (this.size){0};
    149                         (this.func){NULL};
    150                 }
    151 
    152                 static inline void ?{}(__monitor_group_t & this, struct monitor_desc ** data, __lock_size_t size, fptr_t func) {
    153                         (this.data){data};
    154                         (this.size){size};
    155                         (this.func){func};
    156                 }
    157 
    158167                static inline bool ?==?( const __monitor_group_t & lhs, const __monitor_group_t & rhs ) {
    159                         if( (lhs.data != 0) != (rhs.data != 0) ) return false;
     168                        if( (lhs.list != 0) != (rhs.list != 0) ) return false;
    160169                        if( lhs.size != rhs.size ) return false;
    161170                        if( lhs.func != rhs.func ) return false;
     
    168177
    169178                        return true;
    170                 }
    171 
    172                 static inline void ?=?(__monitor_group_t & lhs, const __monitor_group_t & rhs) {
    173                         lhs.data = rhs.data;
    174                         lhs.size = rhs.size;
    175                         lhs.func = rhs.func;
    176179                }
    177180        }
     
    207210#endif //_INVOKE_PRIVATE_H_
    208211#endif //! defined(__CFA_INVOKE_PRIVATE__)
    209 #ifdef __cforall
     212#ifdef __CFORALL__
    210213}
    211214#endif
  • src/libcfa/concurrency/kernel

    r9c35431 rc6e2c18  
    2626//-----------------------------------------------------------------------------
    2727// Locks
     28// // Lock the spinlock, spin if already acquired
     29// void lock      ( spinlock * DEBUG_CTX_PARAM2 );
     30
     31// // Lock the spinlock, yield repeatedly if already acquired
     32// void lock_yield( spinlock * DEBUG_CTX_PARAM2 );
     33
     34// // Lock the spinlock, return false if already acquired
     35// bool try_lock  ( spinlock * DEBUG_CTX_PARAM2 );
     36
     37// // Unlock the spinlock
     38// void unlock    ( spinlock * );
     39
    2840struct semaphore {
    2941        __spinlock_t lock;
    3042        int count;
    31         __queue_t(thread_desc) waiting;
     43        __thread_queue_t waiting;
    3244};
    3345
     
    4557
    4658        // Ready queue for threads
    47         __queue_t(thread_desc) ready_queue;
     59        __thread_queue_t ready_queue;
    4860
    4961        // Preemption rate on this cluster
  • src/libcfa/concurrency/kernel.c

    r9c35431 rc6e2c18  
    164164
    165165void ?{}(cluster & this) {
    166         (this.ready_queue){};
     166        ( this.ready_queue ){};
    167167        ( this.ready_queue_lock ){};
    168168
     
    611611}
    612612
     613//-----------------------------------------------------------------------------
     614// Queues
     615void ?{}( __thread_queue_t & this ) {
     616        this.head = NULL;
     617        this.tail = &this.head;
     618}
     619
     620void append( __thread_queue_t & this, thread_desc * t ) {
     621        verify(this.tail != NULL);
     622        *this.tail = t;
     623        this.tail = &t->next;
     624}
     625
     626thread_desc * pop_head( __thread_queue_t & this ) {
     627        thread_desc * head = this.head;
     628        if( head ) {
     629                this.head = head->next;
     630                if( !head->next ) {
     631                        this.tail = &this.head;
     632                }
     633                head->next = NULL;
     634        }
     635        return head;
     636}
     637
     638thread_desc * remove( __thread_queue_t & this, thread_desc ** it ) {
     639        thread_desc * thrd = *it;
     640        verify( thrd );
     641
     642        (*it) = thrd->next;
     643
     644        if( this.tail == &thrd->next ) {
     645                this.tail = it;
     646        }
     647
     648        thrd->next = NULL;
     649
     650        verify( (this.head == NULL) == (&this.head == this.tail) );
     651        verify( *this.tail == NULL );
     652        return thrd;
     653}
     654
     655void ?{}( __condition_stack_t & this ) {
     656        this.top = NULL;
     657}
     658
     659void push( __condition_stack_t & this, __condition_criterion_t * t ) {
     660        verify( !t->next );
     661        t->next = this.top;
     662        this.top = t;
     663}
     664
     665__condition_criterion_t * pop( __condition_stack_t & this ) {
     666        __condition_criterion_t * top = this.top;
     667        if( top ) {
     668                this.top = top->next;
     669                top->next = NULL;
     670        }
     671        return top;
     672}
     673
    613674// Local Variables: //
    614675// mode: c //
  • src/libcfa/concurrency/monitor

    r9c35431 rc6e2c18  
    3434        this.recursion     = 0;
    3535        this.mask.accepted = NULL;
    36         this.mask.data     = NULL;
     36        this.mask.clauses  = NULL;
    3737        this.mask.size     = 0;
    3838        this.dtor_node     = NULL;
     
    4040
    4141struct monitor_guard_t {
    42         monitor_desc **         m;
    43         __lock_size_t           count;
    44         __monitor_group_t prev;
     42        monitor_desc ** m;
     43        __lock_size_t   count;
     44        monitor_desc ** prev_mntrs;
     45        __lock_size_t   prev_count;
     46        fptr_t          prev_func;
    4547};
    4648
     
    4951
    5052struct monitor_dtor_guard_t {
    51         monitor_desc *    m;
    52         __monitor_group_t prev;
     53        monitor_desc * m;
     54        monitor_desc ** prev_mntrs;
     55        __lock_size_t   prev_count;
     56        fptr_t          prev_func;
    5357};
    5458
     
    7983};
    8084
    81 static inline __condition_criterion_t * & get_next( __condition_criterion_t & this ) {
    82         return this.next;
    83 }
    84 
    8585struct __condition_node_t {
    8686        // Thread that needs to be woken when all criteria are met
     
    100100};
    101101
    102 static inline __condition_node_t * & get_next( __condition_node_t & this ) {
    103         return this.next;
    104 }
     102struct __condition_blocked_queue_t {
     103        __condition_node_t * head;
     104        __condition_node_t ** tail;
     105};
    105106
    106107void ?{}(__condition_node_t & this, thread_desc * waiting_thread, __lock_size_t count, uintptr_t user_info );
     
    108109void ?{}(__condition_criterion_t & this, monitor_desc * target, __condition_node_t * owner );
    109110
     111void ?{}( __condition_blocked_queue_t & );
     112void append( __condition_blocked_queue_t &, __condition_node_t * );
     113__condition_node_t * pop_head( __condition_blocked_queue_t & );
     114
    110115struct condition {
    111116        // Link list which contains the blocked threads as-well as the information needed to unblock them
    112         __queue_t(__condition_node_t) blocked;
     117        __condition_blocked_queue_t blocked;
    113118
    114119        // Array of monitor pointers (Monitors are NOT contiguous in memory)
  • src/libcfa/concurrency/monitor.c

    r9c35431 rc6e2c18  
    280280static inline void enter( __monitor_group_t monitors ) {
    281281        for( __lock_size_t i = 0; i < monitors.size; i++) {
    282                 __enter_monitor_desc( monitors[i], monitors );
     282                __enter_monitor_desc( monitors.list[i], monitors );
    283283        }
    284284}
     
    303303
    304304        // Save previous thread context
    305         this.prev = this_thread->monitors;
     305        this.[prev_mntrs, prev_count, prev_func] = this_thread->monitors.[list, size, func];
    306306
    307307        // Update thread context (needed for conditions)
    308         (this_thread->monitors){m, count, func};
     308        this_thread->monitors.[list, size, func] = [m, count, func];
    309309
    310310        // LIB_DEBUG_PRINT_SAFE("MGUARD : enter %d\n", count);
     
    328328
    329329        // Restore thread context
    330         this_thread->monitors = this.prev;
     330        this_thread->monitors.[list, size, func] = this.[prev_mntrs, prev_count, prev_func];
    331331}
    332332
     
    338338
    339339        // Save previous thread context
    340         this.prev = this_thread->monitors;
     340        this.[prev_mntrs, prev_count, prev_func] = this_thread->monitors.[list, size, func];
    341341
    342342        // Update thread context (needed for conditions)
    343         (this_thread->monitors){m, 1, func};
     343        this_thread->monitors.[list, size, func] = [m, 1, func];
    344344
    345345        __enter_monitor_dtor( this.m, func );
     
    352352
    353353        // Restore thread context
    354         this_thread->monitors = this.prev;
     354        this_thread->monitors.[list, size, func] = this.[prev_mntrs, prev_count, prev_func];
    355355}
    356356
     
    437437
    438438                for(int i = 0; i < this.monitor_count; i++) {
    439                         if ( this.monitors[i] != this_thrd->monitors[i] ) {
    440                                 abortf( "Signal on condition %p made with different monitor, expected %p got %i", &this, this.monitors[i], this_thrd->monitors[i] );
     439                        if ( this.monitors[i] != this_thrd->monitors.list[i] ) {
     440                                abortf( "Signal on condition %p made with different monitor, expected %p got %i", &this, this.monitors[i], this_thrd->monitors.list[i] );
    441441                        }
    442442                }
     
    510510                "Possible cause is not checking if the condition is empty before reading stored data."
    511511        );
    512         return ((typeof(this.blocked.head))this.blocked.head)->user_info;
     512        return this.blocked.head->user_info;
    513513}
    514514
     
    554554                if( next ) {
    555555                        *mask.accepted = index;
    556                         __acceptable_t& accepted = mask[index];
    557                         if( accepted.is_dtor ) {
     556                        if( mask.clauses[index].is_dtor ) {
    558557                                LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : dtor already there\n");
    559                                 verifyf( accepted.size == 1, "ERROR: Accepted dtor has more than 1 mutex parameter." );
    560 
    561                                 monitor_desc * mon2dtor = accepted[0];
     558                                verifyf( mask.clauses[index].size == 1        , "ERROR: Accepted dtor has more than 1 mutex parameter." );
     559
     560                                monitor_desc * mon2dtor = mask.clauses[index].list[0];
    562561                                verifyf( mon2dtor->dtor_node, "ERROR: Accepted monitor has no dtor_node." );
    563562
     
    597596
    598597                        LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : accepted %d\n", *mask.accepted);
     598
    599599                        return;
    600600                }
     
    671671static inline void reset_mask( monitor_desc * this ) {
    672672        this->mask.accepted = NULL;
    673         this->mask.data = NULL;
     673        this->mask.clauses = NULL;
    674674        this->mask.size = 0;
    675675}
     
    697697
    698698static inline bool is_accepted( monitor_desc * this, const __monitor_group_t & group ) {
    699         __acceptable_t * it = this->mask.data; // Optim
     699        __acceptable_t * it = this->mask.clauses; // Optim
    700700        __lock_size_t count = this->mask.size;
    701701
     
    820820        if( !this.monitors ) {
    821821                // LIB_DEBUG_PRINT_SAFE("Branding\n");
    822                 assertf( thrd->monitors.data != NULL, "No current monitor to brand condition %p", thrd->monitors.data );
     822                assertf( thrd->monitors.list != NULL, "No current monitor to brand condition %p", thrd->monitors.list );
    823823                this.monitor_count = thrd->monitors.size;
    824824
    825825                this.monitors = (monitor_desc **)malloc( this.monitor_count * sizeof( *this.monitors ) );
    826826                for( int i = 0; i < this.monitor_count; i++ ) {
    827                         this.monitors[i] = thrd->monitors[i];
     827                        this.monitors[i] = thrd->monitors.list[i];
    828828                }
    829829        }
     
    832832static inline [thread_desc *, int] search_entry_queue( const __waitfor_mask_t & mask, monitor_desc * monitors [], __lock_size_t count ) {
    833833
    834         __queue_t(thread_desc) & entry_queue = monitors[0]->entry_queue;
     834        __thread_queue_t & entry_queue = monitors[0]->entry_queue;
    835835
    836836        // For each thread in the entry-queue
     
    841841                // For each acceptable check if it matches
    842842                int i = 0;
    843                 __acceptable_t * end   = end  (mask);
    844                 __acceptable_t * begin = begin(mask);
    845                 for( __acceptable_t * it = begin; it != end; it++, i++ ) {
     843                __acceptable_t * end = mask.clauses + mask.size;
     844                for( __acceptable_t * it = mask.clauses; it != end; it++, i++ ) {
    846845                        // Check if we have a match
    847846                        if( *it == (*thrd_it)->monitors ) {
     
    873872        __lock_size_t max = 0;
    874873        for( __lock_size_t i = 0; i < mask.size; i++ ) {
    875                 __acceptable_t & accepted = mask[i];
    876                 max += accepted.size;
     874                max += mask.clauses[i].size;
    877875        }
    878876        return max;
     
    882880        __lock_size_t size = 0;
    883881        for( __lock_size_t i = 0; i < mask.size; i++ ) {
    884                 __acceptable_t & accepted = mask[i];
    885                 __libcfa_small_sort( accepted.data, accepted.size );
    886                 for( __lock_size_t j = 0; j < accepted.size; j++) {
    887                         insert_unique( storage, size, accepted[j] );
     882                __libcfa_small_sort( mask.clauses[i].list, mask.clauses[i].size );
     883                for( __lock_size_t j = 0; j < mask.clauses[i].size; j++) {
     884                        insert_unique( storage, size, mask.clauses[i].list[j] );
    888885                }
    889886        }
     
    891888        __libcfa_small_sort( storage, size );
    892889        return size;
     890}
     891
     892void ?{}( __condition_blocked_queue_t & this ) {
     893        this.head = NULL;
     894        this.tail = &this.head;
     895}
     896
     897void append( __condition_blocked_queue_t & this, __condition_node_t * c ) {
     898        verify(this.tail != NULL);
     899        *this.tail = c;
     900        this.tail = &c->next;
     901}
     902
     903__condition_node_t * pop_head( __condition_blocked_queue_t & this ) {
     904        __condition_node_t * head = this.head;
     905        if( head ) {
     906                this.head = head->next;
     907                if( !head->next ) {
     908                        this.tail = &this.head;
     909                }
     910                head->next = NULL;
     911        }
     912        return head;
    893913}
    894914
  • src/libcfa/exception.h

    r9c35431 rc6e2c18  
    1717
    1818
    19 #ifdef __cforall
     19#ifdef __CFORALL__
    2020extern "C" {
    2121#endif
     
    6868struct __cfaehm__cleanup_hook {};
    6969
    70 #ifdef __cforall
     70#ifdef __CFORALL__
    7171}
    7272#endif
  • src/libcfa/stdhdr/assert.h

    r9c35431 rc6e2c18  
    44// The contents of this file are covered under the licence agreement in the
    55// file "LICENCE" distributed with Cforall.
    6 //
    7 // assert.h --
    8 //
     6// 
     7// assert.h -- 
     8// 
    99// Author           : Peter A. Buhr
    1010// Created On       : Mon Jul  4 23:25:26 2016
     
    1212// Last Modified On : Mon Jul 31 23:09:32 2017
    1313// Update Count     : 13
    14 //
     14// 
    1515
    16 #ifdef __cforall
     16#ifdef __CFORALL__
    1717extern "C" {
    18 #endif //__cforall
     18#endif //__CFORALL__
    1919
    2020#include_next <assert.h>
     
    3030#endif
    3131
    32 #ifdef __cforall
     32#ifdef __CFORALL__
    3333} // extern "C"
    34 #endif //__cforall
     34#endif //__CFORALL__
    3535
    3636// Local Variables: //
  • src/libcfa/virtual.h

    r9c35431 rc6e2c18  
    1616#pragma once
    1717
    18 #ifdef __cforall
     18#ifdef __CFORALL__
    1919extern "C" {
    2020#endif
     
    3535                struct __cfa__parent_vtable const * const * child );
    3636
    37 #ifdef __cforall
     37#ifdef __CFORALL__
    3838}
    3939#endif
  • src/tests/Makefile.am

    r9c35431 rc6e2c18  
    1111## Created On       : Sun May 31 09:08:15 2015
    1212## Last Modified By : Peter A. Buhr
    13 ## Last Modified On : Mon Nov 27 21:34:33 2017
    14 ## Update Count     : 48
     13## Last Modified On : Tue Oct 10 14:04:40 2017
     14## Update Count     : 47
    1515###############################################################################
    1616
     
    118118        ${CC} ${AM_CFLAGS} ${CFLAGS} -CFA -XCFA -p ${<} -o ${@}
    119119
    120 functions: functions.c @CFA_BINDIR@/@CFA_NAME@
    121         ${CC} ${AM_CFLAGS} ${CFLAGS} -CFA -XCFA -p ${<} -o ${@}
    122 
    123120KRfunctions : KRfunctions.c @CFA_BINDIR@/@CFA_NAME@
    124121        ${CC} ${AM_CFLAGS} ${CFLAGS} -CFA -XCFA -p ${<} -o ${@}
  • src/tests/Makefile.in

    r9c35431 rc6e2c18  
    871871        ${CC} ${AM_CFLAGS} ${CFLAGS} -CFA -XCFA -p ${<} -o ${@}
    872872
    873 functions: functions.c @CFA_BINDIR@/@CFA_NAME@
    874         ${CC} ${AM_CFLAGS} ${CFLAGS} -CFA -XCFA -p ${<} -o ${@}
    875 
    876873KRfunctions : KRfunctions.c @CFA_BINDIR@/@CFA_NAME@
    877874        ${CC} ${AM_CFLAGS} ${CFLAGS} -CFA -XCFA -p ${<} -o ${@}
  • src/tests/designations.c

    r9c35431 rc6e2c18  
    1717// In particular, since the syntax for designations in Cforall differs from that of C, preprocessor substitution
    1818// is used for the designation syntax
    19 #ifdef __cforall
     19#ifdef __CFORALL__
    2020#define DES :
    2121#else
  • src/tests/functions.c

    r9c35431 rc6e2c18  
    1010// Created On       : Wed Aug 17 08:39:58 2016
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Nov 27 18:08:54 2017
    13 // Update Count     : 11
     12// Last Modified On : Wed Aug 17 08:40:52 2016
     13// Update Count     : 1
    1414//
    1515
     
    6666// Cforall extensions
    6767
    68 // [] f( );
     68[] f( );
    6969[int] f( );
    70 // [] f(int);
     70[] f(int);
    7171[int] f(int);
    72 // [] f( ) {}
     72[] f( ) {}
    7373[int] f( ) {}
    74 // [] f(int) {}
     74[] f(int) {}
    7575[int] f(int) {}
    7676
    7777[int x] f( );
    78 // [] f(int x);
    79 //[int x] f(int x);
    80 //[int x] f( ) {}
    81 // [] f(int x) {}
    82 //[int x] f(int x) {}
     78[] f(int x);
     79[int x] f(int x);
     80[int x] f( ) {}
     81[] f(int x) {}
     82[int x] f(int x) {}
    8383
    8484[int, int x] f( );
    85 // [] f(int, int x);
     85[] f(int, int x);
    8686[int, int x] f(int, int x);
    8787[int, int x] f( ) {}
    88 // [] f(int, int x) {}
     88[] f(int, int x) {}
    8989[int, int x] f(int, int x) {}
    9090
    9191[int, int x, int] f( );
    92 // [] f(int, int x, int);
     92[] f(int, int x, int);
    9393[int, int x, int] f(int, int x, int);
    9494[int, int x, int] f( ) {}
    95 // [] f(int, int x, int) {}
     95[] f(int, int x, int) {}
    9696[int, int x, int] f(int, int x, int) {}
    9797
    9898[int, int x, * int y] f( );
    99 // [] f(int, int x, * int y);
     99[] f(int, int x, * int y);
    100100[int, int x, * int y] f(int, int x, * int y);
    101101[int, int x, * int y] f( ) {}
    102 // [] f(int, int x, * int y) {}
     102[] f(int, int x, * int y) {}
    103103[int, int x, * int y] f(int, int x, * int y) {}
    104104
    105 // function prototypes
    106 
    107 [ int ] f11( int ), f12();  // => int f11( int ), f12( void );
    108 
    109 const double bar1(), bar2( int ), bar3( double );               // C version
    110 [const double] foo(), foo( int ), foo( double ) { return 3.0; } // CFA version
    111 struct S { int i; };
    112 [S] rtn( int ) {}
    113 
     105[ int ] f11( int ), f12;  // => int f11( int ), f12( int );
    114106
    115107[int] f(
     
    117109        [int](int)
    118110        ) {
    119         int (*(*pc)[][10])[][3];
     111        int (*(*p)[][10])[][3];
    120112        * [][10] * [][3] int p;
    121113        * [] * [int](int) p;
Note: See TracChangeset for help on using the changeset viewer.