Changeset d5ccbe9 for doc/papers/concurrency/Paper.tex
- Timestamp:
- Mar 16, 2018, 1:57:38 PM (5 years ago)
- Branches:
- ADT, aaron-thesis, arm-eh, cleanup-dtors, deferred_resn, demangler, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, pthread-emulation, qualifiedEnum, with_gc
- Children:
- fdfced6
- Parents:
- 759f05f
- git-author:
- Peter A. Buhr <pabuhr@…> (03/16/18 12:14:02)
- git-committer:
- Peter A. Buhr <pabuhr@…> (03/16/18 13:57:38)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
doc/papers/concurrency/Paper.tex
r759f05f rd5ccbe9 7 7 % math escape $...$ (dollar symbol) 8 8 9 \documentclass[10pt]{article} 9 \documentclass[AMA,STIX1COL]{WileyNJD-v2} 10 11 \articletype{RESEARCH ARTICLE}% 12 13 \received{26 April 2016} 14 \revised{6 June 2016} 15 \accepted{6 June 2016} 16 17 \raggedbottom 10 18 11 19 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 12 20 13 21 % Latex packages used in the document. 22 14 23 \usepackage[T1]{fontenc} % allow Latin1 (extended ASCII) characters 15 24 \usepackage{textcomp} 16 25 \usepackage[latin1]{inputenc} 17 \usepackage{fullpage,times,comment} 26 18 27 \usepackage{epic,eepic} 28 \usepackage{xspace} 29 \usepackage{comment} 19 30 \usepackage{upquote} % switch curled `'" to straight 20 \usepackage{calc} 21 \usepackage{xspace} 31 \usepackage{listings} % format program code 22 32 \usepackage[labelformat=simple]{subfig} 23 33 \renewcommand{\thesubfigure}{(\alph{subfigure})} 24 \usepackage{ graphicx}25 \ usepackage{tabularx}26 \ usepackage{multicol}27 \usepackage{varioref} 28 \ usepackage{listings} % format program code29 \ usepackage[flushmargin]{footmisc} % support label/reference in footnote30 \ usepackage{latexsym} % \Box glyph31 \ usepackage{mathptmx} % better math font with "times"32 \usepackage[usenames]{color} 34 \usepackage{siunitx} 35 \sisetup{ binary-units=true } 36 \input{style} % bespoke macros used in the document 37 38 \hypersetup{breaklinks=true} 39 \definecolor{OliveGreen}{cmyk}{0.64 0 0.95 0.40} 40 \definecolor{Mahogany}{cmyk}{0 0.85 0.87 0.35} 41 \definecolor{Plum}{cmyk}{0.50 1 0 0} 42 33 43 \usepackage[pagewise]{lineno} 34 44 \renewcommand{\linenumberfont}{\scriptsize\sffamily} 35 \usepackage{fancyhdr} 36 \usepackage{float} 37 \usepackage{siunitx} 38 \sisetup{ binary-units=true } 39 \input{style} % bespoke macros used in the document 40 \usepackage{url} 41 \usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref} 42 \usepackage{breakurl} 43 \urlstyle{rm} 44 45 \setlength{\topmargin}{-0.45in} % move running title into header 46 \setlength{\headsep}{0.25in} 45 46 \lefthyphenmin=4 % hyphen only after 4 characters 47 \righthyphenmin=4 47 48 48 49 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% … … 50 51 % Names used in the document. 51 52 52 \newcommand{\Version}{1.0.0}53 53 \newcommand{\CS}{C\raisebox{-0.9ex}{\large$^\sharp$}\xspace} 54 54 … … 67 67 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 68 68 69 \setcounter{secnumdepth}{2} % number subsubsections 70 \setcounter{tocdepth}{2} % subsubsections in table of contents 71 % \linenumbers % comment out to turn off line numbering 72 73 \title{Concurrency in \CFA} 74 \author{Thierry Delisle and Peter A. Buhr, Waterloo, Ontario, Canada} 69 \title{\texorpdfstring{Concurrency in \protect\CFA}{Concurrency in Cforall}} 70 71 \author[1]{Thierry Delisle} 72 \author[1]{Peter A. Buhr*} 73 \authormark{Thierry Delisle \textsc{et al}} 74 75 \address[1]{\orgdiv{David R. Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Ontario}, \country{Canada}}} 76 77 \corres{*Peter A. Buhr, \email{pabuhr{\char`\@}uwaterloo.ca}} 78 \presentaddress{David R. Cheriton School of Computer Science, University of Waterloo, Waterloo, ON, N2L 3G1, Canada} 79 80 81 \abstract[Summary]{ 82 \CFA is a modern, polymorphic, \emph{non-object-oriented} extension of the C programming language. 83 This paper discusses the design of the concurrency and parallelism features in \CFA, and the concurrent runtime-system that supports them. 84 These features are created from scratch as ISO C lacks concurrency, relying largely on pthreads. 85 Coroutines and lightweight (user) threads are introduced into the language. 86 In addition, monitors are added as a high-level mechanism for mutual exclusion and synchronization. 87 A unique contribution is allowing multiple monitors to be safely acquired simultaneously. 88 All features respect the expectations of C programmers, while being fully integrate with the \CFA polymorphic type-system and other language features. 89 Finally, experimental results are presented to validate several of the new features with other concurrent programming-languages. 90 }% 91 92 \keywords{concurrency, runtime, coroutines, threads, C, Cforall} 75 93 76 94 77 95 \begin{document} 96 \linenumbers % comment out to turn off line numbering 97 78 98 \maketitle 79 99 80 \begin{abstract} 81 \CFA is a modern, \emph{non-object-oriented} extension of the C programming language. 82 This paper serves as a definition and an implementation for the concurrency and parallelism \CFA offers. These features are created from scratch due to the lack of concurrency in ISO C. Lightweight threads are introduced into the language. In addition, monitors are introduced as a high-level tool for control-flow based synchronization and mutual-exclusion. The main contributions of this paper are two-fold: it extends the existing semantics of monitors introduce by~\cite{Hoare74} to handle monitors in groups and also details the engineering effort needed to introduce these features as core language features. Indeed, these features are added with respect to expectations of C programmers, and integrate with the \CFA type-system and other language features. 83 \end{abstract} 84 85 %---------------------------------------------------------------------- 86 % MAIN BODY 87 %---------------------------------------------------------------------- 88 100 % ====================================================================== 89 101 % ====================================================================== 90 102 \section{Introduction} 91 103 % ====================================================================== 92 93 This paper provides a minimal concurrency \textbf{api} that is simple, efficient and can be reused to build higher-level features. The simplest possible concurrency system is a thread and a lock but this low-level approach is hard to master. An easier approach for users is to support higher-level constructs as the basis of concurrency. Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{HPP:Study}. Examples are task based, message passing and implicit threading. The high-level approach and its minimal \textbf{api} are tested in a dialect of C, called \CFA. Furthermore, the proposed \textbf{api} doubles as an early definition of the \CFA language and library. This paper also provides an implementation of the concurrency library for \CFA as well as all the required language features added to the source-to-source translator. 94 95 There are actually two problems that need to be solved in the design of concurrency for a programming language: which concurrency and which parallelism tools are available to the programmer. While these two concepts are often combined, they are in fact distinct, requiring different tools~\cite{Buhr05a}. Concurrency tools need to handle mutual exclusion and synchronization, while parallelism tools are about performance, cost and resource utilization. 96 97 In the context of this paper, a \textbf{thread} is a fundamental unit of execution that runs a sequence of code, generally on a program stack. Having multiple simultaneous threads gives rise to concurrency and generally requires some kind of locking mechanism to ensure proper execution. Correspondingly, \textbf{concurrency} is defined as the concepts and challenges that occur when multiple independent (sharing memory, timing dependencies, etc.) concurrent threads are introduced. Accordingly, \textbf{locking} (and by extension locks) are defined as a mechanism that prevents the progress of certain threads in order to avoid problems due to concurrency. Finally, in this paper \textbf{parallelism} is distinct from concurrency and is defined as running multiple threads simultaneously. More precisely, parallelism implies \emph{actual} simultaneous execution as opposed to concurrency which only requires \emph{apparent} simultaneous execution. As such, parallelism is only observable in the differences in performance or, more generally, differences in timing. 104 % ====================================================================== 105 106 This paper provides a minimal concurrency \textbf{api} that is simple, efficient and can be reused to build higher-level features. 107 The simplest possible concurrency system is a thread and a lock but this low-level approach is hard to master. 108 An easier approach for users is to support higher-level constructs as the basis of concurrency. 109 Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{HPP:Study}. 110 Examples are task based, message passing and implicit threading. 111 The high-level approach and its minimal \textbf{api} are tested in a dialect of C, called \CFA. 112 Furthermore, the proposed \textbf{api} doubles as an early definition of the \CFA language and library. 113 This paper also provides an implementation of the concurrency library for \CFA as well as all the required language features added to the source-to-source translator. 114 115 There are actually two problems that need to be solved in the design of concurrency for a programming language: which concurrency and which parallelism tools are available to the programmer. 116 While these two concepts are often combined, they are in fact distinct, requiring different tools~\cite{Buhr05a}. 117 Concurrency tools need to handle mutual exclusion and synchronization, while parallelism tools are about performance, cost and resource utilization. 118 119 In the context of this paper, a \textbf{thread} is a fundamental unit of execution that runs a sequence of code, generally on a program stack. 120 Having multiple simultaneous threads gives rise to concurrency and generally requires some kind of locking mechanism to ensure proper execution. 121 Correspondingly, \textbf{concurrency} is defined as the concepts and challenges that occur when multiple independent (sharing memory, timing dependencies, etc.) concurrent threads are introduced. 122 Accordingly, \textbf{locking} (and by extension locks) are defined as a mechanism that prevents the progress of certain threads in order to avoid problems due to concurrency. 123 Finally, in this paper \textbf{parallelism} is distinct from concurrency and is defined as running multiple threads simultaneously. 124 More precisely, parallelism implies \emph{actual} simultaneous execution as opposed to concurrency which only requires \emph{apparent} simultaneous execution. 125 As such, parallelism is only observable in the differences in performance or, more generally, differences in timing. 98 126 99 127 % ====================================================================== … … 105 133 The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency. 106 134 107 \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 opted 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 108 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}. 135 \CFA is an extension of ISO-C and therefore supports all of the same paradigms as C. 136 It is a non-object-oriented system-language, meaning most of the major abstractions have either no runtime overhead or can be opted out easily. 137 Like C, the basics of \CFA revolve around structures and routines, which are thin abstractions over machine code. 138 The vast majority of the code produced by the \CFA translator respects memory layouts and calling conventions laid out by C. 139 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 140 values''~\cite[3.15]{C11}}, most importantly construction and destruction of objects. 141 Most of the following code examples can be found on the \CFA website~\cite{www-cfa}. 109 142 110 143 % ====================================================================== 111 144 \subsection{References} 112 145 113 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: 146 Like \CC, \CFA introduces rebind-able references providing multiple dereferencing as an alternative to pointers. 147 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: 114 148 \begin{cfacode} 115 149 int x, *p1 = &x, **p2 = &p1, ***p3 = &p2, … … 130 164 \subsection{Overloading} 131 165 132 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. 166 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. 167 As well, \CFA uses the return type as part of the selection criteria, as in Ada~\cite{Ada}. 168 For routines with multiple parameters and returns, the selection is complex. 133 169 \begin{cfacode} 134 170 //selection based on type and number of parameters … … 146 182 double d = f(4); //select (2) 147 183 \end{cfacode} 148 This feature is particularly important for concurrency since the runtime system relies on creating different types to represent concurrency objects. Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions that prevent name clashes. As seen in section \ref{basics}, routine \code{main} is an example that benefits from overloading. 184 This feature is particularly important for concurrency since the runtime system relies on creating different types to represent concurrency objects. 185 Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions that prevent name clashes. 186 As seen in section \ref{basics}, routine \code{main} is an example that benefits from overloading. 149 187 150 188 % ====================================================================== 151 189 \subsection{Operators} 152 Overloading also extends to operators. The syntax for denoting operator-overloading is to name a routine with the symbol of the operator and question marks where the arguments of the operation appear, e.g.: 190 Overloading also extends to operators. 191 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 appear, e.g.: 153 192 \begin{cfacode} 154 193 int ++? (int op); //unary prefix increment … … 170 209 % ====================================================================== 171 210 \subsection{Constructors/Destructors} 172 Object lifetime is often a challenge in concurrency. \CFA uses the approach of giving concurrent meaning to object lifetime as a means of synchronization and/or mutual exclusion. Since \CFA relies heavily on the lifetime of objects, constructors and destructors is a core feature required for concurrency and parallelism. \CFA uses the following syntax for constructors and destructors: 211 Object lifetime is often a challenge in concurrency. \CFA uses the approach of giving concurrent meaning to object lifetime as a means of synchronization and/or mutual exclusion. 212 Since \CFA relies heavily on the lifetime of objects, constructors and destructors is a core feature required for concurrency and parallelism. \CFA uses the following syntax for constructors and destructors: 173 213 \begin{cfacode} 174 214 struct S { … … 191 231 } //implicit calls: ^?{}(y), ^?{}(x) 192 232 \end{cfacode} 193 The language guarantees that every object and all their fields are constructed. Like \CC, construction of an object is automatically done on allocation and destruction of the object is done on deallocation. Allocation and deallocation can occur on the stack or on the heap. 233 The language guarantees that every object and all their fields are constructed. 234 Like \CC, construction of an object is automatically done on allocation and destruction of the object is done on deallocation. 235 Allocation and deallocation can occur on the stack or on the heap. 194 236 \begin{cfacode} 195 237 { … … 206 248 \subsection{Parametric Polymorphism} 207 249 \label{s:ParametricPolymorphism} 208 Routines in \CFA can also be reused for multiple types. This capability is done using the \code{forall} clauses, which 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: 250 Routines in \CFA can also be reused for multiple types. 251 This capability is done using the \code{forall} clauses, which allow separately compiled routines to support generic usage over multiple types. 252 For example, the following sum function works for any type that supports construction from 0 and addition: 209 253 \begin{cfacode} 210 254 //constraint type, 0 and + … … 221 265 \end{cfacode} 222 266 223 Since writing constraints on types can become cumbersome for more constrained functions, \CFA also has the concept of traits. Traits are named collection of constraints that can be used both instead and in addition to regular constraints: 267 Since writing constraints on types can become cumbersome for more constrained functions, \CFA also has the concept of traits. 268 Traits are named collection of constraints that can be used both instead and in addition to regular constraints: 224 269 \begin{cfacode} 225 270 trait summable( otype T ) { … … 234 279 \end{cfacode} 235 280 236 Note that the type use for assertions can be either an \code{otype} or a \code{dtype}. Types declared 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. 281 Note that the type use for assertions can be either an \code{otype} or a \code{dtype}. 282 Types declared 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. 283 Using \code{dtype,} on the other hand, has none of these assumptions but is extremely restrictive, it only guarantees the object is addressable. 237 284 238 285 % ====================================================================== 239 286 \subsection{with Clause/Statement} 240 Since \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). 287 Since \CFA lacks the concept of a receiver, certain functions end up needing to repeat variable names often. 288 To remove this inconvenience, \CFA provides the \code{with} statement, which opens an aggregate scope making its fields directly accessible (like Pascal). 241 289 \begin{cfacode} 242 290 struct S { int i, j; }; … … 273 321 274 322 \section{Basics of concurrency} 275 At its core, concurrency is based on having multiple call-stacks and scheduling among threads of execution executing on these stacks. Concurrency without parallelism only requires having multiple call stacks (or contexts) for a single thread of execution. 276 277 Execution with a single thread and multiple stacks where the thread is self-scheduling deterministically across the stacks is called coroutining. Execution with a single and multiple stacks but where the thread is scheduled by an oracle (non-deterministic from the thread's perspective) across the stacks is called concurrency. 278 279 Therefore, a minimal concurrency system can be achieved by creating coroutines (see Section \ref{coroutine}), 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. 280 281 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. 323 At its core, concurrency is based on having multiple call-stacks and scheduling among threads of execution executing on these stacks. 324 Concurrency without parallelism only requires having multiple call stacks (or contexts) for a single thread of execution. 325 326 Execution with a single thread and multiple stacks where the thread is self-scheduling deterministically across the stacks is called coroutining. 327 Execution with a single and multiple stacks but where the thread is scheduled by an oracle (non-deterministic from the thread's perspective) across the stacks is called concurrency. 328 329 Therefore, a minimal concurrency system can be achieved by creating coroutines (see Section \ref{coroutine}), which instead of context-switching among each other, always ask an oracle where to context-switch next. 330 While coroutines can execute on the caller's stack-frame, stack-full coroutines allow full generality and are sufficient as the basis for concurrency. 331 The aforementioned oracle is a scheduler and the whole system now follows a cooperative threading-model (a.k.a., non-preemptive scheduling). 332 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. 333 In any case, a subset of concurrency related challenges start to appear. 334 For the complete set of concurrency challenges to occur, the only feature missing is preemption. 335 336 A scheduler introduces order of execution uncertainty, while preemption introduces uncertainty about where context switches occur. 337 Mutual exclusion and synchronization are ways of limiting non-determinism in a concurrent system. 338 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. 339 Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows. 282 340 283 341 \section{\protect\CFA's Thread Building Blocks} 284 One of the important features that are missing in C is threading\footnote{While the C11 standard defines a ``threads.h'' header, it is minimal and defined as optional. As such, library support for threading is far from widespread. At the time of writing the paper, neither \texttt{gcc} nor \texttt{clang} support ``threads.h'' in their respective standard libraries.}. 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 efficient 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. 342 One of the important features that are missing in C is threading\footnote{While the C11 standard defines a ``threads.h'' header, it is minimal and defined as optional. 343 As such, library support for threading is far from widespread. 344 At the time of writing the paper, neither \texttt{gcc} nor \texttt{clang} support ``threads.h'' in their respective standard libraries.}. 345 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 efficient concurrent programs to take advantage of parallelism. 346 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. 347 And being a system-level language means programmers expect to choose precisely which features they need and which cost they are willing to pay. 285 348 286 349 \section{Coroutines: A Stepping Stone}\label{coroutine} 287 While the main focus of this proposal is concurrency and parallelism, it is important to address coroutines, which are actually a significant building block of a concurrency system. \textbf{Coroutine}s are generalized routines which have predefined points where execution is suspended and can be resumed at a later time. Therefore, they need to deal with context switches and other context-management operations. 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 \textbf{api} of coroutines revolves around two features: independent call-stacks and \code{suspend}/\code{resume}. 350 While the main focus of this proposal is concurrency and parallelism, it is important to address coroutines, which are actually a significant building block of a concurrency system. \textbf{Coroutine}s are generalized routines which have predefined points where execution is suspended and can be resumed at a later time. 351 Therefore, they need to deal with context switches and other context-management operations. 352 This proposal includes coroutines both as an intermediate step for the implementation of threads, and a first-class feature of \CFA. 353 Furthermore, many design challenges of threads are at least partially present in designing coroutines, which makes the design effort that much more relevant. 354 The core \textbf{api} of coroutines revolves around two features: independent call-stacks and \code{suspend}/\code{resume}. 288 355 289 356 \begin{table} … … 399 466 \end{table} 400 467 401 A good example of a problem made easier with coroutines is generators, e.g., generating the Fibonacci sequence. This problem comes with the challenge of decoupling how a sequence is generated and how it is used. Listing \ref{lst:fibonacci-c} shows conventional approaches to writing generators in C. All three of these approach suffer from strong coupling. The left and centre 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. 402 403 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. 468 A good example of a problem made easier with coroutines is generators, e.g., generating the Fibonacci sequence. 469 This problem comes with the challenge of decoupling how a sequence is generated and how it is used. 470 Listing \ref{lst:fibonacci-c} shows conventional approaches to writing generators in C. 471 All three of these approach suffer from strong coupling. 472 The left and centre 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. 473 474 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. 475 This solution has the advantage of having very strong decoupling between how the sequence is generated and how it is used. 476 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. 404 477 405 478 \begin{figure} … … 447 520 \end{figure} 448 521 449 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. 522 Listing \ref{lst:fmt-line} shows the \code{Format} coroutine for restructuring text into groups of character blocks of fixed size. 523 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. 450 524 451 525 \begin{figure} … … 497 571 498 572 \subsection{Construction} 499 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. 500 501 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 expect both 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 option effectively forces the design of the coroutine. 502 503 Furthermore, \CFA faces an extra challenge as polymorphic routines create invisible thunks when cast 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: 573 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. 574 In the case of coroutines, this challenge is simpler since there is no non-determinism from preemption or scheduling. 575 However, the underlying challenge remains the same for coroutines and threads. 576 577 The runtime system needs to create the coroutine's stack and, more importantly, prepare it for the first resumption. 578 The timing of the creation is non-trivial since users expect both to have fully constructed objects once execution enters the coroutine main and to be able to resume the coroutine from the constructor. 579 There are several solutions to this problem but the chosen option effectively forces the design of the coroutine. 580 581 Furthermore, \CFA faces an extra challenge as polymorphic routines create invisible thunks when cast to non-polymorphic routines and these thunks have function scope. 582 For example, the following code, while looking benign, can run into undefined behaviour because of thunks: 504 583 505 584 \begin{cfacode} … … 534 613 } 535 614 \end{ccode} 536 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 behaviour; 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. 615 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 behaviour; i.e., the stack-based thunk being destroyed before it can be used. 616 This challenge is an extension of challenges that come with second-class routines. 617 Indeed, GCC nested routines also have the limitation that nested routine cannot be passed outside of the declaration scope. 618 The case of coroutines and threads is simply an extension of this problem to multiple call stacks. 537 619 538 620 \subsection{Alternative: Composition} … … 555 637 } 556 638 \end{cfacode} 557 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. 639 The downside of this approach is that users need to correctly construct the coroutine handle before using it. 640 Like any other objects, the user must carefully choose construction order to prevent usage of objects not yet constructed. 641 However, in the case of coroutines, users must also pass to the coroutine information about the coroutine main, like in the previous example. 642 This opens the door for user errors and requires extra runtime storage to pass at runtime information that can be known statically. 558 643 559 644 \subsection{Alternative: Reserved keyword} … … 565 650 }; 566 651 \end{cfacode} 567 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. 652 The \code{coroutine} keyword means the compiler can find and inject code where needed. 653 The downside of this approach is that it makes coroutine a special case in the language. 654 Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language. 655 Furthermore, implementing coroutines without language supports also displays the power of the programming language used. 656 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. 657 The reserved keywords are only present to improve ease of use for the common cases. 568 658 569 659 \subsection{Alternative: Lambda Objects} 570 660 571 For coroutines as for threads, many implementations are based on routine pointers or function objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}. For example, Boost implements coroutines in terms of four functor object types: 661 For coroutines as for threads, many implementations are based on routine pointers or function objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}. 662 For example, Boost implements coroutines in terms of four functor object types: 572 663 \begin{cfacode} 573 664 asymmetric_coroutine<>::pull_type … … 576 667 symmetric_coroutine<>::yield_type 577 668 \end{cfacode} 578 Often, the canonical threading paradigm in languages is based on function pointers, \texttt{pthread} being one of the most well-known examples. The main problem of this approach is that the thread usage is limited to a generic handle that must otherwise be wrapped in a custom type. Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda based coroutines adds very little. 669 Often, the canonical threading paradigm in languages is based on function pointers, \texttt{pthread} being one of the most well-known examples. 670 The main problem of this approach is that the thread usage is limited to a generic handle that must otherwise be wrapped in a custom type. 671 Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda based coroutines adds very little. 579 672 580 673 A variation of this would be to use a simple function pointer in the same way \texttt{pthread} does for threads: … … 591 684 } 592 685 \end{cfacode} 593 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. 686 This semantics is more common for thread interfaces but coroutines work equally well. 687 As discussed in section \ref{threads}, this approach is superseded by static approaches in terms of expressivity. 594 688 595 689 \subsection{Alternative: Trait-Based Coroutines} 596 690 597 Finally, the underlying approach, which is the one closest to \CFA idioms, is to use trait-based lazy coroutines. This approach defines a coroutine as anything that satisfies the trait \code{is_coroutine} (as defined below) and is used as a coroutine. 691 Finally, the underlying approach, which is the one closest to \CFA idioms, is to use trait-based lazy coroutines. 692 This approach defines a coroutine as anything that satisfies the trait \code{is_coroutine} (as defined below) and is used as a coroutine. 598 693 599 694 \begin{cfacode} … … 606 701 forall( dtype T | is_coroutine(T) ) void resume (T&); 607 702 \end{cfacode} 608 This ensures that 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} simply has the effect of implementing the getter and forward declarations required for users to implement the main routine. 703 This ensures that an object is not a coroutine until \code{resume} is called on the object. 704 Correspondingly, any object that is passed to \code{resume} is a coroutine since it must satisfy the \code{is_coroutine} trait to compile. 705 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. 706 The \CFA keyword \code{coroutine} simply has the effect of implementing the getter and forward declarations required for users to implement the main routine. 609 707 610 708 \begin{center} … … 635 733 636 734 \section{Thread Interface}\label{threads} 637 The basic building blocks of multithreading in \CFA are \textbf{cfathread}. Both user and kernel threads are supported, where user threads are the concurrency mechanism and kernel threads are the parallel mechanism. User threads offer a flexible and lightweight interface. A thread can be declared using a struct declaration \code{thread} as follows: 735 The basic building blocks of multithreading in \CFA are \textbf{cfathread}. 736 Both user and kernel threads are supported, where user threads are the concurrency mechanism and kernel threads are the parallel mechanism. 737 User threads offer a flexible and lightweight interface. 738 A thread can be declared using a struct declaration \code{thread} as follows: 638 739 639 740 \begin{cfacode} … … 651 752 \end{cfacode} 652 753 653 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 to use 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 754 Obviously, for this thread implementation to be useful it must run some user code. 755 Several other threading interfaces use a function-pointer representation as the interface of threads (for example \Csharp~\cite{Csharp} and Scala~\cite{Scala}). 756 However, this proposal considers that statically tying a \code{main} routine to a thread supersedes this approach. 757 Since the \code{main} routine is already a special routine in \CFA (where the program begins), it is a natural extension of the semantics to use overloading to declare mains for different threads (the normal main being the main of the initial thread). 758 As such the \code{main} routine of a thread can be defined as 654 759 \begin{cfacode} 655 760 thread foo {}; … … 660 765 \end{cfacode} 661 766 662 In this example, threads of type \code{foo} start execution in the \code{void main(foo &)} routine, which prints \code{"Hello World!".} While this paper encourages this approach to enforce strongly typed programming, users may prefer to use the routine-based thread semantics for the sake of simplicity. With the static semantics it is trivial to write a thread type that takes a function pointer as a parameter and executes it on its stack asynchronously. 767 In this example, threads of type \code{foo} start execution in the \code{void main(foo &)} routine, which prints \code{"Hello World!".} While this paper encourages this approach to enforce strongly typed programming, users may prefer to use the routine-based thread semantics for the sake of simplicity. 768 With the static semantics it is trivial to write a thread type that takes a function pointer as a parameter and executes it on its stack asynchronously. 663 769 \begin{cfacode} 664 770 typedef void (*voidFunc)(int); … … 691 797 A consequence of the strongly typed approach to main is that memory layout of parameters and return values to/from a thread are now explicitly specified in the \textbf{api}. 692 798 693 Of course, for threads to be useful, it must be possible to start and stop threads and wait for them to complete execution. While using an \textbf{api} such as \code{fork} and \code{join} is relatively common in the literature, such an interface is unnecessary. Indeed, the simplest approach is to use \textbf{raii} principles and have threads \code{fork} after the constructor has completed and \code{join} before the destructor runs. 799 Of course, for threads to be useful, it must be possible to start and stop threads and wait for them to complete execution. 800 While using an \textbf{api} such as \code{fork} and \code{join} is relatively common in the literature, such an interface is unnecessary. 801 Indeed, the simplest approach is to use \textbf{raii} principles and have threads \code{fork} after the constructor has completed and \code{join} before the destructor runs. 694 802 \begin{cfacode} 695 803 thread World; … … 732 840 \end{cfacode} 733 841 734 However, one of the drawbacks of this approach is that threads always form a tree where nodes must always outlive their children, i.e., they are always destroyed in the opposite order of construction because of C scoping rules. 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. 842 However, one of the drawbacks of this approach is that threads always form a tree where nodes must always outlive their children, i.e., they are always destroyed in the opposite order of construction because of C scoping rules. 843 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. 735 844 736 845 \begin{cfacode} … … 769 878 % ====================================================================== 770 879 % ====================================================================== 771 Several tools 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 calls). This distinction in turn means that, in order to be effective, programmers need to learn two sets of design patterns. While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account. 772 773 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}. 774 775 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 system languages, which is why it was rejected as the core paradigm for concurrency in \CFA. 776 777 One of the most natural, elegant, and efficient mechanisms for synchronization and communication, especially for shared-memory systems, is the \emph{monitor}. Monitors were first proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}. Many programming languages---e.g., Concurrent Pascal~\cite{ConcurrentPascal}, Mesa~\cite{Mesa}, Modula~\cite{Modula-2}, Turing~\cite{Turing:old}, Modula-3~\cite{Modula-3}, NeWS~\cite{NeWS}, Emerald~\cite{Emerald}, \uC~\cite{Buhr92a} and Java~\cite{Java}---provide monitors as explicit language constructs. In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as semaphores or locks to simulate monitors. For these reasons, this project proposes monitors as the core concurrency construct. 880 Several tools can be used to solve concurrency challenges. 881 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}). 882 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). 883 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 calls). 884 This distinction in turn means that, in order to be effective, programmers need to learn two sets of design patterns. 885 While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account. 886 887 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. 888 At the lowest level, concurrent paradigms are implemented as atomic operations and locks. 889 Many such mechanisms have been proposed, including semaphores~\cite{Dijkstra68b} and path expressions~\cite{Campbell74}. 890 However, for productivity reasons it is desirable to have a higher-level construct be the core concurrency paradigm~\cite{HPP:Study}. 891 892 An approach that is worth mentioning because it is gaining in popularity is transactional memory~\cite{Herlihy93}. 893 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 system languages, which is why it was rejected as the core paradigm for concurrency in \CFA. 894 895 One of the most natural, elegant, and efficient mechanisms for synchronization and communication, especially for shared-memory systems, is the \emph{monitor}. 896 Monitors were first proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}. 897 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. 898 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. 899 For these reasons, this project proposes monitors as the core concurrency construct. 778 900 779 901 \section{Basics} 780 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. 902 Non-determinism requires concurrent systems to offer support for mutual-exclusion and synchronization. 903 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. 904 On the other hand, synchronization enforces relative ordering of execution and synchronization tools provide numerous mechanisms to establish timing relationships among threads. 781 905 782 906 \subsection{Mutual-Exclusion} 783 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 concurrency techniques, 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. 907 As mentioned above, mutual-exclusion is the guarantee that only a fix number of threads can enter a critical section at once. 908 However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use. 909 Methods range from low-level locks, which are fast and flexible but require significant attention to be correct, to higher-level concurrency techniques, which sacrifice some performance in order to improve ease of use. 910 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. 911 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). 912 Another challenge with low-level locks is composability. 913 Locks have restricted composability because it takes careful organizing for multiple locks to be used while preventing deadlocks. 914 Easing composability is another feature higher-level mutual-exclusion mechanisms often offer. 784 915 785 916 \subsection{Synchronization} 786 As with mutual-exclusion, low-level synchronization primitives often offer good performance and good flexibility at the cost of ease of use. Again, higher-level mechanisms often simplify usage by adding either 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 \textbf{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 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. 917 As with mutual-exclusion, low-level synchronization primitives often offer good performance and good flexibility at the cost of ease of use. 918 Again, higher-level mechanisms often simplify usage by adding either better coupling between synchronization and data (e.g., message passing) or offering a simpler solution to otherwise involved challenges. 919 As mentioned above, synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}. 920 Most of the time, synchronization happens within a critical section, where threads must acquire mutual-exclusion in a certain order. 921 However, it may also be desirable to guarantee that event \textit{Z} does not occur between \textit{X} and \textit{Y}. 922 Not satisfying this property is called \textbf{barging}. 923 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}. 924 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 to acquire the resource. 925 Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs. 926 This challenge is often split into two different methods, barging avoidance and barging prevention. 927 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. 787 928 788 929 % ====================================================================== … … 791 932 % ====================================================================== 792 933 % ====================================================================== 793 A \textbf{monitor} is a set of routines that ensure mutual-exclusion when accessing shared state. More precisely, a monitor is a programming technique that associates mutual-exclusion to routine scopes, as opposed to mutex locks, where mutual-exclusion is defined by lock/release calls independently of any scoping of the calling routine. This strong association eases readability and maintainability, at the cost of flexibility. Note that both monitors and mutex locks, require an abstract handle to identify them. This concept is generally associated with object-oriented languages like Java~\cite{Java} or \uC~\cite{uC++book} but does not strictly require OO semantics. The only requirement is the ability to declare a handle to a shared object and a set of routines that act on it: 934 A \textbf{monitor} is a set of routines that ensure mutual-exclusion when accessing shared state. 935 More precisely, a monitor is a programming technique that associates mutual-exclusion to routine scopes, as opposed to mutex locks, where mutual-exclusion is defined by lock/release calls independently of any scoping of the calling routine. 936 This strong association eases readability and maintainability, at the cost of flexibility. 937 Note that both monitors and mutex locks, require an abstract handle to identify them. 938 This concept is generally associated with object-oriented languages like Java~\cite{Java} or \uC~\cite{uC++book} but does not strictly require OO semantics. 939 The only requirement is the ability to declare a handle to a shared object and a set of routines that act on it: 794 940 \begin{cfacode} 795 941 typedef /*some monitor type*/ monitor; … … 807 953 % ====================================================================== 808 954 % ====================================================================== 809 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 non-copy-able objects (\code{dtype}). 810 811 Another 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. Passthrough can occur for generic helper routines (\code{swap}, \code{sort}, etc.) or specific helper routines like the following to implement an atomic counter: 955 The above monitor example displays some of the intrinsic characteristics. 956 First, it is necessary to use pass-by-reference over pass-by-value for monitor routines. 957 This semantics is important, because at their core, monitors are implicit mutual-exclusion objects (locks), and these objects cannot be copied. 958 Therefore, monitors are non-copy-able objects (\code{dtype}). 959 960 Another aspect to consider is when a monitor acquires its mutual exclusion. 961 For example, a monitor may need to be passed through multiple helper routines that do not acquire the monitor mutual-exclusion on entry. 962 Passthrough can occur for generic helper routines (\code{swap}, \code{sort}, etc.) or specific helper routines like the following to implement an atomic counter: 812 963 813 964 \begin{cfacode} … … 838 989 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 the \CC template \code{std::atomic}. 839 990 840 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. 841 842 For maximum usability, monitors use \textbf{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 \textbf{multi-acq} to print values inside a binary tree. 991 Here, the constructor (\code{?\{\}}) uses the \code{nomutex} keyword to signify that it does not acquire the monitor mutual-exclusion when constructing. 992 This semantics is because an object not yet con\-structed should never be shared and therefore does not require mutual exclusion. 993 Furthermore, it allows the implementation greater freedom when it initializes the monitor locking. 994 The prefix increment operator uses \code{mutex} to protect the incrementing process from race conditions. 995 Finally, there is a conversion operator from \code{counter_t} to \code{size_t}. 996 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. 997 998 For maximum usability, monitors use \textbf{multi-acq} semantics, which means a single thread can acquire the same monitor multiple times without deadlock. 999 For example, listing \ref{fig:search} uses recursion and \textbf{multi-acq} to print values inside a binary tree. 843 1000 \begin{figure} 844 1001 \begin{cfacode}[caption={Recursive printing algorithm using \textbf{multi-acq}.},label={fig:search}] … … 858 1015 \end{figure} 859 1016 860 Having both \code{mutex} and \code{nomutex} keywords can be redundant, depending 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}. 861 862 The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. Consider the following declarations: 1017 Having both \code{mutex} and \code{nomutex} keywords can be redundant, depending on the meaning of a routine having neither of these keywords. 1018 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. 1019 On the other hand, \code{nomutex} is the ``normal'' parameter behaviour, it effectively states explicitly that ``this routine is not special''. 1020 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. 1021 Mandatory keywords would also have the added benefit of being self-documented but at the cost of extra typing. 1022 While there are several benefits to mandatory keywords, they do bring a few challenges. 1023 Mandatory keywords in \CFA would imply that the compiler must know without doubt whether or not a parameter is a monitor or not. 1024 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. 1025 For this reason, \CFA only has the \code{mutex} keyword and uses no keyword to mean \code{nomutex}. 1026 1027 The next semantic decision is to establish when \code{mutex} may be used as a type qualifier. 1028 Consider the following declarations: 863 1029 \begin{cfacode} 864 1030 int f1(monitor & mutex m); … … 868 1034 int f5(graph(monitor *) & mutex m); 869 1035 \end{cfacode} 870 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 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: 1036 The problem is to identify which object(s) should be acquired. 1037 Furthermore, each object needs to be acquired only once. 1038 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. 1039 Adding indirections (\code{f3}) still allows the compiler and programmer to identify which object is acquired. 1040 However, adding in arrays (\code{f4}) makes it much harder. 1041 Array lengths are not necessarily known in C, and even then, making sure objects are only acquired once becomes none-trivial. 1042 This problem can be extended to absurd limits like \code{f5}, which uses a graph of monitors. 1043 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). 1044 Also note that while routine \code{f3} can be supported, meaning that monitor \code{**m} is 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. 1045 However, this ambiguity is part of the C type-system with respects to arrays. 1046 For this reason, \code{mutex} is disallowed in the context where arrays may be passed: 871 1047 \begin{cfacode} 872 1048 int f1(monitor & mutex m); //Okay : recommended case … … 876 1052 int f5(monitor * mutex m []); //Not Okay : Array of unknown length 877 1053 \end{cfacode} 878 Note 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. 879 880 Unlike object-oriented monitors, where calling a mutex member \emph{implicitly} acquires mutual-exclusion of the receiver object, \CFA uses an explicit mechanism to specify the object that acquires mutual-exclusion. A consequence of this approach is that it extends naturally to multi-monitor calls. 1054 Note that not all array functions are actually distinct in the type system. 1055 However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic. 1056 1057 Unlike object-oriented monitors, where calling a mutex member \emph{implicitly} acquires mutual-exclusion of the receiver object, \CFA uses an explicit mechanism to specify the object that acquires mutual-exclusion. 1058 A consequence of this approach is that it extends naturally to multi-monitor calls. 881 1059 \begin{cfacode} 882 1060 int f(MonitorA & mutex a, MonitorB & mutex b); … … 886 1064 f(a,b); 887 1065 \end{cfacode} 888 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{\textbf{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 \textbf{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: 1066 While OO monitors could be extended with a mutex qualifier for multiple-monitor calls, no example of this feature could be found. 1067 The capability to acquire multiple locks before entering a critical section is called \emph{\textbf{bulk-acq}}. 1068 In practice, writing multi-locking routines that do not lead to deadlocks is tricky. 1069 Having language support for such a feature is therefore a significant asset for \CFA. 1070 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. 1071 This consistent ordering means acquiring multiple monitors is safe from deadlock when using \textbf{bulk-acq}. 1072 However, users can still force the acquiring order. 1073 For example, notice which routines use \code{mutex}/\code{nomutex} and how this affects acquiring order: 889 1074 \begin{cfacode} 890 1075 void foo(A& mutex a, B& mutex b) { //acquire a & b … … 900 1085 } 901 1086 \end{cfacode} 902 The \textbf{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. 903 904 However, such use leads to lock acquiring order problems. 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 behaviour. As shown~\cite{Lister77}, solving this problem requires: 1087 The \textbf{multi-acq} monitor lock allows a monitor lock to be acquired by both \code{bar} or \code{baz} and acquired again in \code{foo}. 1088 In the calls to \code{bar} and \code{baz} the monitors are acquired in opposite order. 1089 1090 However, such use leads to lock acquiring order problems. 1091 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}. 1092 This subtle difference means that calling these routines concurrently may lead to deadlock and is therefore undefined behaviour. 1093 As shown~\cite{Lister77}, solving this problem requires: 905 1094 \begin{enumerate} 906 1095 \item Dynamically tracking the monitor-call order. 907 1096 \item Implement rollback semantics. 908 1097 \end{enumerate} 909 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 \textbf{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. 1098 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}. 1099 In \CFA, users simply need to be careful when acquiring multiple monitors at the same time or only use \textbf{bulk-acq} of all the monitors. 1100 While \CFA provides only a partial solution, most systems provide no solution and the \CFA partial solution handles many useful cases. 910 1101 911 1102 For example, \textbf{multi-acq} and \textbf{bulk-acq} can be used together in interesting ways: … … 920 1111 } 921 1112 \end{cfacode} 922 This example shows a trivial solution to the bank-account transfer problem~\cite{BankTransfer}. Without \textbf{multi-acq} and \textbf{bulk-acq}, the solution to this problem is much more involved and requires careful engineering. 1113 This example shows a trivial solution to the bank-account transfer problem~\cite{BankTransfer}. 1114 Without \textbf{multi-acq} and \textbf{bulk-acq}, the solution to this problem is much more involved and requires careful engineering. 923 1115 924 1116 \subsection{\code{mutex} statement} \label{mutex-stmt} 925 1117 926 The call semantics discussed above have one software engineering issue: only a routine can acquire the mutual-exclusion of a set of monitor. \CFA offers the \code{mutex} statement to work around 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. 1118 The call semantics discussed above have one software engineering issue: only a routine can acquire the mutual-exclusion of a set of monitor. \CFA offers the \code{mutex} statement to work around the need for unnecessary names, avoiding a major software engineering problem~\cite{2FTwoHardThings}. 1119 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. 1120 Beyond naming, the \code{mutex} statement has no semantic difference from a routine call with \code{mutex} parameters. 927 1121 928 1122 \begin{table} … … 961 1155 % ====================================================================== 962 1156 % ====================================================================== 963 Once the call semantics are established, the next step is to establish data semantics. Indeed, until now a monitor is used simply as a generic handle but in most cases monitors contain shared data. This data should be intrinsic to the monitor declaration to prevent any accidental use of data without its appropriate protection. For example, here is a complete version of the counter shown in section \ref{call}: 1157 Once the call semantics are established, the next step is to establish data semantics. 1158 Indeed, until now a monitor is used simply as a generic handle but in most cases monitors contain shared data. 1159 This data should be intrinsic to the monitor declaration to prevent any accidental use of data without its appropriate protection. 1160 For example, here is a complete version of the counter shown in section \ref{call}: 964 1161 \begin{cfacode} 965 1162 monitor counter_t { … … 981 1178 \end{cfacode} 982 1179 983 Like threads and coroutines, monitors are defined in terms of traits with some additional language support in the form of the \code{monitor} keyword. The monitor trait is: 1180 Like threads and coroutines, monitors are defined in terms of traits with some additional language support in the form of the \code{monitor} keyword. 1181 The monitor trait is: 984 1182 \begin{cfacode} 985 1183 trait is_monitor(dtype T) { … … 988 1186 }; 989 1187 \end{cfacode} 990 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. 1188 Note that the destructor of a monitor must be a \code{mutex} routine to prevent deallocation while a thread is accessing the monitor. 1189 As with any object, calls to a monitor, using \code{mutex} or otherwise, is undefined behaviour after the destructor has run. 991 1190 992 1191 % ====================================================================== … … 995 1194 % ====================================================================== 996 1195 % ====================================================================== 997 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}. With \textbf{scheduling} loosely defined as deciding which thread acquires the critical section next, \textbf{internal scheduling} means making the decision from inside the critical section (i.e., with access to the shared state), while \textbf{external scheduling} means making the decision when entering the critical section (i.e., without access to the shared state). Since internal scheduling within a single monitor is mostly a solved problem, this paper concentrates on extending internal scheduling to multiple monitors. Indeed, like the \textbf{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. 1196 In addition to mutual exclusion, the monitors at the core of \CFA's concurrency can also be used to achieve synchronization. 1197 With monitors, this capability is generally achieved with internal or external scheduling as in~\cite{Hoare74}. 1198 With \textbf{scheduling} loosely defined as deciding which thread acquires the critical section next, \textbf{internal scheduling} means making the decision from inside the critical section (i.e., with access to the shared state), while \textbf{external scheduling} means making the decision when entering the critical section (i.e., without access to the shared state). 1199 Since internal scheduling within a single monitor is mostly a solved problem, this paper concentrates on extending internal scheduling to multiple monitors. 1200 Indeed, like the \textbf{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. 998 1201 999 1202 First, here is a simple example of internal scheduling: … … 1018 1221 } 1019 1222 \end{cfacode} 1020 There are two details to note here. First, \code{signal} is a delayed operation; it only unblocks the waiting thread when it reaches the end of the critical section. This semantics 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, ensuring a basic ordering. 1021 1022 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 be the next thread to acquire the monitor (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 and implementation of \CFA concurrency. 1223 There are two details to note here. 1224 First, \code{signal} is a delayed operation; it only unblocks the waiting thread when it reaches the end of the critical section. 1225 This semantics is needed to respect mutual-exclusion, i.e., the signaller and signalled thread cannot be in the monitor simultaneously. 1226 The alternative is to return immediately after the call to \code{signal}, which is significantly more restrictive. 1227 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. 1228 Here routine \code{foo} waits for the \code{signal} from \code{bar} before making further progress, ensuring a basic ordering. 1229 1230 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 be the next thread to acquire the monitor (unless some other thread waited on the same condition). 1231 This guarantee offers the benefit of not having to loop around waits to recheck that a condition is met. 1232 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. 1233 Supporting barging prevention as well as extending internal scheduling to multiple monitors is the main source of complexity in the design and implementation of \CFA concurrency. 1023 1234 1024 1235 % ====================================================================== … … 1027 1238 % ====================================================================== 1028 1239 % ====================================================================== 1029 It is easy 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 parameters and explicitly name 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. 1240 It is easy to understand the problem of multi-monitor scheduling using a series of pseudo-code examples. 1241 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. 1242 Indeed, \code{wait} statements always use the implicit condition variable as parameters and explicitly name the monitors (A and B) associated with the condition. 1243 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. 1244 The example below shows the simple case of having two threads (one for each column) and a single monitor A. 1030 1245 1031 1246 \begin{multicols}{2} … … 1046 1261 \end{pseudo} 1047 1262 \end{multicols} 1048 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. 1263 One thread acquires before waiting (atomically blocking and releasing A) and the other acquires before signalling. 1264 It is important to note here that both \code{wait} and \code{signal} must be called with the proper monitor(s) already acquired. 1265 This semantic is a logical requirement for barging prevention. 1049 1266 1050 1267 A direct extension of the previous example is a \textbf{bulk-acq} version: … … 1062 1279 \end{pseudo} 1063 1280 \end{multicols} 1064 \noindent This version uses \textbf{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 a group of monitors. On the implementation side, handling multiple monitors does add a degree of complexity as the next few examples demonstrate. 1065 1066 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: 1281 \noindent This version uses \textbf{bulk-acq} (denoted using the {\sf\&} symbol), but the presence of multiple monitors does not add a particularly new meaning. 1282 Synchronization happens between the two threads in exactly the same way and order. 1283 The only difference is that mutual exclusion covers a group of monitors. 1284 On the implementation side, handling multiple monitors does add a degree of complexity as the next few examples demonstrate. 1285 1286 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. 1287 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. 1288 For example, the following pseudo-code runs into the nested-monitor problem: 1067 1289 \begin{multicols}{2} 1068 1290 \begin{pseudo} … … 1084 1306 \end{pseudo} 1085 1307 \end{multicols} 1086 \noindent 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}. 1087 1088 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}. 1308 \noindent The \code{wait} only releases monitor \code{B} so the signalling thread cannot acquire monitor \code{A} to get to the \code{signal}. 1309 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}. 1310 1311 However, for monitors as for locks, it is possible to write a program using nesting without encountering any problems if nesting is done correctly. 1312 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}. 1089 1313 1090 1314 \begin{multicols}{2} … … 1116 1340 % ====================================================================== 1117 1341 1118 A larger example is presented to show complex issues for \textbf{bulk-acq} and its implementation options are analyzed. Listing \ref{lst:int-bulk-pseudo} shows an example where \textbf{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} parameters, global variables, pointer parameters, or using locals with the \code{mutex} statement. 1342 A larger example is presented to show complex issues for \textbf{bulk-acq} and its implementation options are analyzed. 1343 Listing \ref{lst:int-bulk-pseudo} shows an example where \textbf{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}. 1344 For the purpose of translating the given pseudo-code into \CFA-code, any method of introducing a monitor is acceptable, e.g., \code{mutex} parameters, global variables, pointer parameters, or using locals with the \code{mutex} statement. 1119 1345 1120 1346 \begin{figure}[!t] … … 1211 1437 \end{figure} 1212 1438 1213 The complexity begins at code sections 4 and 8 in listing \ref{lst:int-bulk-pseudo}, which are where the existing semantics of internal scheduling needs to be extended for multiple monitors. The root of the problem is that \textbf{bulk-acq} is used in a context where one of the monitors is already acquired, which 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:releaseFirst}), 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: 1439 The complexity begins at code sections 4 and 8 in listing \ref{lst:int-bulk-pseudo}, which are where the existing semantics of internal scheduling needs to be extended for multiple monitors. 1440 The root of the problem is that \textbf{bulk-acq} is used in a context where one of the monitors is already acquired, which is why it is important to define the behaviour of the previous pseudo-code. 1441 When the signaller thread reaches the location where it should ``release \code{A & B}'' (listing \ref{lst:int-bulk-pseudo} line \ref{line:releaseFirst}), it must actually transfer ownership of monitor \code{B} to the waiting thread. 1442 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}. 1443 There are three options: 1214 1444 1215 1445 \subsubsection{Delaying Signals} 1216 The obvious solution to 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. This solution releases the monitors once every monitor in a group can be released. However, since some monitors are never released (e.g., the monitor of a thread), this interpretation means a group might never be released. A more interesting interpretation is to transfer the group until all its monitors are released, which means the group is not passed further and a thread can retain its locks. 1217 1218 However, listing \ref{lst:int-secret} shows this solution can become much more complicated depending on what is executed while secretly holding B at line \ref{line:secret}, while avoiding the need to transfer ownership of a subset of the condition monitors. 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: 1446 The obvious solution to the problem of multi-monitor scheduling is to keep ownership of all locks until the last lock is ready to be transferred. 1447 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. 1448 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. 1449 This solution releases the monitors once every monitor in a group can be released. 1450 However, since some monitors are never released (e.g., the monitor of a thread), this interpretation means a group might never be released. 1451 A more interesting interpretation is to transfer the group until all its monitors are released, which means the group is not passed further and a thread can retain its locks. 1452 1453 However, listing \ref{lst:int-secret} shows this solution can become much more complicated depending on what is executed while secretly holding B at line \ref{line:secret}, while avoiding the need to transfer ownership of a subset of the condition monitors. 1454 Listing \ref{lst:dependency} shows a slightly different example where a third thread is waiting on monitor \code{A}, using a different condition variable. 1455 Because the third thread is signalled when secretly holding \code{B}, the goal becomes unreachable. 1456 Depending on the order of signals (listing \ref{lst:dependency} line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen: 1219 1457 1220 1458 \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. … … 1222 1460 \\ 1223 1461 1224 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}. 1462 Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order. 1463 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}. 1225 1464 1226 1465 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 knowing when to release a group becomes complex and inefficient (see next section) and therefore effectively precludes this approach. … … 1266 1505 \end{figure} 1267 1506 1268 In listing \ref{lst:int-bulk-pseudo}, 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 has a super-linear complexity. This complexity 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. 1507 In listing \ref{lst:int-bulk-pseudo}, there is a solution that satisfies both barging prevention and mutual exclusion. 1508 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). 1509 Dynamically finding the correct order is therefore the second possible solution. 1510 The problem is effectively resolving a dependency graph of ownership requirements. 1511 Here even the simplest of code snippets requires two transfers and has a super-linear complexity. 1512 This complexity 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. 1513 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. 1269 1514 \begin{figure} 1270 1515 \begin{multicols}{2} … … 1295 1540 \end{figure} 1296 1541 1297 Given the three threads example in listing \ref{lst:dependency}, 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 dependencies unfold. Resolving dependency graphs being a complex and expensive endeavour, this solution is not the preferred one. 1542 Given the three threads example in listing \ref{lst:dependency}, 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$). 1543 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 dependencies unfold. 1544 Resolving dependency graphs being a complex and expensive endeavour, this solution is not the preferred one. 1298 1545 1299 1546 \subsubsection{Partial Signalling} \label{partial-sig} 1300 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 wake up 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 algorithms, which is why it was chosen. Furthermore, after being fully implemented, this solution does not appear to have any significant downsides. 1547 Finally, the solution that is chosen for \CFA is to use partial signalling. 1548 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}. 1549 Only when it reaches line \ref{line:lastRelease} does it actually wake up the waiting thread. 1550 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. 1551 This solution has a much simpler implementation than a dependency graph solving algorithms, which is why it was chosen. 1552 Furthermore, after being fully implemented, this solution does not appear to have any significant downsides. 1301 1553 1302 1554 Using partial signalling, listing \ref{lst:dependency} can be solved easily: … … 1415 1667 \label{tbl:datingservice} 1416 1668 \end{table} 1417 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. 1418 1419 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 front 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. 1669 An important note is that, until now, signalling a monitor was a delayed operation. 1670 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. 1671 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. 1672 1673 The example in table \ref{tbl:datingservice} highlights the difference in behaviour. 1674 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. 1675 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. 1676 This feature removes the need for a second condition variables and simplifies programming. 1677 Like every other monitor semantic, \code{signal_block} uses barging prevention, which means mutual-exclusion is baton-passed both on the front 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. 1420 1678 1421 1679 % ====================================================================== … … 1488 1746 \label{tbl:sched} 1489 1747 \end{table} 1490 This method is more constrained and explicit, which helps users reduce the non-deterministic nature of concurrency. Indeed, as the following examples demonstrate, 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 was 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 \textbf{api}s. 1491 1492 For 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 other routine than \code{V} can acquire the monitor. 1748 This method is more constrained and explicit, which helps users reduce the non-deterministic nature of concurrency. 1749 Indeed, as the following examples demonstrate, external scheduling allows users to wait for events from other threads without the concern of unrelated events occurring. 1750 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). 1751 Of course, both of these paradigms have their own strengths and weaknesses, but for this project, control-flow semantics was chosen to stay consistent with the rest of the languages semantics. 1752 Two challenges specific to \CFA arise when trying to add external scheduling with loose object definitions and multiple-monitor routines. 1753 The previous example shows a simple use \code{_Accept} versus \code{wait}/\code{signal} and its advantages. 1754 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 \textbf{api}s. 1755 1756 For 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. 1757 On the other hand, external scheduling guarantees that while routine \code{P} is waiting, no other routine than \code{V} can acquire the monitor. 1493 1758 1494 1759 % ====================================================================== … … 1497 1762 % ====================================================================== 1498 1763 % ====================================================================== 1499 In \uC, a monitor class declaration includes 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: 1764 In \uC, a monitor class declaration includes an exhaustive list of monitor operations. 1765 Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user: 1500 1766 1501 1767 \begin{cfacode} … … 1513 1779 \end{cfacode} 1514 1780 1515 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: 1781 Furthermore, external scheduling is an example where implementation constraints become visible from the interface. 1782 Here is the pseudo-code for the entering phase of a monitor: 1516 1783 \begin{center} 1517 1784 \begin{tabular}{l} … … 1528 1795 \end{tabular} 1529 1796 \end{center} 1530 For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions. 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 Figure~\ref{fig:ClassicalMonitor}. 1797 For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions. 1798 However, a fast check for \pscode{monitor accepts me} is much harder to implement depending on the constraints put on the monitors. 1799 Indeed, monitors are often expressed as an entry queue and some acceptor queue as in Figure~\ref{fig:ClassicalMonitor}. 1531 1800 1532 1801 \begin{figure} … … 1544 1813 \end{figure} 1545 1814 1546 There are other alternatives to these pictures, but in the case of the left 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 unique dense 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 inheritance. 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. 1815 There are other alternatives to these pictures, but in the case of the left picture, implementing a fast accept check is relatively easy. 1816 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. 1817 This approach requires a unique dense ordering of routines with an upper-bound and that ordering must be consistent across translation units. 1818 For OO languages these constraints are common, since objects only offer adding member routines consistently across translation units via inheritance. 1819 However, in \CFA users can extend objects with mutex routines that are only visible in certain translation unit. 1820 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. 1547 1821 1548 1822 The alternative is to alter the implementation as in Figure~\ref{fig:BulkMonitor}. 1549 Here, the mutex routine called is associated with a thread on the entry queue while a list of acceptable routines is kept separate. 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 comparison 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. 1823 Here, the mutex routine called is associated with a thread on the entry queue while a list of acceptable routines is kept separate. 1824 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. 1825 Storing an array of accepted function pointers replaces the single instruction bitmask comparison with dereferencing a pointer followed by a linear search. 1826 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. 1550 1827 1551 1828 \begin{figure} … … 1564 1841 \end{figure} 1565 1842 1566 Note that in the right 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 discussed in the next section. These details are omitted from the picture for the sake of simplicity. 1567 1568 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 problem than writing locks that are as flexible as external scheduling in \CFA. 1843 Note that in the right 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 discussed in the next section. 1844 These details are omitted from the picture for the sake of simplicity. 1845 1846 At this point, a decision must be made between flexibility and performance. 1847 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. 1848 Here, however, the cost of flexibility cannot be trivially removed. 1849 In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be hard to write. 1850 This decision is based on the assumption that writing fast but inflexible locks is closer to a solved problem than writing locks that are as flexible as external scheduling in \CFA. 1569 1851 1570 1852 % ====================================================================== … … 1574 1856 % ====================================================================== 1575 1857 1576 External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax. Even in the simplest possible case, some new semantics needs to be established: 1858 External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax. 1859 Even in the simplest possible case, some new semantics needs to be established: 1577 1860 \begin{cfacode} 1578 1861 monitor M {}; … … 1596 1879 } 1597 1880 \end{cfacode} 1598 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. 1881 This syntax is unambiguous. 1882 Both locks are acquired and kept by \code{g}. 1883 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}). 1884 This behaviour can be extended to the multi-monitor \code{waitfor} statement as follows. 1599 1885 1600 1886 \begin{cfacode} … … 1633 1919 } 1634 1920 \end{cfacode} 1635 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 wakeup 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. 1921 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. 1922 In both cases, partially matching monitor sets does not wakeup the waiting thread. 1923 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. 1636 1924 1637 1925 % ====================================================================== … … 1641 1929 % ====================================================================== 1642 1930 1643 Syntactically, the \code{waitfor} statement takes a function identifier and a set of monitors. While the set of monitors can be any list of expressions, 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 usages 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. 1931 Syntactically, the \code{waitfor} statement takes a function identifier and a set of monitors. 1932 While the set of monitors can be any list of expressions, 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. 1933 It checks that the set of monitors passed in matches the requirements for a function call. 1934 Listing \ref{lst:waitfor} shows various usages of the waitfor statement and which are acceptable. 1935 The choice of the function type is made ignoring any non-\code{mutex} parameter. 1936 One limitation of the current implementation is that it does not handle overloading, but overloading is possible. 1644 1937 \begin{figure} 1645 1938 \begin{cfacode}[caption={Various correct and incorrect uses of the waitfor statement},label={lst:waitfor}] … … 1675 1968 \end{figure} 1676 1969 1677 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 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. 1970 Finally, for added flexibility, \CFA supports constructing a complex \code{waitfor} statement using the \code{or}, \code{timeout} and \code{else}. 1971 Indeed, multiple \code{waitfor} clauses can be chained together using \code{or}; this chain forms a single statement that uses baton pass to any function that fits one of the function+monitor set passed in. 1972 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. 1973 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. 1974 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. 1975 Listing \ref{lst:waitfor2} demonstrates several complex masks and some incorrect ones. 1678 1976 1679 1977 \begin{figure} … … 1743 2041 % ====================================================================== 1744 2042 % ====================================================================== 1745 An 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 ordering of execution 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. 2043 An interesting use for the \code{waitfor} statement is destructor semantics. 2044 Indeed, the \code{waitfor} statement can accept any \code{mutex} routine, which includes the destructor (see section \ref{data}). 2045 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. 2046 The simplest approach is to disallow \code{waitfor} on a destructor. 2047 However, a more expressive approach is to flip ordering of execution 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. 1746 2048 \begin{figure} 1747 2049 \begin{cfacode}[caption={Example of an executor which executes action in series until the destructor is called.},label={lst:dtor-order}] … … 1761 2063 \end{cfacode} 1762 2064 \end{figure} 1763 For 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. 2065 For 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. 2066 Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction. 1764 2067 1765 2068 … … 1772 2075 % # # # # # # # ####### ####### ####### ####### ### ##### # # 1773 2076 \section{Parallelism} 1774 Historically, computer performance was about processor speeds and instruction counts. 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 no 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 \textbf{kthread} in combination with semantics like \code{fork}, \code{join}, etc. However, since these have significant costs and limitations, \textbf{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. 2077 Historically, computer performance was about processor speeds and instruction counts. 2078 However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}. 2079 In this decade, it is no longer reasonable to create a high-performance application without caring about parallelism. 2080 Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization. 2081 The lowest-level approach of parallelism is to use \textbf{kthread} in combination with semantics like \code{fork}, \code{join}, etc. 2082 However, since these have significant costs and limitations, \textbf{kthread} are now mostly used as an implementation tool rather than a user oriented one. 2083 There are several alternatives to solve these issues that all have strengths and weaknesses. 2084 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. 1775 2085 1776 2086 \section{Paradigms} 1777 2087 \subsection{User-Level Threads} 1778 A direct improvement on the \textbf{kthread} approach is to use \textbf{uthread}. These threads offer most of the same features that the operating system already provides but can be used on a much larger scale. This approach is the most powerful solution as it allows all the features of multithreading, while removing several of the more expensive costs of kernel threads. The downside 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. 2088 A direct improvement on the \textbf{kthread} approach is to use \textbf{uthread}. 2089 These threads offer most of the same features that the operating system already provides but can be used on a much larger scale. 2090 This approach is the most powerful solution as it allows all the features of multithreading, while removing several of the more expensive costs of kernel threads. 2091 The downside is that almost none of the low-level threading problems are hidden; users still have to think about data races, deadlocks and synchronization issues. 2092 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. 1779 2093 1780 2094 Examples of languages that support \textbf{uthread} are Erlang~\cite{Erlang} and \uC~\cite{uC++book}. 1781 2095 1782 2096 \subsection{Fibers : User-Level Threads Without Preemption} \label{fibers} 1783 A popular variant of \textbf{uthread} is what is often referred to as \textbf{fiber}. However, \textbf{fiber} do not present meaningful semantic differences with \textbf{uthread}. The significant difference between \textbf{uthread} and \textbf{fiber} is the lack of \textbf{preemption} in the latter. Advocates of \textbf{fiber} list their high performance and ease of implementation as major strengths, but the performance difference between \textbf{uthread} and \textbf{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. 2097 A popular variant of \textbf{uthread} is what is often referred to as \textbf{fiber}. 2098 However, \textbf{fiber} do not present meaningful semantic differences with \textbf{uthread}. 2099 The significant difference between \textbf{uthread} and \textbf{fiber} is the lack of \textbf{preemption} in the latter. 2100 Advocates of \textbf{fiber} list their high performance and ease of implementation as major strengths, but the performance difference between \textbf{uthread} and \textbf{fiber} is controversial, and the ease of implementation, while true, is a weak argument in the context of language design. 2101 Therefore this proposal largely ignores fibers. 1784 2102 1785 2103 An example of a language that uses fibers is Go~\cite{Go} 1786 2104 1787 2105 \subsection{Jobs and Thread Pools} 1788 An approach on the opposite end of the spectrum is to base parallelism on \textbf{pool}. Indeed, \textbf{pool} offer limited flexibility but at the benefit of a simpler user interface. In \textbf{pool} based systems, users express parallelism as units of work, called jobs, and a dependency graph (either explicit or implicit) that ties them together. This approach means users need not worry about concurrency but significantly limit the interaction that can occur among jobs. Indeed, any \textbf{job} that blocks also block the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably. It can be argued that a solution to this problem is to use more workers than available cores. However, unless the number of jobs and the number of workers are comparable, having a significant number of blocked jobs always results in idles cores. 2106 An approach on the opposite end of the spectrum is to base parallelism on \textbf{pool}. 2107 Indeed, \textbf{pool} offer limited flexibility but at the benefit of a simpler user interface. 2108 In \textbf{pool} based systems, users express parallelism as units of work, called jobs, and a dependency graph (either explicit or implicit) that ties them together. 2109 This approach means users need not worry about concurrency but significantly limit the interaction that can occur among jobs. 2110 Indeed, any \textbf{job} that blocks also block the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably. 2111 It can be argued that a solution to this problem is to use more workers than available cores. 2112 However, unless the number of jobs and the number of workers are comparable, having a significant number of blocked jobs always results in idles cores. 1789 2113 1790 2114 The gold standard of this implementation is Intel's TBB library~\cite{TBB}. 1791 2115 1792 2116 \subsection{Paradigm Performance} 1793 While the choice between the three paradigms listed above may have significant performance implications, 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 equivalent performance across paradigms and that the \textbf{pool}-based system has the best efficiency 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. 2117 While the choice between the three paradigms listed above may have significant performance implications, it is difficult to pin down the performance implications of choosing a model at the language level. 2118 Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload. 2119 Having a large amount of mostly independent units of work to execute almost guarantees equivalent performance across paradigms and that the \textbf{pool}-based system has the best efficiency thanks to the lower memory overhead (i.e., no thread stack per job). 2120 However, interactions among jobs can easily exacerbate contention. 2121 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. 2122 Finally, if the units of uninterrupted work are large, enough the paradigm choice is largely amortized by the actual work done. 1794 2123 1795 2124 \section{The \protect\CFA\ Kernel : Processors, Clusters and Threads}\label{kernel} 1796 A \textbf{cfacluster} is a group of \textbf{kthread} executed in isolation. \textbf{uthread} are scheduled on the \textbf{kthread} of a given \textbf{cfacluster}, allowing organization between \textbf{uthread} and \textbf{kthread}. It is important that \textbf{kthread} belonging to a same \textbf{cfacluster} have homogeneous settings, otherwise migrating a \textbf{uthread} from one \textbf{kthread} to the other can cause issues. A \textbf{cfacluster} also offers a pluggable scheduler that can optimize the workload generated by the \textbf{uthread}. 1797 1798 \textbf{cfacluster} have not been fully implemented in the context of this paper. Currently \CFA only supports one \textbf{cfacluster}, the initial one. 2125 A \textbf{cfacluster} is a group of \textbf{kthread} executed in isolation. \textbf{uthread} are scheduled on the \textbf{kthread} of a given \textbf{cfacluster}, allowing organization between \textbf{uthread} and \textbf{kthread}. 2126 It is important that \textbf{kthread} belonging to a same \textbf{cfacluster} have homogeneous settings, otherwise migrating a \textbf{uthread} from one \textbf{kthread} to the other can cause issues. 2127 A \textbf{cfacluster} also offers a pluggable scheduler that can optimize the workload generated by the \textbf{uthread}. 2128 2129 \textbf{cfacluster} have not been fully implemented in the context of this paper. 2130 Currently \CFA only supports one \textbf{cfacluster}, the initial one. 1799 2131 1800 2132 \subsection{Future Work: Machine Setup}\label{machine} 1801 While this was not done in the context of this paper, 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 \textbf{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. 2133 While this was not done in the context of this paper, another important aspect of clusters is affinity. 2134 While many common desktop and laptop PCs have homogeneous CPUs, other devices often have more heterogeneous setups. 2135 For example, a system using \textbf{numa} configurations may benefit from users being able to tie clusters and/or kernel threads to certain CPU cores. 2136 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. 1802 2137 1803 2138 \subsection{Paradigms}\label{cfaparadigms} 1804 Given these building blocks, it is possible to reproduce all three of the popular paradigms. Indeed, \textbf{uthread} is the default paradigm in \CFA. However, disabling \textbf{preemption} on the \textbf{cfacluster} means \textbf{cfathread} effectively become \textbf{fiber}. Since several \textbf{cfacluster} with different scheduling policy can coexist in the same application, this allows \textbf{fiber} and \textbf{uthread} to coexist in the runtime of an application. Finally, it is possible to build executors for thread pools from \textbf{uthread} or \textbf{fiber}, which includes specialized jobs like actors~\cite{Actors}. 2139 Given these building blocks, it is possible to reproduce all three of the popular paradigms. 2140 Indeed, \textbf{uthread} is the default paradigm in \CFA. 2141 However, disabling \textbf{preemption} on the \textbf{cfacluster} means \textbf{cfathread} effectively become \textbf{fiber}. 2142 Since several \textbf{cfacluster} with different scheduling policy can coexist in the same application, this allows \textbf{fiber} and \textbf{uthread} to coexist in the runtime of an application. 2143 Finally, it is possible to build executors for thread pools from \textbf{uthread} or \textbf{fiber}, which includes specialized jobs like actors~\cite{Actors}. 1805 2144 1806 2145 1807 2146 1808 2147 \section{Behind the Scenes} 1809 There are several challenges specific to \CFA when implementing concurrency. These challenges are a direct result of \textbf{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. 1810 1811 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 node 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 \textbf{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 call stack 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 on scopes, 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 \code{mutex} routines and blocking calls allow for an unbound amount, within the stack size. 2148 There are several challenges specific to \CFA when implementing concurrency. 2149 These challenges are a direct result of \textbf{bulk-acq} and loose object definitions. 2150 These two constraints are the root cause of most design decisions in the implementation. 2151 Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs. 2152 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. 2153 This extra goal means that memory management is a constant concern in the design of the system. 2154 2155 The main memory concern for concurrency is queues. 2156 All blocking operations are made by parking threads onto queues and all queues are designed with intrusive nodes, where each node has pre-allocated link fields for chaining, to avoid the need for memory allocation. 2157 Since several concurrency operations can use an unbound amount of memory (depending on \textbf{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. 2158 Conveniently, the call stack 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. 2159 Since stack allocation is based on scopes, 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. 2160 The threads and the condition both have a fixed amount of memory, while \code{mutex} routines and blocking calls allow for an unbound amount, within the stack size. 1812 2161 1813 2162 Note that since the major contributions of this paper are extending monitor semantics to \textbf{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. … … 1819 2168 % ====================================================================== 1820 2169 1821 The first step towards the monitor implementation is simple \code{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 behaviour. 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. 2170 The first step towards the monitor implementation is simple \code{mutex} routines. 2171 In the single monitor case, mutual-exclusion is done using the entry/exit procedure in listing \ref{lst:entry1}. 2172 The entry/exit procedures do not have to be extended to support multiple monitors. 2173 Indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlock~\cite{Havender68}. 2174 In \CFA, ordering of monitor acquisition relies on memory ordering. 2175 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 behaviour. 2176 When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer array and sorted based on pointer values. 2177 This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively. 1822 2178 \begin{figure} 1823 2179 \begin{multicols}{2} … … 1846 2202 1847 2203 \subsection{Details: Interaction with polymorphism} 1848 Depending 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. 1849 1850 First of all, interaction between \code{otype} polymorphism (see Section~\ref{s:ParametricPolymorphism}) 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: \textbf{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: 2204 Depending 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. 2205 However, it is shown that entry-point locking solves most of the issues. 2206 2207 First of all, interaction between \code{otype} polymorphism (see Section~\ref{s:ParametricPolymorphism}) and monitors is impossible since monitors do not support copying. 2208 Therefore, the main question is how to support \code{dtype} polymorphism. 2209 It is important to present the difference between the two acquiring options: \textbf{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. 2210 For example: 1851 2211 \begin{table}[H] 1852 2212 \begin{center} … … 1915 2275 \end{cfacode} 1916 2276 1917 Both entry point and \textbf{callsite-locking} are feasible implementations. The current \CFA implementation uses entry-point locking because it requires less work when using \textbf{raii}, effectively transferring the burden of implementation to object construction/destruction. It is harder to use \textbf{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 is called multiple times but there is only one entry point for many call sites. 2277 Both entry point and \textbf{callsite-locking} are feasible implementations. 2278 The current \CFA implementation uses entry-point locking because it requires less work when using \textbf{raii}, effectively transferring the burden of implementation to object construction/destruction. 2279 It is harder to use \textbf{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. 2280 For example, the monitor call can appear in the middle of an expression. 2281 Furthermore, entry-point locking requires less code generation since any useful routine is called multiple times but there is only one entry point for many call sites. 1918 2282 1919 2283 % ====================================================================== … … 1923 2287 % ====================================================================== 1924 2288 1925 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 detail in the flowing sections. 2289 Figure \ref{fig:system1} shows a high-level picture if the \CFA runtime system in regards to concurrency. 2290 Each component of the picture is explained in detail in the flowing sections. 1926 2291 1927 2292 \begin{figure} … … 1934 2299 1935 2300 \subsection{Processors} 1936 Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically \texttt{pthread}s in the current implementation of \CFA. Indeed, any parallelism must go through operating-system libraries. However, \textbf{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism. Indeed, processor \textbf{kthread} simply fetch a \textbf{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. 2301 Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically \texttt{pthread}s in the current implementation of \CFA. 2302 Indeed, any parallelism must go through operating-system libraries. 2303 However, \textbf{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism. 2304 Indeed, processor \textbf{kthread} simply fetch a \textbf{uthread} from the scheduler and run it; they are effectively executers for user-threads. 2305 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. 2306 Processors internally use coroutines to take advantage of the existing context-switching semantics. 1937 2307 1938 2308 \subsection{Stack Management} 1939 One of the challenges of this system is to reduce the footprint as much as possible. Specifically, all \texttt{pthread}s created also have a stack created with them, which should be used as much as possible. Normally, coroutines also create their own stack to run on, however, in the case of the coroutines used for processors, these coroutines run directly on the \textbf{kthread} stack, effectively stealing the processor stack. The exception to this rule is the Main Processor, i.e., the initial \textbf{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. 2309 One of the challenges of this system is to reduce the footprint as much as possible. 2310 Specifically, all \texttt{pthread}s created also have a stack created with them, which should be used as much as possible. 2311 Normally, coroutines also create their own stack to run on, however, in the case of the coroutines used for processors, these coroutines run directly on the \textbf{kthread} stack, effectively stealing the processor stack. 2312 The exception to this rule is the Main Processor, i.e., the initial \textbf{kthread} that is given to any program. 2313 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. 1940 2314 1941 2315 \subsection{Context Switching} 1942 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 operations 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. 2316 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. 2317 To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific function call. 2318 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. 2319 Note that the instruction pointer can be left untouched since the context-switch is always inside the same function. 2320 Threads, however, do not context-switch between each other directly. 2321 They context-switch to the scheduler. 2322 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 operations happen. 2323 Obviously, this doubles the context-switch cost because threads must context-switch to an intermediate stack. 2324 The alternative 1-step context-switch uses the stack of the ``from'' thread to schedule and then context-switches directly to the ``to'' thread. 2325 However, the performance of the 2-step context-switch is still superior to a \code{pthread_yield} (see section \ref{results}). 2326 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). 2327 This option is not currently present in \CFA, but the changes required to add it are strictly additive. 1943 2328 1944 2329 \subsection{Preemption} \label{preemption} 1945 Finally, an important aspect for any complete threading system is preemption. As mentioned in section \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. 1946 1947 Preemption in \CFA\footnote{Note that the implementation of preemption is strongly tied with the underlying threading system. For this reason, only the Linux implementation is cover, \CFA does not run on Windows at the time of writting} 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.: 2330 Finally, an important aspect for any complete threading system is preemption. 2331 As mentioned in section \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. 2332 Indeed, preemption is desirable because it adds a degree of isolation among threads. 2333 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. 2334 Obviously, preemption is not optimal for every workload. 2335 However any preemptive system can become a cooperative system by making the time slices extremely large. 2336 Therefore, \CFA uses a preemptive threading system. 2337 2338 Preemption in \CFA\footnote{Note that the implementation of preemption is strongly tied with the underlying threading system. 2339 For this reason, only the Linux implementation is cover, \CFA does not run on Windows at the time of writting} is based on kernel timers, which are used to run a discrete-event simulation. 2340 Every processor keeps track of the current time and registers an expiration time with the preemption system. 2341 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. 2342 These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread. 2343 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.: 1948 2344 \begin{quote} 1949 A 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. 2345 A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked. 2346 If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal. 1950 2347 SIGNAL(7) - Linux Programmer's Manual 1951 2348 \end{quote} 1952 2349 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. 1953 2350 1954 Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread. Hence, involuntary context-switching is done by sending signal {\tt SIGUSR1} 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. 2351 Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread. 2352 Hence, involuntary context-switching is done by sending signal {\tt SIGUSR1} to the corresponding proces\-sor and having the thread yield from inside the signal handler. 2353 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. 2354 As a result, a signal handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread). 2355 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. 2356 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.}. 2357 However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel-alarm thread can cause deadlocks. 2358 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. 2359 One final detail about the alarm thread is how to wake it when additional communication is required (e.g., on thread termination). 2360 This unblocking is also done using {\tt SIGALRM}, but sent through the \code{pthread_sigqueue}. 2361 Indeed, \code{sigwait} can differentiate signals sent from \code{pthread_sigqueue} from signals sent from alarms or the kernel. 1955 2362 1956 2363 \subsection{Scheduler} 1957 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}. 2364 Finally, an aspect that was not mentioned yet is the scheduling algorithm. 2365 Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling. 2366 Further discussion on scheduling is present in section \ref{futur:sched}. 1958 2367 1959 2368 % ====================================================================== … … 1971 2380 \end{figure} 1972 2381 1973 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/signaller (AS) stack is a FILO list used for threads that have been signalled or otherwise marked as running next. 1974 1975 For \CFA, this picture does not have support for blocking multiple monitors on a single condition. To support \textbf{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}. 2382 This picture has several components, the two most important being the entry queue and the AS-stack. 2383 The entry queue is an (almost) FIFO list where threads waiting to enter are parked, while the acceptor/signaller (AS) stack is a FILO list used for threads that have been signalled or otherwise marked as running next. 2384 2385 For \CFA, this picture does not have support for blocking multiple monitors on a single condition. 2386 To support \textbf{bulk-acq} two changes to this picture are required. 2387 First, it is no longer helpful to attach the condition to \emph{a single} monitor. 2388 Secondly, the thread waiting on the condition has to be separated across multiple monitors, seen in figure \ref{fig:monitor_cfa}. 1976 2389 1977 2390 \begin{figure}[H] … … 1983 2396 \end{figure} 1984 2397 1985 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 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 signalling operation every monitor needs a piece of thread on its AS-stack. 2398 This picture and the proper entry and leave algorithms (see listing \ref{lst:entry2}) is the fundamental implementation of internal scheduling. 2399 Note that when a thread is moved from the condition to the AS-stack, it is conceptually split into N pieces, where N is the number of monitors specified in the parameter list. 2400 The thread is woken up when all the pieces have popped from the AS-stacks and made active. 2401 In this picture, the threads are split into halves but this is only because there are two monitors. 2402 For a specific signalling operation every monitor needs a piece of thread on its AS-stack. 1986 2403 1987 2404 \begin{figure}[b] … … 2016 2433 \end{figure} 2017 2434 2018 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 structures 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. 2435 The solution discussed in \ref{intsched} can be seen in the exit routine of listing \ref{lst:entry2}. 2436 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. 2437 This solution is deadlock safe as well as preventing any potential barging. 2438 The data structures 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. 2019 2439 2020 2440 \begin{figure}[H] … … 2026 2446 \end{figure} 2027 2447 2028 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 ``next'' pointers for linking onto monitors. The \code{condition node} is the data structure that is queued onto a condition variable and, when signalled, the condition queue is popped and each \code{condition criterion} is moved to the AS-stack. Once all the criteria have been popped from their respective AS-stacks, the thread is woken up, which is what is shown in listing \ref{lst:entry2}. 2448 Figure \ref{fig:structs} shows a high-level representation of these data structures. 2449 The main idea behind them is that, a thread cannot contain an arbitrary number of intrusive ``next'' pointers for linking onto monitors. 2450 The \code{condition node} is the data structure that is queued onto a condition variable and, when signalled, the condition queue is popped and each \code{condition criterion} is moved to the AS-stack. 2451 Once all the criteria have been popped from their respective AS-stacks, the thread is woken up, which is what is shown in listing \ref{lst:entry2}. 2029 2452 2030 2453 % ====================================================================== … … 2033 2456 % ====================================================================== 2034 2457 % ====================================================================== 2035 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 (i.e., 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. 2458 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}. 2459 For internal scheduling, these queues are part of condition variables, which are still unique for a given scheduling operation (i.e., no signal statement uses multiple conditions). 2460 However, in the case of external scheduling, there is no equivalent object which is associated with \code{waitfor} statements. 2461 This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired. 2462 These monitors being the only objects that have sufficient lifetime and are available on both sides of the \code{waitfor} statement. 2463 This requires an algorithm to choose which monitor holds the relevant queue. 2464 It is also important that said algorithm be independent of the order in which users list parameters. 2465 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. 2466 This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint. 2036 2467 2037 2468 This algorithm choice has two consequences: 2038 2469 \begin{itemize} 2039 \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. 2040 \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 which has 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. 2470 \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. 2471 These queues need to contain a set of monitors for each of the waiting threads. 2472 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. 2473 \item The queue of the lowest priority monitor is both required and potentially unused. 2474 Indeed, since it is not known at compile time which monitor is the monitor which has 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. 2041 2475 \end{itemize} 2042 2476 Therefore, the following modifications need to be made to support external scheduling: 2043 2477 \begin{itemize} 2044 \item The threads waiting on the entry queue need to keep track of which routine they are 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. 2045 \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. 2478 \item The threads waiting on the entry queue need to keep track of which routine they are trying to enter, and using which set of monitors. 2479 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. 2480 \item The monitors need to keep a mask of acceptable routines. 2481 This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it. 2482 It also needs storage to keep track of which routine was accepted. 2483 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. 2484 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. 2485 This becomes relevant when \code{when} clauses affect the number of monitors passed to a \code{waitfor} statement. 2046 2486 \item The entry/exit routines need to be updated as shown in listing \ref{lst:entry3}. 2047 2487 \end{itemize} 2048 2488 2049 2489 \subsection{External Scheduling - Destructors} 2050 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 needed 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 \code{waitfor} semantics can then be adjusted correspondingly, as seen in listing \ref{lst:entry-dtor} 2490 Finally, to support the ordering inversion of destructors, the code generation needs to be modified to use a special entry routine. 2491 This routine is needed because of the storage requirements of the call order inversion. 2492 Indeed, when waiting for the destructors, storage is needed for the waiting context and the lifetime of said storage needs to outlive the waiting operation it is needed for. 2493 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. 2494 The \code{waitfor} semantics can then be adjusted correspondingly, as seen in listing \ref{lst:entry-dtor} 2051 2495 2052 2496 \begin{figure} … … 2141 2585 2142 2586 \section{Threads As Monitors} 2143 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: 2587 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. 2588 For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine: 2144 2589 \begin{figure}[H] 2145 2590 \begin{cfacode}[caption={Toy simulator using \code{thread}s and \code{monitor}s.},label={lst:engine-v1}] … … 2172 2617 \end{cfacode} 2173 2618 \end{figure} 2174 One 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: 2619 One 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. 2620 Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner: 2175 2621 \begin{figure}[H] 2176 2622 \begin{cfacode}[caption={Same toy simulator with proper termination condition.},label={lst:engine-v2}] … … 2216 2662 2217 2663 \section{Fibers \& Threads} 2218 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~: 2664 As mentioned in section \ref{preemption}, \CFA uses preemptive threads by default but can use fibers on demand. 2665 Currently, using fibers is done by adding the following line of code to the program~: 2219 2666 \begin{cfacode} 2220 2667 unsigned int default_preemption() { … … 2222 2669 } 2223 2670 \end{cfacode} 2224 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 \textbf{uthread} in the same system, as in listing \ref{lst:fiber-uthread} 2671 This function is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice, i.e., no preemption. 2672 However, once clusters are fully implemented, it will be possible to create fibers and \textbf{uthread} in the same system, as in listing \ref{lst:fiber-uthread} 2225 2673 \begin{figure} 2226 2674 \begin{cfacode}[caption={Using fibers and \textbf{uthread} side-by-side in \CFA},label={lst:fiber-uthread}] … … 2281 2729 % ====================================================================== 2282 2730 \section{Machine Setup} 2283 Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks. All tests were made on this machine. 2731 Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks. 2732 All tests were made on this machine. 2284 2733 \begin{table}[H] 2285 2734 \begin{center} … … 2314 2763 2315 2764 \section{Micro Benchmarks} 2316 All benchmarks are run using the same harness to produce the results, seen as the \code{BENCH()} macro in the following examples. This macro uses the following logic to benchmark the code: 2765 All benchmarks are run using the same harness to produce the results, seen as the \code{BENCH()} macro in the following examples. 2766 This macro uses the following logic to benchmark the code: 2317 2767 \begin{pseudo} 2318 2768 #define BENCH(run, result) \ … … 2322 2772 result = (after - before) / N; 2323 2773 \end{pseudo} 2324 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 iterations depends on the specific benchmark. 2774 The method used to get time is \code{clock_gettime(CLOCK_THREAD_CPUTIME_ID);}. 2775 Each benchmark is using many iterations of a simple call to measure the cost of the call. 2776 The specific number of iterations depends on the specific benchmark. 2325 2777 2326 2778 \subsection{Context-Switching} 2327 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. Yielding causes the thread to context-switch to the scheduler and back, more precisely: from the \textbf{uthread} to the \textbf{kthread} then from the \textbf{kthread} back to the same \textbf{uthread} (or a different one in the general case). In order to make the comparison fair, coroutines also execute a 2-step context-switch by resuming another coroutine which does nothing but suspending in a tight loop, which is a resume/suspend cycle instead of a yield. Listing \ref{lst:ctx-switch} shows the code for coroutines and threads with the results in table \ref{tab:ctx-switch}. All omitted tests are functionally identical to one of these tests. The difference between coroutines and threads can be attributed to the cost of scheduling. 2779 The first interesting benchmark is to measure how long context-switches take. 2780 The simplest approach to do this is to yield on a thread, which executes a 2-step context switch. 2781 Yielding causes the thread to context-switch to the scheduler and back, more precisely: from the \textbf{uthread} to the \textbf{kthread} then from the \textbf{kthread} back to the same \textbf{uthread} (or a different one in the general case). 2782 In order to make the comparison fair, coroutines also execute a 2-step context-switch by resuming another coroutine which does nothing but suspending in a tight loop, which is a resume/suspend cycle instead of a yield. 2783 Listing \ref{lst:ctx-switch} shows the code for coroutines and threads with the results in table \ref{tab:ctx-switch}. 2784 All omitted tests are functionally identical to one of these tests. 2785 The difference between coroutines and threads can be attributed to the cost of scheduling. 2328 2786 \begin{figure} 2329 2787 \begin{multicols}{2} … … 2386 2844 \end{tabular} 2387 2845 \end{center} 2388 \caption{Context Switch comparison. All numbers are in nanoseconds(\si{\nano\second})} 2846 \caption{Context Switch comparison. 2847 All numbers are in nanoseconds(\si{\nano\second})} 2389 2848 \label{tab:ctx-switch} 2390 2849 \end{table} 2391 2850 2392 2851 \subsection{Mutual-Exclusion} 2393 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 \code{pthread_mutex} lock is also measured. The results can be shown in table \ref{tab:mutex}. 2852 The next interesting benchmark is to measure the overhead to enter/leave a critical-section. 2853 For monitors, the simplest approach is to measure how long it takes to enter and leave a monitor routine. 2854 Listing \ref{lst:mutex} shows the code for \CFA. 2855 To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a \code{pthread_mutex} lock is also measured. 2856 The results can be shown in table \ref{tab:mutex}. 2394 2857 2395 2858 \begin{figure} … … 2428 2891 \end{tabular} 2429 2892 \end{center} 2430 \caption{Mutex routine comparison. All numbers are in nanoseconds(\si{\nano\second})} 2893 \caption{Mutex routine comparison. 2894 All numbers are in nanoseconds(\si{\nano\second})} 2431 2895 \label{tab:mutex} 2432 2896 \end{table} 2433 2897 2434 2898 \subsection{Internal Scheduling} 2435 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. 2899 The internal-scheduling benchmark measures the cost of waiting on and signalling a condition variable. 2900 Listing \ref{lst:int-sched} shows the code for \CFA, with results table \ref{tab:int-sched}. 2901 As with all other benchmarks, all omitted tests are functionally identical to one of these tests. 2436 2902 2437 2903 \begin{figure} … … 2484 2950 \end{tabular} 2485 2951 \end{center} 2486 \caption{Internal scheduling comparison. All numbers are in nanoseconds(\si{\nano\second})} 2952 \caption{Internal scheduling comparison. 2953 All numbers are in nanoseconds(\si{\nano\second})} 2487 2954 \label{tab:int-sched} 2488 2955 \end{table} 2489 2956 2490 2957 \subsection{External Scheduling} 2491 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. 2958 The Internal scheduling benchmark measures the cost of the \code{waitfor} statement (\code{_Accept} in \uC). 2959 Listing \ref{lst:ext-sched} shows the code for \CFA, with results in table \ref{tab:ext-sched}. 2960 As with all other benchmarks, all omitted tests are functionally identical to one of these tests. 2492 2961 2493 2962 \begin{figure} … … 2537 3006 \end{tabular} 2538 3007 \end{center} 2539 \caption{External scheduling comparison. All numbers are in nanoseconds(\si{\nano\second})} 3008 \caption{External scheduling comparison. 3009 All numbers are in nanoseconds(\si{\nano\second})} 2540 3010 \label{tab:ext-sched} 2541 3011 \end{table} 2542 3012 2543 3013 \subsection{Object Creation} 2544 Finally, the last benchmark measures the cost of creation for concurrent objects. Listing \ref{lst:creation} shows the code for \texttt{pthread}s 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. 3014 Finally, the last benchmark measures the cost of creation for concurrent objects. 3015 Listing \ref{lst:creation} shows the code for \texttt{pthread}s and \CFA threads, with results shown in table \ref{tab:creation}. 3016 As with all other benchmarks, all omitted tests are functionally identical to one of these tests. 3017 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. 2545 3018 2546 3019 \begin{figure} … … 2604 3077 \end{tabular} 2605 3078 \end{center} 2606 \caption{Creation comparison. All numbers are in nanoseconds(\si{\nano\second}).} 3079 \caption{Creation comparison. 3080 All numbers are in nanoseconds(\si{\nano\second}).} 2607 3081 \label{tab:creation} 2608 3082 \end{table} … … 2611 3085 2612 3086 \section{Conclusion} 2613 This paper has achieved a minimal concurrency \textbf{api} that is simple, efficient and usable as the basis for higher-level features. The approach presented is based on a lightweight thread-system for parallelism, which sits on top of clusters of processors. This M:N model is judged to be both more efficient and allow more flexibility for users. Furthermore, this document introduces monitors as the main concurrency tool for users. This paper also offers a novel approach allowing multiple monitors to be accessed simultaneously without running into the Nested Monitor Problem~\cite{Lister77}. It also offers a full implementation of the concurrency runtime written entirely in \CFA, effectively the largest \CFA code base to date. 3087 This paper has achieved a minimal concurrency \textbf{api} that is simple, efficient and usable as the basis for higher-level features. 3088 The approach presented is based on a lightweight thread-system for parallelism, which sits on top of clusters of processors. 3089 This M:N model is judged to be both more efficient and allow more flexibility for users. 3090 Furthermore, this document introduces monitors as the main concurrency tool for users. 3091 This paper also offers a novel approach allowing multiple monitors to be accessed simultaneously without running into the Nested Monitor Problem~\cite{Lister77}. 3092 It also offers a full implementation of the concurrency runtime written entirely in \CFA, effectively the largest \CFA code base to date. 2614 3093 2615 3094 … … 2621 3100 2622 3101 \subsection{Performance} \label{futur:perf} 2623 This paper presents a first implementation of the \CFA concurrency runtime. Therefore, there is still significant work to improve performance. Many of the data structures and algorithms may change in the future to more efficient versions. For example, the number of monitors in a single \textbf{bulk-acq} is only bound by the stack size, this is probably unnecessarily generous. It may be possible that limiting the number helps increase performance. However, it is not obvious that the benefit would be significant. 3102 This paper presents a first implementation of the \CFA concurrency runtime. 3103 Therefore, there is still significant work to improve performance. 3104 Many of the data structures and algorithms may change in the future to more efficient versions. 3105 For example, the number of monitors in a single \textbf{bulk-acq} is only bound by the stack size, this is probably unnecessarily generous. 3106 It may be possible that limiting the number helps increase performance. 3107 However, it is not obvious that the benefit would be significant. 2624 3108 2625 3109 \subsection{Flexible Scheduling} \label{futur:sched} 2626 An important part of concurrency is scheduling. Different scheduling algorithms 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. 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. 3110 An important part of concurrency is scheduling. 3111 Different scheduling algorithms can affect performance (both in terms of average and variation). 3112 However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs. 3113 One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted to the requirements of the workload. 3114 However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms. 3115 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. 3116 This path of flexible schedulers will be explored for \CFA. 2627 3117 2628 3118 \subsection{Non-Blocking I/O} \label{futur:nbio} 2629 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 types of workloads often require significant engineering around amortizing costs of blocking IO operations. At its core, non-blocking I/O is an 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 makes 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. 3119 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). 3120 These types of workloads often require significant engineering around amortizing costs of blocking IO operations. 3121 At its core, non-blocking I/O is an operating system level feature that allows queuing IO operations (e.g., network operations) and registering for notifications instead of waiting for requests to complete. 3122 In this context, the role of the language makes Non-Blocking IO easily available and with low overhead. 3123 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. 3124 However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear. 2630 3125 2631 3126 \subsection{Other Concurrency Tools} \label{futur:tools} 2632 While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package. Examples 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. 3127 While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package. 3128 Examples of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, executors and actors. 3129 These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks. 2633 3130 2634 3131 \subsection{Implicit Threading} \label{futur:implcit} 2635 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 algorithms~\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. 3132 Simpler applications can benefit greatly from having implicit parallelism. 3133 That is, parallelism that does not rely on the user to write concurrency. 3134 This type of parallelism can be achieved both at the language level and at the library level. 3135 The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithms~\cite{uC++book}. 3136 Table \ref{lst:parfor} shows three different code examples that accomplish point-wise sums of large arrays. 3137 Note that none of these examples explicitly declare any concurrency or parallelism objects. 2636 3138 2637 3139 \begin{table} … … 2718 3220 \end{table} 2719 3221 2720 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 boilerplate needed to start benefiting from parallelism in modern CPUs. 3222 Implicit parallelism is a restrictive solution and therefore has its limitations. 3223 However, it is a quick and simple approach to parallelism, which may very well be sufficient for smaller applications and reduces the amount of boilerplate needed to start benefiting from parallelism in modern CPUs. 2721 3224 2722 3225 … … 2731 3234 % B I B L I O G R A P H Y 2732 3235 % ----------------------------- 2733 \bibliographystyle{plain}3236 %\bibliographystyle{plain} 2734 3237 \bibliography{pl,local} 2735 3238
Note: See TracChangeset
for help on using the changeset viewer.