1 | \documentclass[AMA,STIX1COL]{WileyNJD-v2} |
---|
2 | |
---|
3 | \articletype{RESEARCH ARTICLE}% |
---|
4 | |
---|
5 | \received{26 April 2016} |
---|
6 | \revised{6 June 2016} |
---|
7 | \accepted{6 June 2016} |
---|
8 | |
---|
9 | \raggedbottom |
---|
10 | |
---|
11 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
12 | |
---|
13 | % Latex packages used in the document. |
---|
14 | |
---|
15 | \usepackage{epic,eepic} |
---|
16 | \usepackage{xspace} |
---|
17 | \usepackage{comment} |
---|
18 | \usepackage{upquote} % switch curled `'" to straight |
---|
19 | \usepackage{listings} % format program code |
---|
20 | \usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig} |
---|
21 | \renewcommand{\thesubfigure}{(\alph{subfigure})} |
---|
22 | \usepackage{siunitx} |
---|
23 | \sisetup{ binary-units=true } |
---|
24 | |
---|
25 | \hypersetup{breaklinks=true} |
---|
26 | \definecolor{OliveGreen}{cmyk}{0.64 0 0.95 0.40} |
---|
27 | \definecolor{Mahogany}{cmyk}{0 0.85 0.87 0.35} |
---|
28 | \definecolor{Plum}{cmyk}{0.50 1 0 0} |
---|
29 | |
---|
30 | \usepackage[pagewise]{lineno} |
---|
31 | \renewcommand{\linenumberfont}{\scriptsize\sffamily} |
---|
32 | |
---|
33 | \renewcommand{\textfraction}{0.0} % the entire page maybe devoted to floats with no text on the page at all |
---|
34 | |
---|
35 | \lefthyphenmin=3 % hyphen only after 4 characters |
---|
36 | \righthyphenmin=3 |
---|
37 | |
---|
38 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
39 | |
---|
40 | % Names used in the document. |
---|
41 | |
---|
42 | \newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name |
---|
43 | \newcommand{\CFA}{\protect\CFAIcon} % safe for section/caption |
---|
44 | \newcommand{\CFL}{\textrm{Cforall}\xspace} % Cforall symbolic name |
---|
45 | \newcommand{\Celeven}{\textrm{C11}\xspace} % C11 symbolic name |
---|
46 | \newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name |
---|
47 | \newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name |
---|
48 | \newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name |
---|
49 | \newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name |
---|
50 | \newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name |
---|
51 | \newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name |
---|
52 | |
---|
53 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
54 | |
---|
55 | \newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}} |
---|
56 | \newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}} |
---|
57 | \newcommand{\R}[1]{\Textbf{#1}} |
---|
58 | \newcommand{\B}[1]{{\Textbf[blue]{#1}}} |
---|
59 | \newcommand{\G}[1]{{\Textbf[OliveGreen]{#1}}} |
---|
60 | \newcommand{\uC}{$\mu$\CC} |
---|
61 | \newcommand{\cit}{\textsuperscript{[Citation Needed]}\xspace} |
---|
62 | \newcommand{\TODO}{{\Textbf{TODO}}} |
---|
63 | |
---|
64 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
65 | |
---|
66 | % Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore |
---|
67 | % removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR |
---|
68 | % AFTER HYPERREF. |
---|
69 | %\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}} |
---|
70 | \renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}} |
---|
71 | |
---|
72 | \makeatletter |
---|
73 | % parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for |
---|
74 | % use rather than use \parident directly. |
---|
75 | \newlength{\parindentlnth} |
---|
76 | \setlength{\parindentlnth}{\parindent} |
---|
77 | |
---|
78 | \newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{\lst@basicstyle{#1}}}} |
---|
79 | \newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}} |
---|
80 | \newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}} |
---|
81 | |
---|
82 | \newlength{\gcolumnposn} % temporary hack because lstlisting does not handle tabs correctly |
---|
83 | \newlength{\columnposn} |
---|
84 | \setlength{\gcolumnposn}{3.5in} |
---|
85 | \setlength{\columnposn}{\gcolumnposn} |
---|
86 | \newcommand{\C}[2][\@empty]{\ifx#1\@empty\else\global\setlength{\columnposn}{#1}\global\columnposn=\columnposn\fi\hfill\makebox[\textwidth-\columnposn][l]{\lst@basicstyle{\LstCommentStyle{#2}}}} |
---|
87 | \newcommand{\CRT}{\global\columnposn=\gcolumnposn} |
---|
88 | |
---|
89 | % Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}. |
---|
90 | % The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc} |
---|
91 | % The star version does not lowercase the index information, e.g., \newterm*{IBM}. |
---|
92 | \newcommand{\newtermFontInline}{\emph} |
---|
93 | \newcommand{\newterm}{\@ifstar\@snewterm\@newterm} |
---|
94 | \newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi} |
---|
95 | \newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi} |
---|
96 | |
---|
97 | % Latin abbreviation |
---|
98 | \newcommand{\abbrevFont}{\textit} % set empty for no italics |
---|
99 | \@ifundefined{eg}{ |
---|
100 | \newcommand{\EG}{\abbrevFont{e}.\abbrevFont{g}.} |
---|
101 | \newcommand*{\eg}{% |
---|
102 | \@ifnextchar{,}{\EG}% |
---|
103 | {\@ifnextchar{:}{\EG}% |
---|
104 | {\EG,\xspace}}% |
---|
105 | }}{}% |
---|
106 | \@ifundefined{ie}{ |
---|
107 | \newcommand{\IE}{\abbrevFont{i}.\abbrevFont{e}.} |
---|
108 | \newcommand*{\ie}{% |
---|
109 | \@ifnextchar{,}{\IE}% |
---|
110 | {\@ifnextchar{:}{\IE}% |
---|
111 | {\IE,\xspace}}% |
---|
112 | }}{}% |
---|
113 | \@ifundefined{etc}{ |
---|
114 | \newcommand{\ETC}{\abbrevFont{etc}} |
---|
115 | \newcommand*{\etc}{% |
---|
116 | \@ifnextchar{.}{\ETC}% |
---|
117 | {\ETC.\xspace}% |
---|
118 | }}{}% |
---|
119 | \@ifundefined{etal}{ |
---|
120 | \newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}} |
---|
121 | \newcommand*{\etal}{% |
---|
122 | \@ifnextchar{.}{\protect\ETAL}% |
---|
123 | {\protect\ETAL.\xspace}% |
---|
124 | }}{}% |
---|
125 | \@ifundefined{viz}{ |
---|
126 | \newcommand{\VIZ}{\abbrevFont{viz}} |
---|
127 | \newcommand*{\viz}{% |
---|
128 | \@ifnextchar{.}{\VIZ}% |
---|
129 | {\VIZ.\xspace}% |
---|
130 | }}{}% |
---|
131 | \makeatother |
---|
132 | |
---|
133 | \newenvironment{cquote}{% |
---|
134 | \list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}% |
---|
135 | \item\relax |
---|
136 | }{% |
---|
137 | \endlist |
---|
138 | }% cquote |
---|
139 | |
---|
140 | % CFA programming language, based on ANSI C (with some gcc additions) |
---|
141 | \lstdefinelanguage{CFA}[ANSI]{C}{ |
---|
142 | morekeywords={ |
---|
143 | _Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, __attribute, __attribute__, |
---|
144 | auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__, __const, __const__, |
---|
145 | coroutine, disable, dtype, enable, __extension__, exception, fallthrough, fallthru, finally, |
---|
146 | __float80, float80, __float128, float128, forall, ftype, _Generic, _Imaginary, __imag, __imag__, |
---|
147 | inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or, |
---|
148 | otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread, |
---|
149 | _Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__, |
---|
150 | virtual, __volatile, __volatile__, waitfor, when, with, zero_t}, |
---|
151 | moredirectives={defined,include_next}% |
---|
152 | } |
---|
153 | |
---|
154 | \lstset{ |
---|
155 | language=CFA, |
---|
156 | columns=fullflexible, |
---|
157 | basicstyle=\linespread{0.9}\sf, % reduce line spacing and use sanserif font |
---|
158 | stringstyle=\tt, % use typewriter font |
---|
159 | tabsize=5, % N space tabbing |
---|
160 | xleftmargin=\parindentlnth, % indent code to paragraph indentation |
---|
161 | %mathescape=true, % LaTeX math escape in CFA code $...$ |
---|
162 | escapechar=\$, % LaTeX escape in CFA code |
---|
163 | keepspaces=true, % |
---|
164 | showstringspaces=false, % do not show spaces with cup |
---|
165 | showlines=true, % show blank lines at end of code |
---|
166 | aboveskip=4pt, % spacing above/below code block |
---|
167 | belowskip=3pt, |
---|
168 | % replace/adjust listing characters that look bad in sanserif |
---|
169 | literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1 |
---|
170 | {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1 |
---|
171 | {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex{\textgreater}}2, |
---|
172 | moredelim=**[is][\color{red}]{`}{`}, |
---|
173 | }% lstset |
---|
174 | |
---|
175 | % uC++ programming language, based on ANSI C++ |
---|
176 | \lstdefinelanguage{uC++}[ANSI]{C++}{ |
---|
177 | morekeywords={ |
---|
178 | _Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _CatchResume, _Cormonitor, _Coroutine, _Disable, |
---|
179 | _Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask, |
---|
180 | _Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw}, |
---|
181 | } |
---|
182 | \lstdefinelanguage{Golang}{ |
---|
183 | morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,}, |
---|
184 | morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64, |
---|
185 | bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface}, |
---|
186 | morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,}, |
---|
187 | morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,}, |
---|
188 | morekeywords=[5]{Println,Printf,Error,}, |
---|
189 | sensitive=true, |
---|
190 | morecomment=[l]{//}, |
---|
191 | morecomment=[s]{/*}{*/}, |
---|
192 | morestring=[b]', |
---|
193 | morestring=[b]", |
---|
194 | morestring=[s]{`}{`}, |
---|
195 | } |
---|
196 | |
---|
197 | \lstnewenvironment{cfa}[1][] |
---|
198 | {\lstset{#1}} |
---|
199 | {} |
---|
200 | \lstnewenvironment{C++}[1][] % use C++ style |
---|
201 | {\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}} |
---|
202 | {} |
---|
203 | \lstnewenvironment{uC++}[1][] |
---|
204 | {\lstset{#1}} |
---|
205 | {} |
---|
206 | \lstnewenvironment{Go}[1][] |
---|
207 | {\lstset{#1}} |
---|
208 | {} |
---|
209 | |
---|
210 | % inline code @...@ |
---|
211 | \lstMakeShortInline@% |
---|
212 | |
---|
213 | |
---|
214 | \title{\texorpdfstring{Concurrency in \protect\CFA}{Concurrency in Cforall}} |
---|
215 | |
---|
216 | \author[1]{Thierry Delisle} |
---|
217 | \author[1]{Peter A. Buhr*} |
---|
218 | \authormark{Thierry Delisle \textsc{et al}} |
---|
219 | |
---|
220 | \address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Ontario}, \country{Canada}}} |
---|
221 | |
---|
222 | \corres{*Peter A. Buhr, \email{pabuhr{\char`\@}uwaterloo.ca}} |
---|
223 | \presentaddress{Cheriton School of Computer Science, University of Waterloo, Waterloo, ON, N2L 3G1, Canada} |
---|
224 | |
---|
225 | |
---|
226 | \abstract[Summary]{ |
---|
227 | \CFA is a modern, polymorphic, \emph{non-object-oriented} extension of the C programming language. |
---|
228 | This paper discusses the design of the concurrency and parallelism features in \CFA, and the concurrent runtime-system. |
---|
229 | These features are created from scratch as ISO C lacks concurrency, relying largely on pthreads. |
---|
230 | Coroutines and lightweight (user) threads are introduced into the language. |
---|
231 | In addition, monitors are added as a high-level mechanism for mutual exclusion and synchronization. |
---|
232 | A unique contribution is allowing multiple monitors to be safely acquired simultaneously. |
---|
233 | All features respect the expectations of C programmers, while being fully integrate with the \CFA polymorphic type-system and other language features. |
---|
234 | Finally, experimental results are presented to compare the performance of the new features with similar mechanisms in other concurrent programming-languages. |
---|
235 | }% |
---|
236 | |
---|
237 | \keywords{concurrency, parallelism, coroutines, threads, monitors, runtime, C, Cforall} |
---|
238 | |
---|
239 | |
---|
240 | \begin{document} |
---|
241 | \linenumbers % comment out to turn off line numbering |
---|
242 | |
---|
243 | \maketitle |
---|
244 | |
---|
245 | % ====================================================================== |
---|
246 | % ====================================================================== |
---|
247 | \section{Introduction} |
---|
248 | % ====================================================================== |
---|
249 | % ====================================================================== |
---|
250 | |
---|
251 | This paper provides a minimal concurrency \newterm{Abstract Program Interface} (API) that is simple, efficient and can be used to build other concurrency features. |
---|
252 | While the simplest concurrency system is a thread and a lock, this low-level approach is hard to master. |
---|
253 | An easier approach for programmers is to support higher-level constructs as the basis of concurrency. |
---|
254 | Indeed, for highly productive concurrent programming, high-level approaches are much more popular~\cite{Hochstein05}. |
---|
255 | Examples of high-level approaches are task based~\cite{TBB}, message passing~\cite{Erlang,MPI}, and implicit threading~\cite{OpenMP}. |
---|
256 | |
---|
257 | This paper used the following terminology. |
---|
258 | A \newterm{thread} is a fundamental unit of execution that runs a sequence of code and requires a stack to maintain state. |
---|
259 | Multiple simultaneous threads gives rise to \newterm{concurrency}, which requires locking to ensure safe communication and access to shared data. |
---|
260 | % Correspondingly, concurrency is defined as the concepts and challenges that occur when multiple independent (sharing memory, timing dependencies, \etc) concurrent threads are introduced. |
---|
261 | \newterm{Locking}, and by extension locks, are defined as a mechanism to prevent progress of threads to provide safety. |
---|
262 | \newterm{Parallelism} is running multiple threads simultaneously. |
---|
263 | Parallelism implies \emph{actual} simultaneous execution, where concurrency only requires \emph{apparent} simultaneous execution. |
---|
264 | As such, parallelism is only observable in differences in performance, which is observed through differences in timing. |
---|
265 | |
---|
266 | Hence, there are two problems to be solved in the design of concurrency for a programming language: concurrency and parallelism. |
---|
267 | While these two concepts are often combined, they are in fact distinct, requiring different tools~\cite[\S~2]{Buhr05a}. |
---|
268 | Concurrency tools handle synchronization and mutual exclusion, while parallelism tools handle performance, cost and resource utilization. |
---|
269 | |
---|
270 | The proposed concurrency API is implemented in a dialect of C, called \CFA. |
---|
271 | The paper discusses how the language features are added to the \CFA translator with respect to parsing, semantic, and type checking, and the corresponding high-perforamnce runtime-library to implement the concurrency features. |
---|
272 | |
---|
273 | % ====================================================================== |
---|
274 | % ====================================================================== |
---|
275 | \section{\CFA Overview} |
---|
276 | % ====================================================================== |
---|
277 | % ====================================================================== |
---|
278 | |
---|
279 | The following is a quick introduction to the \CFA language, specifically tailored to the features needed to support concurrency. |
---|
280 | |
---|
281 | \CFA is an extension of ISO-C and therefore supports all of the same paradigms as C. |
---|
282 | 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. |
---|
283 | Like C, the basics of \CFA revolve around structures and routines, which are thin abstractions over machine code. |
---|
284 | The vast majority of the code produced by the \CFA translator respects memory layouts and calling conventions laid out by C. |
---|
285 | Interestingly, while \CFA is not an object-oriented language, lacking the concept of a receiver (\eg {\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 |
---|
286 | values''~\cite[3.15]{C11}}, most importantly construction and destruction of objects. |
---|
287 | Most of the following code examples can be found on the \CFA website~\cite{Cforall}. |
---|
288 | |
---|
289 | |
---|
290 | \subsection{References} |
---|
291 | |
---|
292 | Like \CC, \CFA introduces rebind-able references providing multiple dereferencing as an alternative to pointers. |
---|
293 | 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: |
---|
294 | \begin{cfa} |
---|
295 | int x, *p1 = &x, **p2 = &p1, ***p3 = &p2, |
---|
296 | &r1 = x, &&r2 = r1, &&&r3 = r2; |
---|
297 | ***p3 = 3; $\C{// change x}$ |
---|
298 | r3 = 3; $\C{// change x, ***r3}$ |
---|
299 | **p3 = ...; $\C{// change p1}$ |
---|
300 | *p3 = ...; $\C{// change p2}$ |
---|
301 | int y, z, & ar[3] = {x, y, z}; $\C{// initialize array of references}$ |
---|
302 | typeof( ar[1]) p; $\C{// is int, referenced object type}$ |
---|
303 | typeof(&ar[1]) q; $\C{// is int \&, reference type}$ |
---|
304 | sizeof( ar[1]) == sizeof(int); $\C{// is true, referenced object size}$ |
---|
305 | sizeof(&ar[1]) == sizeof(int *); $\C{// is true, reference size}$ |
---|
306 | \end{cfa} |
---|
307 | The important take away from this code example is that a reference offers a handle to an object, much like a pointer, but which is automatically dereferenced for convenience. |
---|
308 | |
---|
309 | % ====================================================================== |
---|
310 | \subsection{Overloading} |
---|
311 | |
---|
312 | 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. |
---|
313 | As well, \CFA uses the return type as part of the selection criteria, as in Ada~\cite{Ada}. |
---|
314 | For routines with multiple parameters and returns, the selection is complex. |
---|
315 | \begin{cfa} |
---|
316 | // selection based on type and number of parameters |
---|
317 | void f(void); $\C{// (1)}$ |
---|
318 | void f(char); $\C{// (2)}$ |
---|
319 | void f(int, double); $\C{// (3)}$ |
---|
320 | f(); $\C{// select (1)}$ |
---|
321 | f('a'); $\C{// select (2)}$ |
---|
322 | f(3, 5.2); $\C{// select (3)}$ |
---|
323 | |
---|
324 | // selection based on type and number of returns |
---|
325 | char f(int); $\C{// (1)}$ |
---|
326 | double f(int); $\C{// (2)}$ |
---|
327 | char c = f(3); $\C{// select (1)}$ |
---|
328 | double d = f(4); $\C{// select (2)}$ |
---|
329 | \end{cfa} |
---|
330 | This feature is particularly important for concurrency since the runtime system relies on creating different types to represent concurrency objects. |
---|
331 | Therefore, overloading is necessary to prevent the need for long prefixes and other naming conventions that prevent name clashes. |
---|
332 | As seen in section \ref{basics}, routine @main@ is an example that benefits from overloading. |
---|
333 | |
---|
334 | % ====================================================================== |
---|
335 | \subsection{Operators} |
---|
336 | Overloading also extends to operators. |
---|
337 | 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, \eg: |
---|
338 | \begin{cfa} |
---|
339 | int ++? (int op); $\C{// unary prefix increment}$ |
---|
340 | int ?++ (int op); $\C{// unary postfix increment}$ |
---|
341 | int ?+? (int op1, int op2); $\C{// binary plus}$ |
---|
342 | int ?<=?(int op1, int op2); $\C{// binary less than}$ |
---|
343 | int ?=? (int & op1, int op2); $\C{// binary assignment}$ |
---|
344 | int ?+=?(int & op1, int op2); $\C{// binary plus-assignment}$ |
---|
345 | |
---|
346 | struct S {int i, j;}; |
---|
347 | S ?+?(S op1, S op2) { $\C{// add two structures}$ |
---|
348 | return (S){op1.i + op2.i, op1.j + op2.j}; |
---|
349 | } |
---|
350 | S s1 = {1, 2}, s2 = {2, 3}, s3; |
---|
351 | s3 = s1 + s2; $\C{// compute sum: s3 == {2, 5}}$ |
---|
352 | \end{cfa} |
---|
353 | While concurrency does not use operator overloading directly, this feature is more important as an introduction for the syntax of constructors. |
---|
354 | |
---|
355 | % ====================================================================== |
---|
356 | \subsection{Constructors/Destructors} |
---|
357 | 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. |
---|
358 | 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: |
---|
359 | \begin{cfa} |
---|
360 | struct S { |
---|
361 | size_t size; |
---|
362 | int * ia; |
---|
363 | }; |
---|
364 | void ?{}(S & s, int asize) { $\C{// constructor operator}$ |
---|
365 | s.size = asize; $\C{// initialize fields}$ |
---|
366 | s.ia = calloc(size, sizeof(S)); |
---|
367 | } |
---|
368 | void ^?{}(S & s) { $\C{// destructor operator}$ |
---|
369 | free(ia); $\C{// de-initialization fields}$ |
---|
370 | } |
---|
371 | int main() { |
---|
372 | S x = {10}, y = {100}; $\C{// implicit calls: ?\{\}(x, 10), ?\{\}(y, 100)}$ |
---|
373 | ... $\C{// use x and y}$ |
---|
374 | ^x{}; ^y{}; $\C{// explicit calls to de-initialize}$ |
---|
375 | x{20}; y{200}; $\C{// explicit calls to reinitialize}$ |
---|
376 | ... $\C{// reuse x and y}$ |
---|
377 | } $\C{// implicit calls: \^?\{\}(y), \^?\{\}(x)}$ |
---|
378 | \end{cfa} |
---|
379 | The language guarantees that every object and all their fields are constructed. |
---|
380 | Like \CC, construction of an object is automatically done on allocation and destruction of the object is done on deallocation. |
---|
381 | Allocation and deallocation can occur on the stack or on the heap. |
---|
382 | \begin{cfa} |
---|
383 | { |
---|
384 | struct S s = {10}; $\C{// allocation, call constructor}$ |
---|
385 | ... |
---|
386 | } $\C{// deallocation, call destructor}$ |
---|
387 | struct S * s = new(); $\C{// allocation, call constructor}$ |
---|
388 | ... |
---|
389 | delete(s); $\C{// deallocation, call destructor}$ |
---|
390 | \end{cfa} |
---|
391 | Note that like \CC, \CFA introduces @new@ and @delete@, which behave like @malloc@ and @free@ in addition to constructing and destructing objects, after calling @malloc@ and before calling @free@, respectively. |
---|
392 | |
---|
393 | % ====================================================================== |
---|
394 | \subsection{Parametric Polymorphism} |
---|
395 | \label{s:ParametricPolymorphism} |
---|
396 | Routines in \CFA can also be reused for multiple types. |
---|
397 | This capability is done using the @forall@ clauses, which allow separately compiled routines to support generic usage over multiple types. |
---|
398 | For example, the following sum function works for any type that supports construction from 0 and addition: |
---|
399 | \begin{cfa} |
---|
400 | // constraint type, 0 and + |
---|
401 | forall(otype T | { void ?{}(T *, zero_t); T ?+?(T, T); }) |
---|
402 | T sum(T a[ ], size_t size) { |
---|
403 | T total = 0; $\C{// construct T from 0}$ |
---|
404 | for(size_t i = 0; i < size; i++) |
---|
405 | total = total + a[i]; $\C{// select appropriate +}$ |
---|
406 | return total; |
---|
407 | } |
---|
408 | |
---|
409 | S sa[5]; |
---|
410 | int i = sum(sa, 5); $\C{// use S's 0 construction and +}$ |
---|
411 | \end{cfa} |
---|
412 | |
---|
413 | Since writing constraints on types can become cumbersome for more constrained functions, \CFA also has the concept of traits. |
---|
414 | Traits are named collection of constraints that can be used both instead and in addition to regular constraints: |
---|
415 | \begin{cfa} |
---|
416 | trait summable( otype T ) { |
---|
417 | void ?{}(T *, zero_t); $\C{// constructor from 0 literal}$ |
---|
418 | T ?+?(T, T); $\C{// assortment of additions}$ |
---|
419 | T ?+=?(T *, T); |
---|
420 | T ++?(T *); |
---|
421 | T ?++(T *); |
---|
422 | }; |
---|
423 | forall( otype T | summable(T) ) $\C{// use trait}$ |
---|
424 | T sum(T a[], size_t size); |
---|
425 | \end{cfa} |
---|
426 | |
---|
427 | Note that the type use for assertions can be either an @otype@ or a @dtype@. |
---|
428 | Types declared as @otype@ refer to ``complete'' objects, \ie objects with a size, a default constructor, a copy constructor, a destructor and an assignment operator. |
---|
429 | Using @dtype@, on the other hand, has none of these assumptions but is extremely restrictive, it only guarantees the object is addressable. |
---|
430 | |
---|
431 | % ====================================================================== |
---|
432 | \subsection{with Clause/Statement} |
---|
433 | Since \CFA lacks the concept of a receiver, certain functions end up needing to repeat variable names often. |
---|
434 | To remove this inconvenience, \CFA provides the @with@ statement, which opens an aggregate scope making its fields directly accessible (like Pascal). |
---|
435 | \begin{cfa} |
---|
436 | struct S { int i, j; }; |
---|
437 | int mem(S & this) with (this) $\C{// with clause}$ |
---|
438 | i = 1; $\C{// this->i}$ |
---|
439 | j = 2; $\C{// this->j}$ |
---|
440 | } |
---|
441 | int foo() { |
---|
442 | struct S1 { ... } s1; |
---|
443 | struct S2 { ... } s2; |
---|
444 | with (s1) $\C{// with statement}$ |
---|
445 | { |
---|
446 | // access fields of s1 without qualification |
---|
447 | with (s2) $\C{// nesting}$ |
---|
448 | { |
---|
449 | // access fields of s1 and s2 without qualification |
---|
450 | } |
---|
451 | } |
---|
452 | with (s1, s2) $\C{// scopes open in parallel}$ |
---|
453 | { |
---|
454 | // access fields of s1 and s2 without qualification |
---|
455 | } |
---|
456 | } |
---|
457 | \end{cfa} |
---|
458 | |
---|
459 | For more information on \CFA see \cite{cforall-ug,Schluntz17,www-cfa}. |
---|
460 | |
---|
461 | % ====================================================================== |
---|
462 | % ====================================================================== |
---|
463 | \section{Concurrency Basics}\label{basics} |
---|
464 | % ====================================================================== |
---|
465 | % ====================================================================== |
---|
466 | |
---|
467 | At its core, concurrency is based on having multiple call-stacks and scheduling among threads of execution executing on these stacks. |
---|
468 | Multiple call stacks (or contexts) and a single thread of execution does \emph{not} imply concurrency. |
---|
469 | Execution with a single thread and multiple stacks where the thread is deterministically self-scheduling across the stacks is called \newterm{coroutining}; |
---|
470 | execution with a single thread 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~\cite[\S~3]{Buhr05a}. |
---|
471 | Therefore, a minimal concurrency system can be achieved using coroutines (see Section \ref{coroutine}), which instead of context-switching among each other, always defer to an oracle for where to context-switch next. |
---|
472 | |
---|
473 | While coroutines can execute on the caller's stack-frame, stack-full coroutines allow full generality and are sufficient as the basis for concurrency. |
---|
474 | The aforementioned oracle is a scheduler and the whole system now follows a cooperative threading-model (a.k.a., non-preemptive scheduling). |
---|
475 | 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. |
---|
476 | In any case, a subset of concurrency related challenges start to appear. |
---|
477 | For the complete set of concurrency challenges to occur, the only feature missing is preemption. |
---|
478 | |
---|
479 | A scheduler introduces order of execution uncertainty, while preemption introduces uncertainty about where context switches occur. |
---|
480 | Mutual exclusion and synchronization are ways of limiting non-determinism in a concurrent system. |
---|
481 | 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. |
---|
482 | Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows. |
---|
483 | |
---|
484 | |
---|
485 | \subsection{\protect\CFA's Thread Building Blocks} |
---|
486 | |
---|
487 | 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. |
---|
488 | As such, library support for threading is far from widespread. |
---|
489 | At the time of writing the paper, neither \protect\lstinline|gcc| nor \protect\lstinline|clang| support ``threads.h'' in their standard libraries.}. |
---|
490 | 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. |
---|
491 | 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. |
---|
492 | And being a system-level language means programmers expect to choose precisely which features they need and which cost they are willing to pay. |
---|
493 | |
---|
494 | |
---|
495 | \subsection{Coroutines: A Stepping Stone}\label{coroutine} |
---|
496 | |
---|
497 | While the focus of this proposal is concurrency and parallelism, it is important to address coroutines, which are a significant building block of a concurrency system. |
---|
498 | \newterm{Coroutine}s are generalized routines with points where execution is suspended and resumed at a later time. |
---|
499 | Suspend/resume is a context switche and coroutines have other context-management operations. |
---|
500 | Many design challenges of threads are partially present in designing coroutines, which makes the design effort relevant. |
---|
501 | The core \textbf{api} of coroutines has two features: independent call-stacks and @suspend@/@resume@. |
---|
502 | |
---|
503 | A coroutine handles the class of problems that need to retain state between calls (\eg plugin, device driver, finite-state machine). |
---|
504 | For example, a problem made easier with coroutines is unbounded generators, \eg generating an infinite sequence of Fibonacci numbers: |
---|
505 | \begin{displaymath} |
---|
506 | f(n) = \left \{ |
---|
507 | \begin{array}{ll} |
---|
508 | 0 & n = 0 \\ |
---|
509 | 1 & n = 1 \\ |
---|
510 | f(n-1) + f(n-2) & n \ge 2 \\ |
---|
511 | \end{array} |
---|
512 | \right. |
---|
513 | \end{displaymath} |
---|
514 | Figure~\ref{f:C-fibonacci} shows conventional approaches for writing a Fibonacci generator in C. |
---|
515 | |
---|
516 | Figure~\ref{f:GlobalVariables} illustrates the following problems: |
---|
517 | unencapsulated global variables necessary to retain state between calls; |
---|
518 | only one fibonacci generator can run at a time; |
---|
519 | execution state must be explicitly retained. |
---|
520 | Figure~\ref{f:ExternalState} addresses these issues: |
---|
521 | unencapsulated program global variables become encapsulated structure variables; |
---|
522 | multiple fibonacci generators can run at a time by declaring multiple fibonacci objects; |
---|
523 | explicit execution state is removed by precomputing the first two Fibonacci numbers and returning $f(n-2)$. |
---|
524 | |
---|
525 | \begin{figure} |
---|
526 | \centering |
---|
527 | \newbox\myboxA |
---|
528 | \begin{lrbox}{\myboxA} |
---|
529 | \begin{lstlisting}[aboveskip=0pt,belowskip=0pt] |
---|
530 | `int f1, f2, state = 1;` // single global variables |
---|
531 | int fib() { |
---|
532 | int fn; |
---|
533 | `switch ( state )` { // explicit execution state |
---|
534 | case 1: fn = 0; f1 = fn; state = 2; break; |
---|
535 | case 2: fn = 1; f2 = f1; f1 = fn; state = 3; break; |
---|
536 | case 3: fn = f1 + f2; f2 = f1; f1 = fn; break; |
---|
537 | } |
---|
538 | return fn; |
---|
539 | } |
---|
540 | int main() { |
---|
541 | |
---|
542 | for ( int i = 0; i < 10; i += 1 ) { |
---|
543 | printf( "%d\n", fib() ); |
---|
544 | } |
---|
545 | } |
---|
546 | \end{lstlisting} |
---|
547 | \end{lrbox} |
---|
548 | |
---|
549 | \newbox\myboxB |
---|
550 | \begin{lrbox}{\myboxB} |
---|
551 | \begin{lstlisting}[aboveskip=0pt,belowskip=0pt] |
---|
552 | #define FIB_INIT `{ 0, 1 }` |
---|
553 | typedef struct { int f2, f1; } Fib; |
---|
554 | int fib( Fib * f ) { |
---|
555 | |
---|
556 | int ret = f->f2; |
---|
557 | int fn = f->f1 + f->f2; |
---|
558 | f->f2 = f->f1; f->f1 = fn; |
---|
559 | |
---|
560 | return ret; |
---|
561 | } |
---|
562 | int main() { |
---|
563 | Fib f1 = FIB_INIT, f2 = FIB_INIT; |
---|
564 | for ( int i = 0; i < 10; i += 1 ) { |
---|
565 | printf( "%d %d\n", fib( &f1 ), fib( &f2 ) ); |
---|
566 | } |
---|
567 | } |
---|
568 | \end{lstlisting} |
---|
569 | \end{lrbox} |
---|
570 | |
---|
571 | \subfloat[3 States: global variables]{\label{f:GlobalVariables}\usebox\myboxA} |
---|
572 | \qquad |
---|
573 | \subfloat[1 State: external variables]{\label{f:ExternalState}\usebox\myboxB} |
---|
574 | \caption{C Fibonacci Implementations} |
---|
575 | \label{f:C-fibonacci} |
---|
576 | |
---|
577 | \bigskip |
---|
578 | |
---|
579 | \newbox\myboxA |
---|
580 | \begin{lrbox}{\myboxA} |
---|
581 | \begin{lstlisting}[aboveskip=0pt,belowskip=0pt] |
---|
582 | `coroutine` Fib { int fn; }; |
---|
583 | void main( Fib & f ) with( f ) { |
---|
584 | int f1, f2; |
---|
585 | fn = 0; f1 = fn; `suspend()`; |
---|
586 | fn = 1; f2 = f1; f1 = fn; `suspend()`; |
---|
587 | for ( ;; ) { |
---|
588 | fn = f1 + f2; f2 = f1; f1 = fn; `suspend()`; |
---|
589 | } |
---|
590 | } |
---|
591 | int next( Fib & fib ) with( fib ) { |
---|
592 | `resume( fib );` |
---|
593 | return fn; |
---|
594 | } |
---|
595 | int main() { |
---|
596 | Fib f1, f2; |
---|
597 | for ( int i = 1; i <= 10; i += 1 ) { |
---|
598 | sout | next( f1 ) | next( f2 ) | endl; |
---|
599 | } |
---|
600 | } |
---|
601 | \end{lstlisting} |
---|
602 | \end{lrbox} |
---|
603 | \newbox\myboxB |
---|
604 | \begin{lrbox}{\myboxB} |
---|
605 | \begin{lstlisting}[aboveskip=0pt,belowskip=0pt] |
---|
606 | `coroutine` Fib { int ret; }; |
---|
607 | void main( Fib & f ) with( f ) { |
---|
608 | int fn, f1 = 1, f2 = 0; |
---|
609 | for ( ;; ) { |
---|
610 | ret = f2; |
---|
611 | |
---|
612 | fn = f1 + f2; f2 = f1; f1 = fn; `suspend();` |
---|
613 | } |
---|
614 | } |
---|
615 | int next( Fib & fib ) with( fib ) { |
---|
616 | `resume( fib );` |
---|
617 | return ret; |
---|
618 | } |
---|
619 | |
---|
620 | |
---|
621 | |
---|
622 | |
---|
623 | |
---|
624 | |
---|
625 | \end{lstlisting} |
---|
626 | \end{lrbox} |
---|
627 | \subfloat[3 States, internal variables]{\label{f:Coroutine3States}\usebox\myboxA} |
---|
628 | \qquad |
---|
629 | \subfloat[1 State, internal variables]{\label{f:Coroutine1State}\usebox\myboxB} |
---|
630 | \caption{\CFA Coroutine Fibonacci Implementations} |
---|
631 | \label{f:fibonacci-cfa} |
---|
632 | \end{figure} |
---|
633 | |
---|
634 | Figure~\ref{f:Coroutine3States} creates a @coroutine@ type, which provides communication for multiple interface functions, and the \newterm{coroutine main}, which runs on the coroutine stack. |
---|
635 | \begin{cfa} |
---|
636 | `coroutine C { char c; int i; _Bool s; };` $\C{// used for communication}$ |
---|
637 | void ?{}( C & c ) { s = false; } $\C{// constructor}$ |
---|
638 | void main( C & cor ) with( cor ) { $\C{// actual coroutine}$ |
---|
639 | while ( ! s ) // process c |
---|
640 | if ( v == ... ) s = false; |
---|
641 | } |
---|
642 | // interface functions |
---|
643 | char cont( C & cor, char ch ) { c = ch; resume( cor ); return c; } |
---|
644 | _Bool stop( C & cor, int v ) { s = true; i = v; resume( cor ); return s; } |
---|
645 | \end{cfa} |
---|
646 | |
---|
647 | encapsulates the Fibonacci state in the shows is an example of a solution to the Fibonacci problem using \CFA coroutines, where the coroutine stack holds sufficient state for the next generation. |
---|
648 | This solution has the advantage of having very strong decoupling between how the sequence is generated and how it is used. |
---|
649 | Indeed, this version is as easy to use as the @fibonacci_state@ solution, while the implementation is very similar to the @fibonacci_func@ example. |
---|
650 | |
---|
651 | Figure~\ref{f:fmt-line} shows the @Format@ coroutine for restructuring text into groups of character blocks of fixed size. |
---|
652 | 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. |
---|
653 | |
---|
654 | \begin{figure} |
---|
655 | \centering |
---|
656 | \begin{cfa} |
---|
657 | `coroutine` Format { |
---|
658 | char ch; $\C{// used for communication}$ |
---|
659 | int g, b; $\C{// global because used in destructor}$ |
---|
660 | }; |
---|
661 | void ?{}( Format & fmt ) { `resume( fmt );` } $\C{// prime (start) coroutine}$ |
---|
662 | void ^?{}( Format & fmt ) with( fmt ) { if ( g != 0 || b != 0 ) sout | endl; } |
---|
663 | void main( Format & fmt ) with( fmt ) { |
---|
664 | for ( ;; ) { $\C{// for as many characters}$ |
---|
665 | for ( g = 0; g < 5; g += 1 ) { $\C{// groups of 5 blocks}$ |
---|
666 | for ( b = 0; b < 4; b += 1 ) { $\C{// blocks of 4 characters}$ |
---|
667 | `suspend();` |
---|
668 | sout | ch; $\C{// print character}$ |
---|
669 | } |
---|
670 | sout | " "; $\C{// print block separator}$ |
---|
671 | } |
---|
672 | sout | endl; $\C{// print group separator}$ |
---|
673 | } |
---|
674 | } |
---|
675 | void prt( Format & fmt, char ch ) { |
---|
676 | fmt.ch = ch; |
---|
677 | `resume( fmt );` |
---|
678 | } |
---|
679 | int main() { |
---|
680 | Format fmt; |
---|
681 | char ch; |
---|
682 | for ( ;; ) { $\C{// read until end of file}$ |
---|
683 | sin | ch; $\C{// read one character}$ |
---|
684 | if ( eof( sin ) ) break; $\C{// eof ?}$ |
---|
685 | prt( fmt, ch ); $\C{// push character for formatting}$ |
---|
686 | } |
---|
687 | } |
---|
688 | \end{cfa} |
---|
689 | \caption{Formatting text into lines of 5 blocks of 4 characters.} |
---|
690 | \label{f:fmt-line} |
---|
691 | \end{figure} |
---|
692 | |
---|
693 | \begin{figure} |
---|
694 | \centering |
---|
695 | \lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}} |
---|
696 | \begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}} |
---|
697 | \begin{cfa} |
---|
698 | `coroutine` Prod { |
---|
699 | Cons & c; |
---|
700 | int N, money, receipt; |
---|
701 | }; |
---|
702 | void main( Prod & prod ) with( prod ) { |
---|
703 | // 1st resume starts here |
---|
704 | for ( int i = 0; i < N; i += 1 ) { |
---|
705 | int p1 = random( 100 ), p2 = random( 100 ); |
---|
706 | sout | p1 | " " | p2 | endl; |
---|
707 | int status = delivery( c, p1, p2 ); |
---|
708 | sout | " $" | money | endl | status | endl; |
---|
709 | receipt += 1; |
---|
710 | } |
---|
711 | stop( c ); |
---|
712 | sout | "prod stops" | endl; |
---|
713 | } |
---|
714 | int payment( Prod & prod, int money ) { |
---|
715 | prod.money = money; |
---|
716 | `resume( prod );` |
---|
717 | return prod.receipt; |
---|
718 | } |
---|
719 | void start( Prod & prod, int N, Cons &c ) { |
---|
720 | &prod.c = &c; |
---|
721 | prod.[N, receipt] = [N, 0]; |
---|
722 | `resume( prod );` |
---|
723 | } |
---|
724 | int main() { |
---|
725 | Prod prod; |
---|
726 | Cons cons = { prod }; |
---|
727 | srandom( getpid() ); |
---|
728 | start( prod, 5, cons ); |
---|
729 | } |
---|
730 | \end{cfa} |
---|
731 | & |
---|
732 | \begin{cfa} |
---|
733 | `coroutine` Cons { |
---|
734 | Prod & p; |
---|
735 | int p1, p2, status; |
---|
736 | _Bool done; |
---|
737 | }; |
---|
738 | void ?{}( Cons & cons, Prod & p ) { |
---|
739 | &cons.p = &p; |
---|
740 | cons.[status, done ] = [0, false]; |
---|
741 | } |
---|
742 | void ^?{}( Cons & cons ) {} |
---|
743 | void main( Cons & cons ) with( cons ) { |
---|
744 | // 1st resume starts here |
---|
745 | int money = 1, receipt; |
---|
746 | for ( ; ! done; ) { |
---|
747 | sout | p1 | " " | p2 | endl | " $" | money | endl; |
---|
748 | status += 1; |
---|
749 | receipt = payment( p, money ); |
---|
750 | sout | " #" | receipt | endl; |
---|
751 | money += 1; |
---|
752 | } |
---|
753 | sout | "cons stops" | endl; |
---|
754 | } |
---|
755 | int delivery( Cons & cons, int p1, int p2 ) { |
---|
756 | cons.[p1, p2] = [p1, p2]; |
---|
757 | `resume( cons );` |
---|
758 | return cons.status; |
---|
759 | } |
---|
760 | void stop( Cons & cons ) { |
---|
761 | cons.done = true; |
---|
762 | `resume( cons );` |
---|
763 | } |
---|
764 | |
---|
765 | \end{cfa} |
---|
766 | \end{tabular} |
---|
767 | \caption{Producer / consumer: resume-resume cycle, bi-directional communication} |
---|
768 | \label{f:ProdCons} |
---|
769 | \end{figure} |
---|
770 | |
---|
771 | |
---|
772 | \subsubsection{Construction} |
---|
773 | |
---|
774 | 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. |
---|
775 | In the case of coroutines, this challenge is simpler since there is no non-determinism from preemption or scheduling. |
---|
776 | However, the underlying challenge remains the same for coroutines and threads. |
---|
777 | |
---|
778 | The runtime system needs to create the coroutine's stack and, more importantly, prepare it for the first resumption. |
---|
779 | 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. |
---|
780 | There are several solutions to this problem but the chosen option effectively forces the design of the coroutine. |
---|
781 | |
---|
782 | Furthermore, \CFA faces an extra challenge as polymorphic routines create invisible thunks when cast to non-polymorphic routines and these thunks have function scope. |
---|
783 | For example, the following code, while looking benign, can run into undefined behaviour because of thunks: |
---|
784 | |
---|
785 | \begin{cfa} |
---|
786 | // async: Runs function asynchronously on another thread |
---|
787 | forall(otype T) |
---|
788 | extern void async(void (*func)(T*), T* obj); |
---|
789 | |
---|
790 | forall(otype T) |
---|
791 | void noop(T*) {} |
---|
792 | |
---|
793 | void bar() { |
---|
794 | int a; |
---|
795 | async(noop, &a); // start thread running noop with argument a |
---|
796 | } |
---|
797 | \end{cfa} |
---|
798 | |
---|
799 | The generated C code\footnote{Code trimmed down for brevity} creates a local thunk to hold type information: |
---|
800 | |
---|
801 | \begin{cfa} |
---|
802 | extern void async(/* omitted */, void (*func)(void*), void* obj); |
---|
803 | |
---|
804 | void noop(/* omitted */, void* obj){} |
---|
805 | |
---|
806 | void bar(){ |
---|
807 | int a; |
---|
808 | void _thunk0(int* _p0){ |
---|
809 | /* omitted */ |
---|
810 | noop(/* omitted */, _p0); |
---|
811 | } |
---|
812 | /* omitted */ |
---|
813 | async(/* omitted */, ((void (*)(void*))(&_thunk0)), (&a)); |
---|
814 | } |
---|
815 | \end{cfa} |
---|
816 | The problem in this example is a storage management issue, the function pointer @_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; \ie the stack-based thunk being destroyed before it can be used. |
---|
817 | This challenge is an extension of challenges that come with second-class routines. |
---|
818 | Indeed, GCC nested routines also have the limitation that nested routine cannot be passed outside of the declaration scope. |
---|
819 | The case of coroutines and threads is simply an extension of this problem to multiple call stacks. |
---|
820 | |
---|
821 | |
---|
822 | \subsubsection{Alternative: Composition} |
---|
823 | |
---|
824 | One solution to this challenge is to use composition/containment, where coroutine fields are added to manage the coroutine. |
---|
825 | |
---|
826 | \begin{cfa} |
---|
827 | struct Fibonacci { |
---|
828 | int fn; // used for communication |
---|
829 | coroutine c; // composition |
---|
830 | }; |
---|
831 | |
---|
832 | void FibMain(void*) { |
---|
833 | //... |
---|
834 | } |
---|
835 | |
---|
836 | void ?{}(Fibonacci& this) { |
---|
837 | this.fn = 0; |
---|
838 | // Call constructor to initialize coroutine |
---|
839 | (this.c){myMain}; |
---|
840 | } |
---|
841 | \end{cfa} |
---|
842 | The downside of this approach is that users need to correctly construct the coroutine handle before using it. |
---|
843 | Like any other objects, the user must carefully choose construction order to prevent usage of objects not yet constructed. |
---|
844 | However, in the case of coroutines, users must also pass to the coroutine information about the coroutine main, like in the previous example. |
---|
845 | This opens the door for user errors and requires extra runtime storage to pass at runtime information that can be known statically. |
---|
846 | |
---|
847 | |
---|
848 | \subsubsection{Alternative: Reserved keyword} |
---|
849 | |
---|
850 | The next alternative is to use language support to annotate coroutines as follows: |
---|
851 | \begin{cfa} |
---|
852 | coroutine Fibonacci { |
---|
853 | int fn; // used for communication |
---|
854 | }; |
---|
855 | \end{cfa} |
---|
856 | The @coroutine@ keyword means the compiler can find and inject code where needed. |
---|
857 | The downside of this approach is that it makes coroutine a special case in the language. |
---|
858 | Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language. |
---|
859 | Furthermore, implementing coroutines without language supports also displays the power of the programming language used. |
---|
860 | 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. |
---|
861 | The reserved keywords are only present to improve ease of use for the common cases. |
---|
862 | |
---|
863 | |
---|
864 | \subsubsection{Alternative: Lambda Objects} |
---|
865 | |
---|
866 | For coroutines as for threads, many implementations are based on routine pointers or function objects~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}. |
---|
867 | For example, Boost implements coroutines in terms of four functor object types: |
---|
868 | \begin{cfa} |
---|
869 | asymmetric_coroutine<>::pull_type |
---|
870 | asymmetric_coroutine<>::push_type |
---|
871 | symmetric_coroutine<>::call_type |
---|
872 | symmetric_coroutine<>::yield_type |
---|
873 | \end{cfa} |
---|
874 | Often, the canonical threading paradigm in languages is based on function pointers, @pthread@ being one of the most well-known examples. |
---|
875 | 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. |
---|
876 | Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda based coroutines adds very little. |
---|
877 | |
---|
878 | A variation of this would be to use a simple function pointer in the same way @pthread@ does for threads: |
---|
879 | \begin{cfa} |
---|
880 | void foo( coroutine_t cid, void* arg ) { |
---|
881 | int* value = (int*)arg; |
---|
882 | // Coroutine body |
---|
883 | } |
---|
884 | |
---|
885 | int main() { |
---|
886 | int value = 0; |
---|
887 | coroutine_t cid = coroutine_create( &foo, (void*)&value ); |
---|
888 | coroutine_resume( &cid ); |
---|
889 | } |
---|
890 | \end{cfa} |
---|
891 | This semantics is more common for thread interfaces but coroutines work equally well. |
---|
892 | As discussed in section \ref{threads}, this approach is superseded by static approaches in terms of expressivity. |
---|
893 | |
---|
894 | |
---|
895 | \subsubsection{Alternative: Trait-Based Coroutines} |
---|
896 | |
---|
897 | Finally, the underlying approach, which is the one closest to \CFA idioms, is to use trait-based lazy coroutines. |
---|
898 | This approach defines a coroutine as anything that satisfies the trait @is_coroutine@ (as defined below) and is used as a coroutine. |
---|
899 | |
---|
900 | \begin{cfa} |
---|
901 | trait is_coroutine(dtype T) { |
---|
902 | void main(T& this); |
---|
903 | coroutine_desc* get_coroutine(T& this); |
---|
904 | }; |
---|
905 | |
---|
906 | forall( dtype T | is_coroutine(T) ) void suspend(T&); |
---|
907 | forall( dtype T | is_coroutine(T) ) void resume (T&); |
---|
908 | \end{cfa} |
---|
909 | This ensures that an object is not a coroutine until @resume@ is called on the object. |
---|
910 | Correspondingly, any object that is passed to @resume@ is a coroutine since it must satisfy the @is_coroutine@ trait to compile. |
---|
911 | 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 @get_coroutine@ routine. |
---|
912 | The \CFA keyword @coroutine@ simply has the effect of implementing the getter and forward declarations required for users to implement the main routine. |
---|
913 | |
---|
914 | \begin{center} |
---|
915 | \begin{tabular}{c c c} |
---|
916 | \begin{cfa}[tabsize=3] |
---|
917 | coroutine MyCoroutine { |
---|
918 | int someValue; |
---|
919 | }; |
---|
920 | \end{cfa} & == & \begin{cfa}[tabsize=3] |
---|
921 | struct MyCoroutine { |
---|
922 | int someValue; |
---|
923 | coroutine_desc __cor; |
---|
924 | }; |
---|
925 | |
---|
926 | static inline |
---|
927 | coroutine_desc* get_coroutine( |
---|
928 | struct MyCoroutine& this |
---|
929 | ) { |
---|
930 | return &this.__cor; |
---|
931 | } |
---|
932 | |
---|
933 | void main(struct MyCoroutine* this); |
---|
934 | \end{cfa} |
---|
935 | \end{tabular} |
---|
936 | \end{center} |
---|
937 | |
---|
938 | The combination of these two approaches allows users new to coroutining and concurrency to have an easy and concise specification, while more advanced users have tighter control on memory layout and initialization. |
---|
939 | |
---|
940 | \subsection{Thread Interface}\label{threads} |
---|
941 | The basic building blocks of multithreading in \CFA are \textbf{cfathread}. |
---|
942 | Both user and kernel threads are supported, where user threads are the concurrency mechanism and kernel threads are the parallel mechanism. |
---|
943 | User threads offer a flexible and lightweight interface. |
---|
944 | A thread can be declared using a struct declaration @thread@ as follows: |
---|
945 | |
---|
946 | \begin{cfa} |
---|
947 | thread foo {}; |
---|
948 | \end{cfa} |
---|
949 | |
---|
950 | As for coroutines, the keyword is a thin wrapper around a \CFA trait: |
---|
951 | |
---|
952 | \begin{cfa} |
---|
953 | trait is_thread(dtype T) { |
---|
954 | void ^?{}(T & mutex this); |
---|
955 | void main(T & this); |
---|
956 | thread_desc* get_thread(T & this); |
---|
957 | }; |
---|
958 | \end{cfa} |
---|
959 | |
---|
960 | Obviously, for this thread implementation to be useful it must run some user code. |
---|
961 | Several other threading interfaces use a function-pointer representation as the interface of threads (for example \Csharp~\cite{Csharp} and Scala~\cite{Scala}). |
---|
962 | However, this proposal considers that statically tying a @main@ routine to a thread supersedes this approach. |
---|
963 | Since the @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). |
---|
964 | As such the @main@ routine of a thread can be defined as |
---|
965 | \begin{cfa} |
---|
966 | thread foo {}; |
---|
967 | |
---|
968 | void main(foo & this) { |
---|
969 | sout | "Hello World!" | endl; |
---|
970 | } |
---|
971 | \end{cfa} |
---|
972 | |
---|
973 | In this example, threads of type @foo@ start execution in the @void main(foo &)@ routine, which prints @"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. |
---|
974 | 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. |
---|
975 | \begin{cfa} |
---|
976 | typedef void (*voidFunc)(int); |
---|
977 | |
---|
978 | thread FuncRunner { |
---|
979 | voidFunc func; |
---|
980 | int arg; |
---|
981 | }; |
---|
982 | |
---|
983 | void ?{}(FuncRunner & this, voidFunc inFunc, int arg) { |
---|
984 | this.func = inFunc; |
---|
985 | this.arg = arg; |
---|
986 | } |
---|
987 | |
---|
988 | void main(FuncRunner & this) { |
---|
989 | // thread starts here and runs the function |
---|
990 | this.func( this.arg ); |
---|
991 | } |
---|
992 | |
---|
993 | void hello(/*unused*/ int) { |
---|
994 | sout | "Hello World!" | endl; |
---|
995 | } |
---|
996 | |
---|
997 | int main() { |
---|
998 | FuncRunner f = {hello, 42}; |
---|
999 | return 0? |
---|
1000 | } |
---|
1001 | \end{cfa} |
---|
1002 | |
---|
1003 | 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}. |
---|
1004 | |
---|
1005 | Of course, for threads to be useful, it must be possible to start and stop threads and wait for them to complete execution. |
---|
1006 | While using an \textbf{api} such as @fork@ and @join@ is relatively common in the literature, such an interface is unnecessary. |
---|
1007 | Indeed, the simplest approach is to use \textbf{raii} principles and have threads @fork@ after the constructor has completed and @join@ before the destructor runs. |
---|
1008 | \begin{cfa} |
---|
1009 | thread World; |
---|
1010 | |
---|
1011 | void main(World & this) { |
---|
1012 | sout | "World!" | endl; |
---|
1013 | } |
---|
1014 | |
---|
1015 | void main() { |
---|
1016 | World w; |
---|
1017 | // Thread forks here |
---|
1018 | |
---|
1019 | // Printing "Hello " and "World!" are run concurrently |
---|
1020 | sout | "Hello " | endl; |
---|
1021 | |
---|
1022 | // Implicit join at end of scope |
---|
1023 | } |
---|
1024 | \end{cfa} |
---|
1025 | |
---|
1026 | This semantic has several advantages over explicit semantics: a thread is always started and stopped exactly once, users cannot make any programming errors, and it naturally scales to multiple threads meaning basic synchronization is very simple. |
---|
1027 | |
---|
1028 | \begin{cfa} |
---|
1029 | thread MyThread { |
---|
1030 | //... |
---|
1031 | }; |
---|
1032 | |
---|
1033 | // main |
---|
1034 | void main(MyThread& this) { |
---|
1035 | //... |
---|
1036 | } |
---|
1037 | |
---|
1038 | void foo() { |
---|
1039 | MyThread thrds[10]; |
---|
1040 | // Start 10 threads at the beginning of the scope |
---|
1041 | |
---|
1042 | DoStuff(); |
---|
1043 | |
---|
1044 | // Wait for the 10 threads to finish |
---|
1045 | } |
---|
1046 | \end{cfa} |
---|
1047 | |
---|
1048 | However, one of the drawbacks of this approach is that threads always form a tree where nodes must always outlive their children, \ie they are always destroyed in the opposite order of construction because of C scoping rules. |
---|
1049 | 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. |
---|
1050 | |
---|
1051 | \begin{cfa} |
---|
1052 | thread MyThread { |
---|
1053 | //... |
---|
1054 | }; |
---|
1055 | |
---|
1056 | void main(MyThread& this) { |
---|
1057 | //... |
---|
1058 | } |
---|
1059 | |
---|
1060 | void foo() { |
---|
1061 | MyThread* long_lived; |
---|
1062 | { |
---|
1063 | // Start a thread at the beginning of the scope |
---|
1064 | MyThread short_lived; |
---|
1065 | |
---|
1066 | // create another thread that will outlive the thread in this scope |
---|
1067 | long_lived = new MyThread; |
---|
1068 | |
---|
1069 | DoStuff(); |
---|
1070 | |
---|
1071 | // Wait for the thread short_lived to finish |
---|
1072 | } |
---|
1073 | DoMoreStuff(); |
---|
1074 | |
---|
1075 | // Now wait for the long_lived to finish |
---|
1076 | delete long_lived; |
---|
1077 | } |
---|
1078 | \end{cfa} |
---|
1079 | |
---|
1080 | |
---|
1081 | % ====================================================================== |
---|
1082 | % ====================================================================== |
---|
1083 | \section{Concurrency} |
---|
1084 | % ====================================================================== |
---|
1085 | % ====================================================================== |
---|
1086 | Several tools can be used to solve concurrency challenges. |
---|
1087 | 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}). |
---|
1088 | 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). |
---|
1089 | However, in languages that use routine calls as their core abstraction mechanism, these approaches force a clear distinction between concurrent and non-concurrent paradigms (\ie message passing versus routine calls). |
---|
1090 | This distinction in turn means that, in order to be effective, programmers need to learn two sets of design patterns. |
---|
1091 | While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account. |
---|
1092 | |
---|
1093 | 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. |
---|
1094 | At the lowest level, concurrent paradigms are implemented as atomic operations and locks. |
---|
1095 | Many such mechanisms have been proposed, including semaphores~\cite{Dijkstra68b} and path expressions~\cite{Campbell74}. |
---|
1096 | However, for productivity reasons it is desirable to have a higher-level construct be the core concurrency paradigm~\cite{Hochstein05}. |
---|
1097 | |
---|
1098 | An approach that is worth mentioning because it is gaining in popularity is transactional memory~\cite{Herlihy93}. |
---|
1099 | 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. |
---|
1100 | |
---|
1101 | One of the most natural, elegant, and efficient mechanisms for synchronization and communication, especially for shared-memory systems, is the \emph{monitor}. |
---|
1102 | Monitors were first proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}. |
---|
1103 | Many programming languages---\eg 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. |
---|
1104 | 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. |
---|
1105 | For these reasons, this project proposes monitors as the core concurrency construct. |
---|
1106 | |
---|
1107 | |
---|
1108 | \subsection{Basics} |
---|
1109 | |
---|
1110 | Non-determinism requires concurrent systems to offer support for mutual-exclusion and synchronization. |
---|
1111 | 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. |
---|
1112 | On the other hand, synchronization enforces relative ordering of execution and synchronization tools provide numerous mechanisms to establish timing relationships among threads. |
---|
1113 | |
---|
1114 | |
---|
1115 | \subsubsection{Mutual-Exclusion} |
---|
1116 | |
---|
1117 | As mentioned above, mutual-exclusion is the guarantee that only a fix number of threads can enter a critical section at once. |
---|
1118 | However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use. |
---|
1119 | 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. |
---|
1120 | Ease of use comes by either guaranteeing some problems cannot occur (\eg being deadlock free) or by offering a more explicit coupling between data and corresponding critical section. |
---|
1121 | For example, the \CC @std::atomic<T>@ offers an easy way to express mutual-exclusion on a restricted set of operations (\eg reading/writing large types atomically). |
---|
1122 | Another challenge with low-level locks is composability. |
---|
1123 | Locks have restricted composability because it takes careful organizing for multiple locks to be used while preventing deadlocks. |
---|
1124 | Easing composability is another feature higher-level mutual-exclusion mechanisms often offer. |
---|
1125 | |
---|
1126 | |
---|
1127 | \subsubsection{Synchronization} |
---|
1128 | |
---|
1129 | As with mutual-exclusion, low-level synchronization primitives often offer good performance and good flexibility at the cost of ease of use. |
---|
1130 | Again, higher-level mechanisms often simplify usage by adding either better coupling between synchronization and data (\eg message passing) or offering a simpler solution to otherwise involved challenges. |
---|
1131 | As mentioned above, synchronization can be expressed as guaranteeing that event \textit{X} always happens before \textit{Y}. |
---|
1132 | Most of the time, synchronization happens within a critical section, where threads must acquire mutual-exclusion in a certain order. |
---|
1133 | However, it may also be desirable to guarantee that event \textit{Z} does not occur between \textit{X} and \textit{Y}. |
---|
1134 | Not satisfying this property is called \textbf{barging}. |
---|
1135 | 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}. |
---|
1136 | 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. |
---|
1137 | Preventing or detecting barging is an involved challenge with low-level locks, which can be made much easier by higher-level constructs. |
---|
1138 | This challenge is often split into two different methods, barging avoidance and barging prevention. |
---|
1139 | 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. |
---|
1140 | |
---|
1141 | |
---|
1142 | % ====================================================================== |
---|
1143 | % ====================================================================== |
---|
1144 | \section{Monitors} |
---|
1145 | % ====================================================================== |
---|
1146 | % ====================================================================== |
---|
1147 | A \textbf{monitor} is a set of routines that ensure mutual-exclusion when accessing shared state. |
---|
1148 | 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. |
---|
1149 | This strong association eases readability and maintainability, at the cost of flexibility. |
---|
1150 | Note that both monitors and mutex locks, require an abstract handle to identify them. |
---|
1151 | 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. |
---|
1152 | The only requirement is the ability to declare a handle to a shared object and a set of routines that act on it: |
---|
1153 | \begin{cfa} |
---|
1154 | typedef /*some monitor type*/ monitor; |
---|
1155 | int f(monitor & m); |
---|
1156 | |
---|
1157 | int main() { |
---|
1158 | monitor m; // Handle m |
---|
1159 | f(m); // Routine using handle |
---|
1160 | } |
---|
1161 | \end{cfa} |
---|
1162 | |
---|
1163 | % ====================================================================== |
---|
1164 | % ====================================================================== |
---|
1165 | \subsection{Call Semantics} \label{call} |
---|
1166 | % ====================================================================== |
---|
1167 | % ====================================================================== |
---|
1168 | The above monitor example displays some of the intrinsic characteristics. |
---|
1169 | First, it is necessary to use pass-by-reference over pass-by-value for monitor routines. |
---|
1170 | This semantics is important, because at their core, monitors are implicit mutual-exclusion objects (locks), and these objects cannot be copied. |
---|
1171 | Therefore, monitors are non-copy-able objects (@dtype@). |
---|
1172 | |
---|
1173 | Another aspect to consider is when a monitor acquires its mutual exclusion. |
---|
1174 | For example, a monitor may need to be passed through multiple helper routines that do not acquire the monitor mutual-exclusion on entry. |
---|
1175 | Passthrough can occur for generic helper routines (@swap@, @sort@, \etc) or specific helper routines like the following to implement an atomic counter: |
---|
1176 | |
---|
1177 | \begin{cfa} |
---|
1178 | monitor counter_t { /*...see section $\ref{data}$...*/ }; |
---|
1179 | |
---|
1180 | void ?{}(counter_t & nomutex this); // constructor |
---|
1181 | size_t ++?(counter_t & mutex this); // increment |
---|
1182 | |
---|
1183 | // need for mutex is platform dependent |
---|
1184 | void ?{}(size_t * this, counter_t & mutex cnt); // conversion |
---|
1185 | \end{cfa} |
---|
1186 | This counter is used as follows: |
---|
1187 | \begin{center} |
---|
1188 | \begin{tabular}{c @{\hskip 0.35in} c @{\hskip 0.35in} c} |
---|
1189 | \begin{cfa} |
---|
1190 | // shared counter |
---|
1191 | counter_t cnt1, cnt2; |
---|
1192 | |
---|
1193 | // multiple threads access counter |
---|
1194 | thread 1 : cnt1++; cnt2++; |
---|
1195 | thread 2 : cnt1++; cnt2++; |
---|
1196 | thread 3 : cnt1++; cnt2++; |
---|
1197 | ... |
---|
1198 | thread N : cnt1++; cnt2++; |
---|
1199 | \end{cfa} |
---|
1200 | \end{tabular} |
---|
1201 | \end{center} |
---|
1202 | 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 @std::atomic@. |
---|
1203 | |
---|
1204 | Here, the constructor (@?{}@) uses the @nomutex@ keyword to signify that it does not acquire the monitor mutual-exclusion when constructing. |
---|
1205 | This semantics is because an object not yet constructed should never be shared and therefore does not require mutual exclusion. |
---|
1206 | Furthermore, it allows the implementation greater freedom when it initializes the monitor locking. |
---|
1207 | The prefix increment operator uses @mutex@ to protect the incrementing process from race conditions. |
---|
1208 | Finally, there is a conversion operator from @counter_t@ to @size_t@. |
---|
1209 | This conversion may or may not require the @mutex@ keyword depending on whether or not reading a @size_t@ is an atomic operation. |
---|
1210 | |
---|
1211 | For maximum usability, monitors use \textbf{multi-acq} semantics, which means a single thread can acquire the same monitor multiple times without deadlock. |
---|
1212 | For example, listing \ref{fig:search} uses recursion and \textbf{multi-acq} to print values inside a binary tree. |
---|
1213 | \begin{figure} |
---|
1214 | \begin{cfa}[caption={Recursive printing algorithm using \textbf{multi-acq}.},label={fig:search}] |
---|
1215 | monitor printer { ... }; |
---|
1216 | struct tree { |
---|
1217 | tree * left, right; |
---|
1218 | char * value; |
---|
1219 | }; |
---|
1220 | void print(printer & mutex p, char * v); |
---|
1221 | |
---|
1222 | void print(printer & mutex p, tree * t) { |
---|
1223 | print(p, t->value); |
---|
1224 | print(p, t->left ); |
---|
1225 | print(p, t->right); |
---|
1226 | } |
---|
1227 | \end{cfa} |
---|
1228 | \end{figure} |
---|
1229 | |
---|
1230 | Having both @mutex@ and @nomutex@ keywords can be redundant, depending on the meaning of a routine having neither of these keywords. |
---|
1231 | For example, it is reasonable that it should default to the safest option (@mutex@) when given a routine without qualifiers @void foo(counter_t & this)@, whereas assuming @nomutex@ is unsafe and may cause subtle errors. |
---|
1232 | On the other hand, @nomutex@ is the ``normal'' parameter behaviour, it effectively states explicitly that ``this routine is not special''. |
---|
1233 | 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. |
---|
1234 | Mandatory keywords would also have the added benefit of being self-documented but at the cost of extra typing. |
---|
1235 | While there are several benefits to mandatory keywords, they do bring a few challenges. |
---|
1236 | Mandatory keywords in \CFA would imply that the compiler must know without doubt whether or not a parameter is a monitor or not. |
---|
1237 | 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. |
---|
1238 | For this reason, \CFA only has the @mutex@ keyword and uses no keyword to mean @nomutex@. |
---|
1239 | |
---|
1240 | The next semantic decision is to establish when @mutex@ may be used as a type qualifier. |
---|
1241 | Consider the following declarations: |
---|
1242 | \begin{cfa} |
---|
1243 | int f1(monitor & mutex m); |
---|
1244 | int f2(const monitor & mutex m); |
---|
1245 | int f3(monitor ** mutex m); |
---|
1246 | int f4(monitor * mutex m []); |
---|
1247 | int f5(graph(monitor *) & mutex m); |
---|
1248 | \end{cfa} |
---|
1249 | The problem is to identify which object(s) should be acquired. |
---|
1250 | Furthermore, each object needs to be acquired only once. |
---|
1251 | In the case of simple routines like @f1@ and @f2@ it is easy to identify an exhaustive list of objects to acquire on entry. |
---|
1252 | Adding indirections (@f3@) still allows the compiler and programmer to identify which object is acquired. |
---|
1253 | However, adding in arrays (@f4@) makes it much harder. |
---|
1254 | Array lengths are not necessarily known in C, and even then, making sure objects are only acquired once becomes none-trivial. |
---|
1255 | This problem can be extended to absurd limits like @f5@, which uses a graph of monitors. |
---|
1256 | 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). |
---|
1257 | Also note that while routine @f3@ can be supported, meaning that monitor @**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. |
---|
1258 | However, this ambiguity is part of the C type-system with respects to arrays. |
---|
1259 | For this reason, @mutex@ is disallowed in the context where arrays may be passed: |
---|
1260 | \begin{cfa} |
---|
1261 | int f1(monitor & mutex m); // Okay : recommended case |
---|
1262 | int f2(monitor * mutex m); // Not Okay : Could be an array |
---|
1263 | int f3(monitor mutex m []); // Not Okay : Array of unknown length |
---|
1264 | int f4(monitor ** mutex m); // Not Okay : Could be an array |
---|
1265 | int f5(monitor * mutex m []); // Not Okay : Array of unknown length |
---|
1266 | \end{cfa} |
---|
1267 | Note that not all array functions are actually distinct in the type system. |
---|
1268 | However, even if the code generation could tell the difference, the extra information is still not sufficient to extend meaningfully the monitor call semantic. |
---|
1269 | |
---|
1270 | 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. |
---|
1271 | A consequence of this approach is that it extends naturally to multi-monitor calls. |
---|
1272 | \begin{cfa} |
---|
1273 | int f(MonitorA & mutex a, MonitorB & mutex b); |
---|
1274 | |
---|
1275 | MonitorA a; |
---|
1276 | MonitorB b; |
---|
1277 | f(a,b); |
---|
1278 | \end{cfa} |
---|
1279 | While OO monitors could be extended with a mutex qualifier for multiple-monitor calls, no example of this feature could be found. |
---|
1280 | The capability to acquire multiple locks before entering a critical section is called \emph{\textbf{bulk-acq}}. |
---|
1281 | In practice, writing multi-locking routines that do not lead to deadlocks is tricky. |
---|
1282 | Having language support for such a feature is therefore a significant asset for \CFA. |
---|
1283 | 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. |
---|
1284 | This consistent ordering means acquiring multiple monitors is safe from deadlock when using \textbf{bulk-acq}. |
---|
1285 | However, users can still force the acquiring order. |
---|
1286 | For example, notice which routines use @mutex@/@nomutex@ and how this affects acquiring order: |
---|
1287 | \begin{cfa} |
---|
1288 | void foo(A& mutex a, B& mutex b) { // acquire a & b |
---|
1289 | ... |
---|
1290 | } |
---|
1291 | |
---|
1292 | void bar(A& mutex a, B& /*nomutex*/ b) { // acquire a |
---|
1293 | ... foo(a, b); ... // acquire b |
---|
1294 | } |
---|
1295 | |
---|
1296 | void baz(A& /*nomutex*/ a, B& mutex b) { // acquire b |
---|
1297 | ... foo(a, b); ... // acquire a |
---|
1298 | } |
---|
1299 | \end{cfa} |
---|
1300 | The \textbf{multi-acq} monitor lock allows a monitor lock to be acquired by both @bar@ or @baz@ and acquired again in @foo@. |
---|
1301 | In the calls to @bar@ and @baz@ the monitors are acquired in opposite order. |
---|
1302 | |
---|
1303 | However, such use leads to lock acquiring order problems. |
---|
1304 | In the example above, the user uses implicit ordering in the case of function @foo@ but explicit ordering in the case of @bar@ and @baz@. |
---|
1305 | This subtle difference means that calling these routines concurrently may lead to deadlock and is therefore undefined behaviour. |
---|
1306 | As shown~\cite{Lister77}, solving this problem requires: |
---|
1307 | \begin{enumerate} |
---|
1308 | \item Dynamically tracking the monitor-call order. |
---|
1309 | \item Implement rollback semantics. |
---|
1310 | \end{enumerate} |
---|
1311 | 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}. |
---|
1312 | 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. |
---|
1313 | While \CFA provides only a partial solution, most systems provide no solution and the \CFA partial solution handles many useful cases. |
---|
1314 | |
---|
1315 | For example, \textbf{multi-acq} and \textbf{bulk-acq} can be used together in interesting ways: |
---|
1316 | \begin{cfa} |
---|
1317 | monitor bank { ... }; |
---|
1318 | |
---|
1319 | void deposit( bank & mutex b, int deposit ); |
---|
1320 | |
---|
1321 | void transfer( bank & mutex mybank, bank & mutex yourbank, int me2you) { |
---|
1322 | deposit( mybank, -me2you ); |
---|
1323 | deposit( yourbank, me2you ); |
---|
1324 | } |
---|
1325 | \end{cfa} |
---|
1326 | This example shows a trivial solution to the bank-account transfer problem~\cite{BankTransfer}. |
---|
1327 | Without \textbf{multi-acq} and \textbf{bulk-acq}, the solution to this problem is much more involved and requires careful engineering. |
---|
1328 | |
---|
1329 | |
---|
1330 | \subsection{\protect\lstinline|mutex| statement} \label{mutex-stmt} |
---|
1331 | |
---|
1332 | 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 @mutex@ statement to work around the need for unnecessary names, avoiding a major software engineering problem~\cite{2FTwoHardThings}. |
---|
1333 | Table \ref{f:mutex-stmt} shows an example of the @mutex@ statement, which introduces a new scope in which the mutual-exclusion of a set of monitor is acquired. |
---|
1334 | Beyond naming, the @mutex@ statement has no semantic difference from a routine call with @mutex@ parameters. |
---|
1335 | |
---|
1336 | \begin{table} |
---|
1337 | \begin{center} |
---|
1338 | \begin{tabular}{|c|c|} |
---|
1339 | function call & @mutex@ statement \\ |
---|
1340 | \hline |
---|
1341 | \begin{cfa}[tabsize=3] |
---|
1342 | monitor M {}; |
---|
1343 | void foo( M & mutex m1, M & mutex m2 ) { |
---|
1344 | // critical section |
---|
1345 | } |
---|
1346 | |
---|
1347 | void bar( M & m1, M & m2 ) { |
---|
1348 | foo( m1, m2 ); |
---|
1349 | } |
---|
1350 | \end{cfa}&\begin{cfa}[tabsize=3] |
---|
1351 | monitor M {}; |
---|
1352 | void bar( M & m1, M & m2 ) { |
---|
1353 | mutex(m1, m2) { |
---|
1354 | // critical section |
---|
1355 | } |
---|
1356 | } |
---|
1357 | |
---|
1358 | |
---|
1359 | \end{cfa} |
---|
1360 | \end{tabular} |
---|
1361 | \end{center} |
---|
1362 | \caption{Regular call semantics vs. \protect\lstinline|mutex| statement} |
---|
1363 | \label{f:mutex-stmt} |
---|
1364 | \end{table} |
---|
1365 | |
---|
1366 | % ====================================================================== |
---|
1367 | % ====================================================================== |
---|
1368 | \subsection{Data semantics} \label{data} |
---|
1369 | % ====================================================================== |
---|
1370 | % ====================================================================== |
---|
1371 | Once the call semantics are established, the next step is to establish data semantics. |
---|
1372 | Indeed, until now a monitor is used simply as a generic handle but in most cases monitors contain shared data. |
---|
1373 | This data should be intrinsic to the monitor declaration to prevent any accidental use of data without its appropriate protection. |
---|
1374 | For example, here is a complete version of the counter shown in section \ref{call}: |
---|
1375 | \begin{cfa} |
---|
1376 | monitor counter_t { |
---|
1377 | int value; |
---|
1378 | }; |
---|
1379 | |
---|
1380 | void ?{}(counter_t & this) { |
---|
1381 | this.cnt = 0; |
---|
1382 | } |
---|
1383 | |
---|
1384 | int ?++(counter_t & mutex this) { |
---|
1385 | return ++this.value; |
---|
1386 | } |
---|
1387 | |
---|
1388 | // need for mutex is platform dependent here |
---|
1389 | void ?{}(int * this, counter_t & mutex cnt) { |
---|
1390 | *this = (int)cnt; |
---|
1391 | } |
---|
1392 | \end{cfa} |
---|
1393 | |
---|
1394 | Like threads and coroutines, monitors are defined in terms of traits with some additional language support in the form of the @monitor@ keyword. |
---|
1395 | The monitor trait is: |
---|
1396 | \begin{cfa} |
---|
1397 | trait is_monitor(dtype T) { |
---|
1398 | monitor_desc * get_monitor( T & ); |
---|
1399 | void ^?{}( T & mutex ); |
---|
1400 | }; |
---|
1401 | \end{cfa} |
---|
1402 | Note that the destructor of a monitor must be a @mutex@ routine to prevent deallocation while a thread is accessing the monitor. |
---|
1403 | As with any object, calls to a monitor, using @mutex@ or otherwise, is undefined behaviour after the destructor has run. |
---|
1404 | |
---|
1405 | % ====================================================================== |
---|
1406 | % ====================================================================== |
---|
1407 | \section{Internal Scheduling} \label{intsched} |
---|
1408 | % ====================================================================== |
---|
1409 | % ====================================================================== |
---|
1410 | In addition to mutual exclusion, the monitors at the core of \CFA's concurrency can also be used to achieve synchronization. |
---|
1411 | With monitors, this capability is generally achieved with internal or external scheduling as in~\cite{Hoare74}. |
---|
1412 | 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 (\ie with access to the shared state), while \textbf{external scheduling} means making the decision when entering the critical section (\ie without access to the shared state). |
---|
1413 | Since internal scheduling within a single monitor is mostly a solved problem, this paper concentrates on extending internal scheduling to multiple monitors. |
---|
1414 | 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. |
---|
1415 | |
---|
1416 | First, here is a simple example of internal scheduling: |
---|
1417 | |
---|
1418 | \begin{cfa} |
---|
1419 | monitor A { |
---|
1420 | condition e; |
---|
1421 | } |
---|
1422 | |
---|
1423 | void foo(A& mutex a1, A& mutex a2) { |
---|
1424 | ... |
---|
1425 | // Wait for cooperation from bar() |
---|
1426 | wait(a1.e); |
---|
1427 | ... |
---|
1428 | } |
---|
1429 | |
---|
1430 | void bar(A& mutex a1, A& mutex a2) { |
---|
1431 | // Provide cooperation for foo() |
---|
1432 | ... |
---|
1433 | // Unblock foo |
---|
1434 | signal(a1.e); |
---|
1435 | } |
---|
1436 | \end{cfa} |
---|
1437 | There are two details to note here. |
---|
1438 | First, @signal@ is a delayed operation; it only unblocks the waiting thread when it reaches the end of the critical section. |
---|
1439 | This semantics is needed to respect mutual-exclusion, \ie the signaller and signalled thread cannot be in the monitor simultaneously. |
---|
1440 | The alternative is to return immediately after the call to @signal@, which is significantly more restrictive. |
---|
1441 | Second, in \CFA, while it is common to store a @condition@ as a field of the monitor, a @condition@ variable can be stored/created independently of a monitor. |
---|
1442 | Here routine @foo@ waits for the @signal@ from @bar@ before making further progress, ensuring a basic ordering. |
---|
1443 | |
---|
1444 | An important aspect of the implementation is that \CFA does not allow barging, which means that once function @bar@ releases the monitor, @foo@ is guaranteed to be the next thread to acquire the monitor (unless some other thread waited on the same condition). |
---|
1445 | This guarantee offers the benefit of not having to loop around waits to recheck that a condition is met. |
---|
1446 | 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. |
---|
1447 | 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. |
---|
1448 | |
---|
1449 | % ====================================================================== |
---|
1450 | % ====================================================================== |
---|
1451 | \subsection{Internal Scheduling - Multi-Monitor} |
---|
1452 | % ====================================================================== |
---|
1453 | % ====================================================================== |
---|
1454 | It is easy to understand the problem of multi-monitor scheduling using a series of pseudo-code examples. |
---|
1455 | 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. |
---|
1456 | Indeed, @wait@ statements always use the implicit condition variable as parameters and explicitly name the monitors (A and B) associated with the condition. |
---|
1457 | 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. |
---|
1458 | The example below shows the simple case of having two threads (one for each column) and a single monitor A. |
---|
1459 | |
---|
1460 | \begin{multicols}{2} |
---|
1461 | thread 1 |
---|
1462 | \begin{cfa} |
---|
1463 | acquire A |
---|
1464 | wait A |
---|
1465 | release A |
---|
1466 | \end{cfa} |
---|
1467 | |
---|
1468 | \columnbreak |
---|
1469 | |
---|
1470 | thread 2 |
---|
1471 | \begin{cfa} |
---|
1472 | acquire A |
---|
1473 | signal A |
---|
1474 | release A |
---|
1475 | \end{cfa} |
---|
1476 | \end{multicols} |
---|
1477 | One thread acquires before waiting (atomically blocking and releasing A) and the other acquires before signalling. |
---|
1478 | It is important to note here that both @wait@ and @signal@ must be called with the proper monitor(s) already acquired. |
---|
1479 | This semantic is a logical requirement for barging prevention. |
---|
1480 | |
---|
1481 | A direct extension of the previous example is a \textbf{bulk-acq} version: |
---|
1482 | \begin{multicols}{2} |
---|
1483 | \begin{cfa} |
---|
1484 | acquire A & B |
---|
1485 | wait A & B |
---|
1486 | release A & B |
---|
1487 | \end{cfa} |
---|
1488 | \columnbreak |
---|
1489 | \begin{cfa} |
---|
1490 | acquire A & B |
---|
1491 | signal A & B |
---|
1492 | release A & B |
---|
1493 | \end{cfa} |
---|
1494 | \end{multicols} |
---|
1495 | \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. |
---|
1496 | Synchronization happens between the two threads in exactly the same way and order. |
---|
1497 | The only difference is that mutual exclusion covers a group of monitors. |
---|
1498 | On the implementation side, handling multiple monitors does add a degree of complexity as the next few examples demonstrate. |
---|
1499 | |
---|
1500 | 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. |
---|
1501 | For monitors, a well-known deadlock problem is the Nested Monitor Problem~\cite{Lister77}, which occurs when a @wait@ is made by a thread that holds more than one monitor. |
---|
1502 | For example, the following cfa-code runs into the nested-monitor problem: |
---|
1503 | \begin{multicols}{2} |
---|
1504 | \begin{cfa} |
---|
1505 | acquire A |
---|
1506 | acquire B |
---|
1507 | wait B |
---|
1508 | release B |
---|
1509 | release A |
---|
1510 | \end{cfa} |
---|
1511 | |
---|
1512 | \columnbreak |
---|
1513 | |
---|
1514 | \begin{cfa} |
---|
1515 | acquire A |
---|
1516 | acquire B |
---|
1517 | signal B |
---|
1518 | release B |
---|
1519 | release A |
---|
1520 | \end{cfa} |
---|
1521 | \end{multicols} |
---|
1522 | \noindent The @wait@ only releases monitor @B@ so the signalling thread cannot acquire monitor @A@ to get to the @signal@. |
---|
1523 | Attempting release of all acquired monitors at the @wait@ introduces a different set of problems, such as releasing monitor @C@, which has nothing to do with the @signal@. |
---|
1524 | |
---|
1525 | However, for monitors as for locks, it is possible to write a program using nesting without encountering any problems if nesting is done correctly. |
---|
1526 | For example, the next cfa-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}. |
---|
1527 | |
---|
1528 | \begin{multicols}{2} |
---|
1529 | \begin{cfa} |
---|
1530 | acquire A |
---|
1531 | acquire B |
---|
1532 | wait B |
---|
1533 | release B |
---|
1534 | release A |
---|
1535 | \end{cfa} |
---|
1536 | |
---|
1537 | \columnbreak |
---|
1538 | |
---|
1539 | \begin{cfa} |
---|
1540 | |
---|
1541 | acquire B |
---|
1542 | signal B |
---|
1543 | release B |
---|
1544 | |
---|
1545 | \end{cfa} |
---|
1546 | \end{multicols} |
---|
1547 | |
---|
1548 | \noindent However, this simple refactoring may not be possible, forcing more complex restructuring. |
---|
1549 | |
---|
1550 | % ====================================================================== |
---|
1551 | % ====================================================================== |
---|
1552 | \subsection{Internal Scheduling - In Depth} |
---|
1553 | % ====================================================================== |
---|
1554 | % ====================================================================== |
---|
1555 | |
---|
1556 | A larger example is presented to show complex issues for \textbf{bulk-acq} and its implementation options are analyzed. |
---|
1557 | Figure~\ref{f:int-bulk-cfa} shows an example where \textbf{bulk-acq} adds a significant layer of complexity to the internal signalling semantics, and listing \ref{f:int-bulk-cfa} shows the corresponding \CFA code to implement the cfa-code in listing \ref{f:int-bulk-cfa}. |
---|
1558 | For the purpose of translating the given cfa-code into \CFA-code, any method of introducing a monitor is acceptable, \eg @mutex@ parameters, global variables, pointer parameters, or using locals with the @mutex@ statement. |
---|
1559 | |
---|
1560 | \begin{figure} |
---|
1561 | \begin{multicols}{2} |
---|
1562 | Waiting thread |
---|
1563 | \begin{cfa}[numbers=left] |
---|
1564 | acquire A |
---|
1565 | // Code Section 1 |
---|
1566 | acquire A & B |
---|
1567 | // Code Section 2 |
---|
1568 | wait A & B |
---|
1569 | // Code Section 3 |
---|
1570 | release A & B |
---|
1571 | // Code Section 4 |
---|
1572 | release A |
---|
1573 | \end{cfa} |
---|
1574 | \columnbreak |
---|
1575 | Signalling thread |
---|
1576 | \begin{cfa}[numbers=left, firstnumber=10,escapechar=|] |
---|
1577 | acquire A |
---|
1578 | // Code Section 5 |
---|
1579 | acquire A & B |
---|
1580 | // Code Section 6 |
---|
1581 | |\label{line:signal1}|signal A & B |
---|
1582 | // Code Section 7 |
---|
1583 | |\label{line:releaseFirst}|release A & B |
---|
1584 | // Code Section 8 |
---|
1585 | |\label{line:lastRelease}|release A |
---|
1586 | \end{cfa} |
---|
1587 | \end{multicols} |
---|
1588 | \begin{cfa}[caption={Internal scheduling with \textbf{bulk-acq}},label={f:int-bulk-cfa}] |
---|
1589 | \end{cfa} |
---|
1590 | \begin{center} |
---|
1591 | \begin{cfa}[xleftmargin=.4\textwidth] |
---|
1592 | monitor A a; |
---|
1593 | monitor B b; |
---|
1594 | condition c; |
---|
1595 | \end{cfa} |
---|
1596 | \end{center} |
---|
1597 | \begin{multicols}{2} |
---|
1598 | Waiting thread |
---|
1599 | \begin{cfa} |
---|
1600 | mutex(a) { |
---|
1601 | // Code Section 1 |
---|
1602 | mutex(a, b) { |
---|
1603 | // Code Section 2 |
---|
1604 | wait(c); |
---|
1605 | // Code Section 3 |
---|
1606 | } |
---|
1607 | // Code Section 4 |
---|
1608 | } |
---|
1609 | \end{cfa} |
---|
1610 | \columnbreak |
---|
1611 | Signalling thread |
---|
1612 | \begin{cfa} |
---|
1613 | mutex(a) { |
---|
1614 | // Code Section 5 |
---|
1615 | mutex(a, b) { |
---|
1616 | // Code Section 6 |
---|
1617 | signal(c); |
---|
1618 | // Code Section 7 |
---|
1619 | } |
---|
1620 | // Code Section 8 |
---|
1621 | } |
---|
1622 | \end{cfa} |
---|
1623 | \end{multicols} |
---|
1624 | \begin{cfa}[caption={Equivalent \CFA code for listing \ref{f:int-bulk-cfa}},label={f:int-bulk-cfa}] |
---|
1625 | \end{cfa} |
---|
1626 | \begin{multicols}{2} |
---|
1627 | Waiter |
---|
1628 | \begin{cfa}[numbers=left] |
---|
1629 | acquire A |
---|
1630 | acquire A & B |
---|
1631 | wait A & B |
---|
1632 | release A & B |
---|
1633 | release A |
---|
1634 | \end{cfa} |
---|
1635 | |
---|
1636 | \columnbreak |
---|
1637 | |
---|
1638 | Signaller |
---|
1639 | \begin{cfa}[numbers=left, firstnumber=6,escapechar=|] |
---|
1640 | acquire A |
---|
1641 | acquire A & B |
---|
1642 | signal A & B |
---|
1643 | release A & B |
---|
1644 | |\label{line:secret}|// Secretly keep B here |
---|
1645 | release A |
---|
1646 | // Wakeup waiter and transfer A & B |
---|
1647 | \end{cfa} |
---|
1648 | \end{multicols} |
---|
1649 | \begin{cfa}[caption={Figure~\ref{f:int-bulk-cfa}, with delayed signalling comments},label={f:int-secret}] |
---|
1650 | \end{cfa} |
---|
1651 | \end{figure} |
---|
1652 | |
---|
1653 | The complexity begins at code sections 4 and 8 in listing \ref{f:int-bulk-cfa}, which are where the existing semantics of internal scheduling needs to be extended for multiple monitors. |
---|
1654 | 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 cfa-code. |
---|
1655 | When the signaller thread reaches the location where it should ``release @A & B@'' (listing \ref{f:int-bulk-cfa} line \ref{line:releaseFirst}), it must actually transfer ownership of monitor @B@ to the waiting thread. |
---|
1656 | This ownership transfer is required in order to prevent barging into @B@ by another thread, since both the signalling and signalled threads still need monitor @A@. |
---|
1657 | There are three options: |
---|
1658 | |
---|
1659 | \subsubsection{Delaying Signals} |
---|
1660 | 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. |
---|
1661 | 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. |
---|
1662 | 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. |
---|
1663 | This solution releases the monitors once every monitor in a group can be released. |
---|
1664 | However, since some monitors are never released (\eg the monitor of a thread), this interpretation means a group might never be released. |
---|
1665 | 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. |
---|
1666 | |
---|
1667 | However, listing \ref{f: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. |
---|
1668 | Figure~\ref{f:dependency} shows a slightly different example where a third thread is waiting on monitor @A@, using a different condition variable. |
---|
1669 | Because the third thread is signalled when secretly holding @B@, the goal becomes unreachable. |
---|
1670 | Depending on the order of signals (listing \ref{f:dependency} line \ref{line:signal-ab} and \ref{line:signal-a}) two cases can happen: |
---|
1671 | |
---|
1672 | \paragraph{Case 1: thread $\alpha$ goes first.} In this case, the problem is that monitor @A@ needs to be passed to thread $\beta$ when thread $\alpha$ is done with it. |
---|
1673 | \paragraph{Case 2: thread $\beta$ goes first.} In this case, the problem is that monitor @B@ needs to be retained and passed to thread $\alpha$ along with monitor @A@, which can be done directly or possibly using thread $\beta$ as an intermediate. |
---|
1674 | \\ |
---|
1675 | |
---|
1676 | Note that ordering is not determined by a race condition but by whether signalled threads are enqueued in FIFO or FILO order. |
---|
1677 | 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{f:dependency}. |
---|
1678 | |
---|
1679 | 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. |
---|
1680 | |
---|
1681 | \subsubsection{Dependency graphs} |
---|
1682 | |
---|
1683 | |
---|
1684 | \begin{figure} |
---|
1685 | \begin{multicols}{3} |
---|
1686 | Thread $\alpha$ |
---|
1687 | \begin{cfa}[numbers=left, firstnumber=1] |
---|
1688 | acquire A |
---|
1689 | acquire A & B |
---|
1690 | wait A & B |
---|
1691 | release A & B |
---|
1692 | release A |
---|
1693 | \end{cfa} |
---|
1694 | \columnbreak |
---|
1695 | Thread $\gamma$ |
---|
1696 | \begin{cfa}[numbers=left, firstnumber=6, escapechar=|] |
---|
1697 | acquire A |
---|
1698 | acquire A & B |
---|
1699 | |\label{line:signal-ab}|signal A & B |
---|
1700 | |\label{line:release-ab}|release A & B |
---|
1701 | |\label{line:signal-a}|signal A |
---|
1702 | |\label{line:release-a}|release A |
---|
1703 | \end{cfa} |
---|
1704 | \columnbreak |
---|
1705 | Thread $\beta$ |
---|
1706 | \begin{cfa}[numbers=left, firstnumber=12, escapechar=|] |
---|
1707 | acquire A |
---|
1708 | wait A |
---|
1709 | |\label{line:release-aa}|release A |
---|
1710 | \end{cfa} |
---|
1711 | \end{multicols} |
---|
1712 | \begin{cfa}[caption={Pseudo-code for the three thread example.},label={f:dependency}] |
---|
1713 | \end{cfa} |
---|
1714 | \begin{center} |
---|
1715 | \input{dependency} |
---|
1716 | \end{center} |
---|
1717 | \caption{Dependency graph of the statements in listing \ref{f:dependency}} |
---|
1718 | \label{fig:dependency} |
---|
1719 | \end{figure} |
---|
1720 | |
---|
1721 | In listing \ref{f:int-bulk-cfa}, there is a solution that satisfies both barging prevention and mutual exclusion. |
---|
1722 | If ownership of both monitors is transferred to the waiter when the signaller releases @A & B@ and then the waiter transfers back ownership of @A@ back to the signaller when it releases it, then the problem is solved (@B@ is no longer in use at this point). |
---|
1723 | Dynamically finding the correct order is therefore the second possible solution. |
---|
1724 | The problem is effectively resolving a dependency graph of ownership requirements. |
---|
1725 | Here even the simplest of code snippets requires two transfers and has a super-linear complexity. |
---|
1726 | This complexity can be seen in listing \ref{f:explosion}, which is just a direct extension to three monitors, requires at least three ownership transfer and has multiple solutions. |
---|
1727 | 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. |
---|
1728 | \begin{figure} |
---|
1729 | \begin{multicols}{2} |
---|
1730 | \begin{cfa} |
---|
1731 | acquire A |
---|
1732 | acquire B |
---|
1733 | acquire C |
---|
1734 | wait A & B & C |
---|
1735 | release C |
---|
1736 | release B |
---|
1737 | release A |
---|
1738 | \end{cfa} |
---|
1739 | |
---|
1740 | \columnbreak |
---|
1741 | |
---|
1742 | \begin{cfa} |
---|
1743 | acquire A |
---|
1744 | acquire B |
---|
1745 | acquire C |
---|
1746 | signal A & B & C |
---|
1747 | release C |
---|
1748 | release B |
---|
1749 | release A |
---|
1750 | \end{cfa} |
---|
1751 | \end{multicols} |
---|
1752 | \begin{cfa}[caption={Extension to three monitors of listing \ref{f:int-bulk-cfa}},label={f:explosion}] |
---|
1753 | \end{cfa} |
---|
1754 | \end{figure} |
---|
1755 | |
---|
1756 | Given the three threads example in listing \ref{f: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 (\eg $\alpha1$ must happen before $\alpha2$). |
---|
1757 | 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. |
---|
1758 | Resolving dependency graphs being a complex and expensive endeavour, this solution is not the preferred one. |
---|
1759 | |
---|
1760 | \subsubsection{Partial Signalling} \label{partial-sig} |
---|
1761 | Finally, the solution that is chosen for \CFA is to use partial signalling. |
---|
1762 | Again using listing \ref{f:int-bulk-cfa}, the partial signalling solution transfers ownership of monitor @B@ at lines \ref{line:signal1} to the waiter but does not wake the waiting thread since it is still using monitor @A@. |
---|
1763 | Only when it reaches line \ref{line:lastRelease} does it actually wake up the waiting thread. |
---|
1764 | 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. |
---|
1765 | This solution has a much simpler implementation than a dependency graph solving algorithms, which is why it was chosen. |
---|
1766 | Furthermore, after being fully implemented, this solution does not appear to have any significant downsides. |
---|
1767 | |
---|
1768 | Using partial signalling, listing \ref{f:dependency} can be solved easily: |
---|
1769 | \begin{itemize} |
---|
1770 | \item When thread $\gamma$ reaches line \ref{line:release-ab} it transfers monitor @B@ to thread $\alpha$ and continues to hold monitor @A@. |
---|
1771 | \item When thread $\gamma$ reaches line \ref{line:release-a} it transfers monitor @A@ to thread $\beta$ and wakes it up. |
---|
1772 | \item When thread $\beta$ reaches line \ref{line:release-aa} it transfers monitor @A@ to thread $\alpha$ and wakes it up. |
---|
1773 | \end{itemize} |
---|
1774 | |
---|
1775 | % ====================================================================== |
---|
1776 | % ====================================================================== |
---|
1777 | \subsection{Signalling: Now or Later} |
---|
1778 | % ====================================================================== |
---|
1779 | % ====================================================================== |
---|
1780 | \begin{table} |
---|
1781 | \begin{tabular}{|c|c|} |
---|
1782 | @signal@ & @signal_block@ \\ |
---|
1783 | \hline |
---|
1784 | \begin{cfa}[tabsize=3] |
---|
1785 | monitor DatingService { |
---|
1786 | // compatibility codes |
---|
1787 | enum{ CCodes = 20 }; |
---|
1788 | |
---|
1789 | int girlPhoneNo |
---|
1790 | int boyPhoneNo; |
---|
1791 | }; |
---|
1792 | |
---|
1793 | condition girls[CCodes]; |
---|
1794 | condition boys [CCodes]; |
---|
1795 | condition exchange; |
---|
1796 | |
---|
1797 | int girl(int phoneNo, int cfa) { |
---|
1798 | // no compatible boy ? |
---|
1799 | if(empty(boys[cfa])) { |
---|
1800 | wait(girls[cfa]); // wait for boy |
---|
1801 | girlPhoneNo = phoneNo; // make phone number available |
---|
1802 | signal(exchange); // wake boy from chair |
---|
1803 | } else { |
---|
1804 | girlPhoneNo = phoneNo; // make phone number available |
---|
1805 | signal(boys[cfa]); // wake boy |
---|
1806 | wait(exchange); // sit in chair |
---|
1807 | } |
---|
1808 | return boyPhoneNo; |
---|
1809 | } |
---|
1810 | int boy(int phoneNo, int cfa) { |
---|
1811 | // same as above |
---|
1812 | // with boy/girl interchanged |
---|
1813 | } |
---|
1814 | \end{cfa}&\begin{cfa}[tabsize=3] |
---|
1815 | monitor DatingService { |
---|
1816 | |
---|
1817 | enum{ CCodes = 20 }; // compatibility codes |
---|
1818 | |
---|
1819 | int girlPhoneNo; |
---|
1820 | int boyPhoneNo; |
---|
1821 | }; |
---|
1822 | |
---|
1823 | condition girls[CCodes]; |
---|
1824 | condition boys [CCodes]; |
---|
1825 | // exchange is not needed |
---|
1826 | |
---|
1827 | int girl(int phoneNo, int cfa) { |
---|
1828 | // no compatible boy ? |
---|
1829 | if(empty(boys[cfa])) { |
---|
1830 | wait(girls[cfa]); // wait for boy |
---|
1831 | girlPhoneNo = phoneNo; // make phone number available |
---|
1832 | signal(exchange); // wake boy from chair |
---|
1833 | } else { |
---|
1834 | girlPhoneNo = phoneNo; // make phone number available |
---|
1835 | signal_block(boys[cfa]); // wake boy |
---|
1836 | |
---|
1837 | // second handshake unnecessary |
---|
1838 | |
---|
1839 | } |
---|
1840 | return boyPhoneNo; |
---|
1841 | } |
---|
1842 | |
---|
1843 | int boy(int phoneNo, int cfa) { |
---|
1844 | // same as above |
---|
1845 | // with boy/girl interchanged |
---|
1846 | } |
---|
1847 | \end{cfa} |
---|
1848 | \end{tabular} |
---|
1849 | \caption{Dating service example using \protect\lstinline|signal| and \protect\lstinline|signal_block|. } |
---|
1850 | \label{tbl:datingservice} |
---|
1851 | \end{table} |
---|
1852 | An important note is that, until now, signalling a monitor was a delayed operation. |
---|
1853 | The ownership of the monitor is transferred only when the monitor would have otherwise been released, not at the point of the @signal@ statement. |
---|
1854 | 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 @signal_block@ routine. |
---|
1855 | |
---|
1856 | The example in table \ref{tbl:datingservice} highlights the difference in behaviour. |
---|
1857 | As mentioned, @signal@ only transfers ownership once the current critical section exits; this behaviour requires additional synchronization when a two-way handshake is needed. |
---|
1858 | To avoid this explicit synchronization, the @condition@ type offers the @signal_block@ routine, which handles the two-way handshake as shown in the example. |
---|
1859 | This feature removes the need for a second condition variables and simplifies programming. |
---|
1860 | Like every other monitor semantic, @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 @signal_block@, meaning no other thread can acquire the monitor either before or after the call. |
---|
1861 | |
---|
1862 | % ====================================================================== |
---|
1863 | % ====================================================================== |
---|
1864 | \section{External scheduling} \label{extsched} |
---|
1865 | % ====================================================================== |
---|
1866 | % ====================================================================== |
---|
1867 | An alternative to internal scheduling is external scheduling (see Table~\ref{tbl:sched}). |
---|
1868 | \begin{table} |
---|
1869 | \begin{tabular}{|c|c|c|} |
---|
1870 | Internal Scheduling & External Scheduling & Go\\ |
---|
1871 | \hline |
---|
1872 | \begin{uC++}[tabsize=3] |
---|
1873 | _Monitor Semaphore { |
---|
1874 | condition c; |
---|
1875 | bool inUse; |
---|
1876 | public: |
---|
1877 | void P() { |
---|
1878 | if(inUse) |
---|
1879 | wait(c); |
---|
1880 | inUse = true; |
---|
1881 | } |
---|
1882 | void V() { |
---|
1883 | inUse = false; |
---|
1884 | signal(c); |
---|
1885 | } |
---|
1886 | } |
---|
1887 | \end{uC++}&\begin{uC++}[tabsize=3] |
---|
1888 | _Monitor Semaphore { |
---|
1889 | |
---|
1890 | bool inUse; |
---|
1891 | public: |
---|
1892 | void P() { |
---|
1893 | if(inUse) |
---|
1894 | _Accept(V); |
---|
1895 | inUse = true; |
---|
1896 | } |
---|
1897 | void V() { |
---|
1898 | inUse = false; |
---|
1899 | |
---|
1900 | } |
---|
1901 | } |
---|
1902 | \end{uC++}&\begin{Go}[tabsize=3] |
---|
1903 | type MySem struct { |
---|
1904 | inUse bool |
---|
1905 | c chan bool |
---|
1906 | } |
---|
1907 | |
---|
1908 | // acquire |
---|
1909 | func (s MySem) P() { |
---|
1910 | if s.inUse { |
---|
1911 | select { |
---|
1912 | case <-s.c: |
---|
1913 | } |
---|
1914 | } |
---|
1915 | s.inUse = true |
---|
1916 | } |
---|
1917 | |
---|
1918 | // release |
---|
1919 | func (s MySem) V() { |
---|
1920 | s.inUse = false |
---|
1921 | |
---|
1922 | // This actually deadlocks |
---|
1923 | // when single thread |
---|
1924 | s.c <- false |
---|
1925 | } |
---|
1926 | \end{Go} |
---|
1927 | \end{tabular} |
---|
1928 | \caption{Different forms of scheduling.} |
---|
1929 | \label{tbl:sched} |
---|
1930 | \end{table} |
---|
1931 | This method is more constrained and explicit, which helps users reduce the non-deterministic nature of concurrency. |
---|
1932 | Indeed, as the following examples demonstrate, external scheduling allows users to wait for events from other threads without the concern of unrelated events occurring. |
---|
1933 | External scheduling can generally be done either in terms of control flow (\eg Ada with @accept@, \uC with @_Accept@) or in terms of data (\eg Go with channels). |
---|
1934 | 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. |
---|
1935 | Two challenges specific to \CFA arise when trying to add external scheduling with loose object definitions and multiple-monitor routines. |
---|
1936 | The previous example shows a simple use @_Accept@ versus @wait@/@signal@ and its advantages. |
---|
1937 | Note that while other languages often use @accept@/@select@ as the core external scheduling keyword, \CFA uses @waitfor@ to prevent name collisions with existing socket \textbf{api}s. |
---|
1938 | |
---|
1939 | For the @P@ member above using internal scheduling, the call to @wait@ only guarantees that @V@ is the last routine to access the monitor, allowing a third routine, say @isInUse()@, acquire mutual exclusion several times while routine @P@ is waiting. |
---|
1940 | On the other hand, external scheduling guarantees that while routine @P@ is waiting, no other routine than @V@ can acquire the monitor. |
---|
1941 | |
---|
1942 | % ====================================================================== |
---|
1943 | % ====================================================================== |
---|
1944 | \subsection{Loose Object Definitions} |
---|
1945 | % ====================================================================== |
---|
1946 | % ====================================================================== |
---|
1947 | In \uC, a monitor class declaration includes an exhaustive list of monitor operations. |
---|
1948 | Since \CFA is not object oriented, monitors become both more difficult to implement and less clear for a user: |
---|
1949 | |
---|
1950 | \begin{cfa} |
---|
1951 | monitor A {}; |
---|
1952 | |
---|
1953 | void f(A & mutex a); |
---|
1954 | void g(A & mutex a) { |
---|
1955 | waitfor(f); // Obvious which f() to wait for |
---|
1956 | } |
---|
1957 | |
---|
1958 | void f(A & mutex a, int); // New different F added in scope |
---|
1959 | void h(A & mutex a) { |
---|
1960 | waitfor(f); // Less obvious which f() to wait for |
---|
1961 | } |
---|
1962 | \end{cfa} |
---|
1963 | |
---|
1964 | Furthermore, external scheduling is an example where implementation constraints become visible from the interface. |
---|
1965 | Here is the cfa-code for the entering phase of a monitor: |
---|
1966 | \begin{center} |
---|
1967 | \begin{tabular}{l} |
---|
1968 | \begin{cfa} |
---|
1969 | if monitor is free |
---|
1970 | enter |
---|
1971 | elif already own the monitor |
---|
1972 | continue |
---|
1973 | elif monitor accepts me |
---|
1974 | enter |
---|
1975 | else |
---|
1976 | block |
---|
1977 | \end{cfa} |
---|
1978 | \end{tabular} |
---|
1979 | \end{center} |
---|
1980 | For the first two conditions, it is easy to implement a check that can evaluate the condition in a few instructions. |
---|
1981 | However, a fast check for @monitor accepts me@ is much harder to implement depending on the constraints put on the monitors. |
---|
1982 | Indeed, monitors are often expressed as an entry queue and some acceptor queue as in Figure~\ref{fig:ClassicalMonitor}. |
---|
1983 | |
---|
1984 | \begin{figure} |
---|
1985 | \centering |
---|
1986 | \subfloat[Classical Monitor] { |
---|
1987 | \label{fig:ClassicalMonitor} |
---|
1988 | {\resizebox{0.45\textwidth}{!}{\input{monitor}}} |
---|
1989 | }% subfloat |
---|
1990 | \qquad |
---|
1991 | \subfloat[\textbf{bulk-acq} Monitor] { |
---|
1992 | \label{fig:BulkMonitor} |
---|
1993 | {\resizebox{0.45\textwidth}{!}{\input{ext_monitor}}} |
---|
1994 | }% subfloat |
---|
1995 | \caption{External Scheduling Monitor} |
---|
1996 | \end{figure} |
---|
1997 | |
---|
1998 | There are other alternatives to these pictures, but in the case of the left picture, implementing a fast accept check is relatively easy. |
---|
1999 | 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 (\eg 128) of mutex members. |
---|
2000 | This approach requires a unique dense ordering of routines with an upper-bound and that ordering must be consistent across translation units. |
---|
2001 | For OO languages these constraints are common, since objects only offer adding member routines consistently across translation units via inheritance. |
---|
2002 | However, in \CFA users can extend objects with mutex routines that are only visible in certain translation unit. |
---|
2003 | 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. |
---|
2004 | |
---|
2005 | The alternative is to alter the implementation as in Figure~\ref{fig:BulkMonitor}. |
---|
2006 | Here, the mutex routine called is associated with a thread on the entry queue while a list of acceptable routines is kept separate. |
---|
2007 | Generating a mask dynamically means that the storage for the mask information can vary between calls to @waitfor@, allowing for more flexibility and extensions. |
---|
2008 | Storing an array of accepted function pointers replaces the single instruction bitmask comparison with dereferencing a pointer followed by a linear search. |
---|
2009 | Furthermore, supporting nested external scheduling (\eg listing \ref{f:nest-ext}) may now require additional searches for the @waitfor@ statement to check if a routine is already queued. |
---|
2010 | |
---|
2011 | \begin{figure} |
---|
2012 | \begin{cfa}[caption={Example of nested external scheduling},label={f:nest-ext}] |
---|
2013 | monitor M {}; |
---|
2014 | void foo( M & mutex a ) {} |
---|
2015 | void bar( M & mutex b ) { |
---|
2016 | // Nested in the waitfor(bar, c) call |
---|
2017 | waitfor(foo, b); |
---|
2018 | } |
---|
2019 | void baz( M & mutex c ) { |
---|
2020 | waitfor(bar, c); |
---|
2021 | } |
---|
2022 | |
---|
2023 | \end{cfa} |
---|
2024 | \end{figure} |
---|
2025 | |
---|
2026 | 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. |
---|
2027 | These details are omitted from the picture for the sake of simplicity. |
---|
2028 | |
---|
2029 | At this point, a decision must be made between flexibility and performance. |
---|
2030 | 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. |
---|
2031 | Here, however, the cost of flexibility cannot be trivially removed. |
---|
2032 | In the end, the most flexible approach has been chosen since it allows users to write programs that would otherwise be hard to write. |
---|
2033 | 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. |
---|
2034 | |
---|
2035 | % ====================================================================== |
---|
2036 | % ====================================================================== |
---|
2037 | \subsection{Multi-Monitor Scheduling} |
---|
2038 | % ====================================================================== |
---|
2039 | % ====================================================================== |
---|
2040 | |
---|
2041 | External scheduling, like internal scheduling, becomes significantly more complex when introducing multi-monitor syntax. |
---|
2042 | Even in the simplest possible case, some new semantics needs to be established: |
---|
2043 | \begin{cfa} |
---|
2044 | monitor M {}; |
---|
2045 | |
---|
2046 | void f(M & mutex a); |
---|
2047 | |
---|
2048 | void g(M & mutex b, M & mutex c) { |
---|
2049 | waitfor(f); // two monitors M => unknown which to pass to f(M & mutex) |
---|
2050 | } |
---|
2051 | \end{cfa} |
---|
2052 | The obvious solution is to specify the correct monitor as follows: |
---|
2053 | |
---|
2054 | \begin{cfa} |
---|
2055 | monitor M {}; |
---|
2056 | |
---|
2057 | void f(M & mutex a); |
---|
2058 | |
---|
2059 | void g(M & mutex a, M & mutex b) { |
---|
2060 | // wait for call to f with argument b |
---|
2061 | waitfor(f, b); |
---|
2062 | } |
---|
2063 | \end{cfa} |
---|
2064 | This syntax is unambiguous. |
---|
2065 | Both locks are acquired and kept by @g@. |
---|
2066 | When routine @f@ is called, the lock for monitor @b@ is temporarily transferred from @g@ to @f@ (while @g@ still holds lock @a@). |
---|
2067 | This behaviour can be extended to the multi-monitor @waitfor@ statement as follows. |
---|
2068 | |
---|
2069 | \begin{cfa} |
---|
2070 | monitor M {}; |
---|
2071 | |
---|
2072 | void f(M & mutex a, M & mutex b); |
---|
2073 | |
---|
2074 | void g(M & mutex a, M & mutex b) { |
---|
2075 | // wait for call to f with arguments a and b |
---|
2076 | waitfor(f, a, b); |
---|
2077 | } |
---|
2078 | \end{cfa} |
---|
2079 | |
---|
2080 | Note that the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired in the routine. @waitfor@ used in any other context is undefined behaviour. |
---|
2081 | |
---|
2082 | An important behaviour to note is when a set of monitors only match partially: |
---|
2083 | |
---|
2084 | \begin{cfa} |
---|
2085 | mutex struct A {}; |
---|
2086 | |
---|
2087 | mutex struct B {}; |
---|
2088 | |
---|
2089 | void g(A & mutex a, B & mutex b) { |
---|
2090 | waitfor(f, a, b); |
---|
2091 | } |
---|
2092 | |
---|
2093 | A a1, a2; |
---|
2094 | B b; |
---|
2095 | |
---|
2096 | void foo() { |
---|
2097 | g(a1, b); // block on accept |
---|
2098 | } |
---|
2099 | |
---|
2100 | void bar() { |
---|
2101 | f(a2, b); // fulfill cooperation |
---|
2102 | } |
---|
2103 | \end{cfa} |
---|
2104 | 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. |
---|
2105 | In both cases, partially matching monitor sets does not wakeup the waiting thread. |
---|
2106 | It is also important to note that in the case of external scheduling the order of parameters is irrelevant; @waitfor(f,a,b)@ and @waitfor(f,b,a)@ are indistinguishable waiting condition. |
---|
2107 | |
---|
2108 | % ====================================================================== |
---|
2109 | % ====================================================================== |
---|
2110 | \subsection{\protect\lstinline|waitfor| Semantics} |
---|
2111 | % ====================================================================== |
---|
2112 | % ====================================================================== |
---|
2113 | |
---|
2114 | Syntactically, the @waitfor@ statement takes a function identifier and a set of monitors. |
---|
2115 | 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 @waitfor@ statement. |
---|
2116 | It checks that the set of monitors passed in matches the requirements for a function call. |
---|
2117 | Figure~\ref{f:waitfor} shows various usages of the waitfor statement and which are acceptable. |
---|
2118 | The choice of the function type is made ignoring any non-@mutex@ parameter. |
---|
2119 | One limitation of the current implementation is that it does not handle overloading, but overloading is possible. |
---|
2120 | \begin{figure} |
---|
2121 | \begin{cfa}[caption={Various correct and incorrect uses of the waitfor statement},label={f:waitfor}] |
---|
2122 | monitor A{}; |
---|
2123 | monitor B{}; |
---|
2124 | |
---|
2125 | void f1( A & mutex ); |
---|
2126 | void f2( A & mutex, B & mutex ); |
---|
2127 | void f3( A & mutex, int ); |
---|
2128 | void f4( A & mutex, int ); |
---|
2129 | void f4( A & mutex, double ); |
---|
2130 | |
---|
2131 | void foo( A & mutex a1, A & mutex a2, B & mutex b1, B & b2 ) { |
---|
2132 | A * ap = & a1; |
---|
2133 | void (*fp)( A & mutex ) = f1; |
---|
2134 | |
---|
2135 | waitfor(f1, a1); // Correct : 1 monitor case |
---|
2136 | waitfor(f2, a1, b1); // Correct : 2 monitor case |
---|
2137 | waitfor(f3, a1); // Correct : non-mutex arguments are ignored |
---|
2138 | waitfor(f1, *ap); // Correct : expression as argument |
---|
2139 | |
---|
2140 | waitfor(f1, a1, b1); // Incorrect : Too many mutex arguments |
---|
2141 | waitfor(f2, a1); // Incorrect : Too few mutex arguments |
---|
2142 | waitfor(f2, a1, a2); // Incorrect : Mutex arguments don't match |
---|
2143 | waitfor(f1, 1); // Incorrect : 1 not a mutex argument |
---|
2144 | waitfor(f9, a1); // Incorrect : f9 function does not exist |
---|
2145 | waitfor(*fp, a1 ); // Incorrect : fp not an identifier |
---|
2146 | waitfor(f4, a1); // Incorrect : f4 ambiguous |
---|
2147 | |
---|
2148 | waitfor(f2, a1, b2); // Undefined behaviour : b2 not mutex |
---|
2149 | } |
---|
2150 | \end{cfa} |
---|
2151 | \end{figure} |
---|
2152 | |
---|
2153 | Finally, for added flexibility, \CFA supports constructing a complex @waitfor@ statement using the @or@, @timeout@ and @else@. |
---|
2154 | Indeed, multiple @waitfor@ clauses can be chained together using @or@; this chain forms a single statement that uses baton pass to any function that fits one of the function+monitor set passed in. |
---|
2155 | To enable users to tell which accepted function executed, @waitfor@s are followed by a statement (including the null statement @;@) or a compound statement, which is executed after the clause is triggered. |
---|
2156 | A @waitfor@ chain can also be followed by a @timeout@, to signify an upper bound on the wait, or an @else@, to signify that the call should be non-blocking, which checks for a matching function call already arrived and otherwise continues. |
---|
2157 | Any and all of these clauses can be preceded by a @when@ condition to dynamically toggle the accept clauses on or off based on some current state. |
---|
2158 | Figure~\ref{f:waitfor2} demonstrates several complex masks and some incorrect ones. |
---|
2159 | |
---|
2160 | \begin{figure} |
---|
2161 | \lstset{language=CFA,deletedelim=**[is][]{`}{`}} |
---|
2162 | \begin{cfa} |
---|
2163 | monitor A{}; |
---|
2164 | |
---|
2165 | void f1( A & mutex ); |
---|
2166 | void f2( A & mutex ); |
---|
2167 | |
---|
2168 | void foo( A & mutex a, bool b, int t ) { |
---|
2169 | waitfor(f1, a); $\C{// Correct : blocking case}$ |
---|
2170 | |
---|
2171 | waitfor(f1, a) { $\C{// Correct : block with statement}$ |
---|
2172 | sout | "f1" | endl; |
---|
2173 | } |
---|
2174 | waitfor(f1, a) { $\C{// Correct : block waiting for f1 or f2}$ |
---|
2175 | sout | "f1" | endl; |
---|
2176 | } or waitfor(f2, a) { |
---|
2177 | sout | "f2" | endl; |
---|
2178 | } |
---|
2179 | waitfor(f1, a); or else; $\C{// Correct : non-blocking case}$ |
---|
2180 | |
---|
2181 | waitfor(f1, a) { $\C{// Correct : non-blocking case}$ |
---|
2182 | sout | "blocked" | endl; |
---|
2183 | } or else { |
---|
2184 | sout | "didn't block" | endl; |
---|
2185 | } |
---|
2186 | waitfor(f1, a) { $\C{// Correct : block at most 10 seconds}$ |
---|
2187 | sout | "blocked" | endl; |
---|
2188 | } or timeout( 10`s) { |
---|
2189 | sout | "didn't block" | endl; |
---|
2190 | } |
---|
2191 | // Correct : block only if b == true if b == false, don't even make the call |
---|
2192 | when(b) waitfor(f1, a); |
---|
2193 | |
---|
2194 | // Correct : block only if b == true if b == false, make non-blocking call |
---|
2195 | waitfor(f1, a); or when(!b) else; |
---|
2196 | |
---|
2197 | // Correct : block only of t > 1 |
---|
2198 | waitfor(f1, a); or when(t > 1) timeout(t); or else; |
---|
2199 | |
---|
2200 | // Incorrect : timeout clause is dead code |
---|
2201 | waitfor(f1, a); or timeout(t); or else; |
---|
2202 | |
---|
2203 | // Incorrect : order must be waitfor [or waitfor... [or timeout] [or else]] |
---|
2204 | timeout(t); or waitfor(f1, a); or else; |
---|
2205 | } |
---|
2206 | \end{cfa} |
---|
2207 | \caption{Correct and incorrect uses of the or, else, and timeout clause around a waitfor statement} |
---|
2208 | \label{f:waitfor2} |
---|
2209 | \end{figure} |
---|
2210 | |
---|
2211 | % ====================================================================== |
---|
2212 | % ====================================================================== |
---|
2213 | \subsection{Waiting For The Destructor} |
---|
2214 | % ====================================================================== |
---|
2215 | % ====================================================================== |
---|
2216 | An interesting use for the @waitfor@ statement is destructor semantics. |
---|
2217 | Indeed, the @waitfor@ statement can accept any @mutex@ routine, which includes the destructor (see section \ref{data}). |
---|
2218 | 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. |
---|
2219 | The simplest approach is to disallow @waitfor@ on a destructor. |
---|
2220 | 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 @mutex@ routine, similarly to how a condition is signalled. |
---|
2221 | \begin{figure} |
---|
2222 | \begin{cfa}[caption={Example of an executor which executes action in series until the destructor is called.},label={f:dtor-order}] |
---|
2223 | monitor Executer {}; |
---|
2224 | struct Action; |
---|
2225 | |
---|
2226 | void ^?{} (Executer & mutex this); |
---|
2227 | void execute(Executer & mutex this, const Action & ); |
---|
2228 | void run (Executer & mutex this) { |
---|
2229 | while(true) { |
---|
2230 | waitfor(execute, this); |
---|
2231 | or waitfor(^?{} , this) { |
---|
2232 | break; |
---|
2233 | } |
---|
2234 | } |
---|
2235 | } |
---|
2236 | \end{cfa} |
---|
2237 | \end{figure} |
---|
2238 | For example, listing \ref{f:dtor-order} shows an example of an executor with an infinite loop, which waits for the destructor to break out of this loop. |
---|
2239 | Switching the semantic meaning introduces an idiomatic way to terminate a task and/or wait for its termination via destruction. |
---|
2240 | |
---|
2241 | |
---|
2242 | % ###### # ###### # # # ####### # ### ##### # # |
---|
2243 | % # # # # # # # # # # # # # # # ## ## |
---|
2244 | % # # # # # # # # # # # # # # # # # # |
---|
2245 | % ###### # # ###### # # # # ##### # # ##### # # # |
---|
2246 | % # ####### # # ####### # # # # # # # # |
---|
2247 | % # # # # # # # # # # # # # # # # |
---|
2248 | % # # # # # # # ####### ####### ####### ####### ### ##### # # |
---|
2249 | \section{Parallelism} |
---|
2250 | Historically, computer performance was about processor speeds and instruction counts. |
---|
2251 | However, with heat dissipation being a direct consequence of speed increase, parallelism has become the new source for increased performance~\cite{Sutter05, Sutter05b}. |
---|
2252 | In this decade, it is no longer reasonable to create a high-performance application without caring about parallelism. |
---|
2253 | Indeed, parallelism is an important aspect of performance and more specifically throughput and hardware utilization. |
---|
2254 | The lowest-level approach of parallelism is to use \textbf{kthread} in combination with semantics like @fork@, @join@, \etc. |
---|
2255 | However, since these have significant costs and limitations, \textbf{kthread} are now mostly used as an implementation tool rather than a user oriented one. |
---|
2256 | There are several alternatives to solve these issues that all have strengths and weaknesses. |
---|
2257 | 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. |
---|
2258 | |
---|
2259 | \section{Paradigms} |
---|
2260 | \subsection{User-Level Threads} |
---|
2261 | A direct improvement on the \textbf{kthread} approach is to use \textbf{uthread}. |
---|
2262 | These threads offer most of the same features that the operating system already provides but can be used on a much larger scale. |
---|
2263 | 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. |
---|
2264 | 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. |
---|
2265 | 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. |
---|
2266 | |
---|
2267 | Examples of languages that support \textbf{uthread} are Erlang~\cite{Erlang} and \uC~\cite{uC++book}. |
---|
2268 | |
---|
2269 | \subsection{Fibers : User-Level Threads Without Preemption} \label{fibers} |
---|
2270 | A popular variant of \textbf{uthread} is what is often referred to as \textbf{fiber}. |
---|
2271 | However, \textbf{fiber} do not present meaningful semantic differences with \textbf{uthread}. |
---|
2272 | The significant difference between \textbf{uthread} and \textbf{fiber} is the lack of \textbf{preemption} in the latter. |
---|
2273 | 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. |
---|
2274 | Therefore this proposal largely ignores fibers. |
---|
2275 | |
---|
2276 | An example of a language that uses fibers is Go~\cite{Go} |
---|
2277 | |
---|
2278 | \subsection{Jobs and Thread Pools} |
---|
2279 | An approach on the opposite end of the spectrum is to base parallelism on \textbf{pool}. |
---|
2280 | Indeed, \textbf{pool} offer limited flexibility but at the benefit of a simpler user interface. |
---|
2281 | 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. |
---|
2282 | This approach means users need not worry about concurrency but significantly limit the interaction that can occur among jobs. |
---|
2283 | Indeed, any \textbf{job} that blocks also block the underlying worker, which effectively means the CPU utilization, and therefore throughput, suffers noticeably. |
---|
2284 | It can be argued that a solution to this problem is to use more workers than available cores. |
---|
2285 | 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. |
---|
2286 | |
---|
2287 | The gold standard of this implementation is Intel's TBB library~\cite{TBB}. |
---|
2288 | |
---|
2289 | \subsection{Paradigm Performance} |
---|
2290 | 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. |
---|
2291 | Indeed, in many situations one of these paradigms may show better performance but it all strongly depends on the workload. |
---|
2292 | 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 (\ie no thread stack per job). |
---|
2293 | However, interactions among jobs can easily exacerbate contention. |
---|
2294 | 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. |
---|
2295 | Finally, if the units of uninterrupted work are large, enough the paradigm choice is largely amortized by the actual work done. |
---|
2296 | |
---|
2297 | \section{The \protect\CFA\ Kernel : Processors, Clusters and Threads}\label{kernel} |
---|
2298 | 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}. |
---|
2299 | 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. |
---|
2300 | A \textbf{cfacluster} also offers a pluggable scheduler that can optimize the workload generated by the \textbf{uthread}. |
---|
2301 | |
---|
2302 | \textbf{cfacluster} have not been fully implemented in the context of this paper. |
---|
2303 | Currently \CFA only supports one \textbf{cfacluster}, the initial one. |
---|
2304 | |
---|
2305 | \subsection{Future Work: Machine Setup}\label{machine} |
---|
2306 | While this was not done in the context of this paper, another important aspect of clusters is affinity. |
---|
2307 | While many common desktop and laptop PCs have homogeneous CPUs, other devices often have more heterogeneous setups. |
---|
2308 | 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. |
---|
2309 | 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. |
---|
2310 | |
---|
2311 | \subsection{Paradigms}\label{cfaparadigms} |
---|
2312 | Given these building blocks, it is possible to reproduce all three of the popular paradigms. |
---|
2313 | Indeed, \textbf{uthread} is the default paradigm in \CFA. |
---|
2314 | However, disabling \textbf{preemption} on the \textbf{cfacluster} means \textbf{cfathread} effectively become \textbf{fiber}. |
---|
2315 | 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. |
---|
2316 | Finally, it is possible to build executors for thread pools from \textbf{uthread} or \textbf{fiber}, which includes specialized jobs like actors~\cite{Actors}. |
---|
2317 | |
---|
2318 | |
---|
2319 | |
---|
2320 | \section{Behind the Scenes} |
---|
2321 | There are several challenges specific to \CFA when implementing concurrency. |
---|
2322 | These challenges are a direct result of \textbf{bulk-acq} and loose object definitions. |
---|
2323 | These two constraints are the root cause of most design decisions in the implementation. |
---|
2324 | Furthermore, to avoid contention from dynamically allocating memory in a concurrent environment, the internal-scheduling design is (almost) entirely free of mallocs. |
---|
2325 | 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. |
---|
2326 | This extra goal means that memory management is a constant concern in the design of the system. |
---|
2327 | |
---|
2328 | The main memory concern for concurrency is queues. |
---|
2329 | 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. |
---|
2330 | 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. |
---|
2331 | 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. |
---|
2332 | 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. |
---|
2333 | The threads and the condition both have a fixed amount of memory, while @mutex@ routines and blocking calls allow for an unbound amount, within the stack size. |
---|
2334 | |
---|
2335 | 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. |
---|
2336 | |
---|
2337 | % ====================================================================== |
---|
2338 | % ====================================================================== |
---|
2339 | \section{Mutex Routines} |
---|
2340 | % ====================================================================== |
---|
2341 | % ====================================================================== |
---|
2342 | |
---|
2343 | The first step towards the monitor implementation is simple @mutex@ routines. |
---|
2344 | In the single monitor case, mutual-exclusion is done using the entry/exit procedure in listing \ref{f:entry1}. |
---|
2345 | The entry/exit procedures do not have to be extended to support multiple monitors. |
---|
2346 | Indeed it is sufficient to enter/leave monitors one-by-one as long as the order is correct to prevent deadlock~\cite{Havender68}. |
---|
2347 | In \CFA, ordering of monitor acquisition relies on memory ordering. |
---|
2348 | 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. |
---|
2349 | When a mutex call is made, the concerned monitors are aggregated into a variable-length pointer array and sorted based on pointer values. |
---|
2350 | This array persists for the entire duration of the mutual-exclusion and its ordering reused extensively. |
---|
2351 | \begin{figure} |
---|
2352 | \begin{multicols}{2} |
---|
2353 | Entry |
---|
2354 | \begin{cfa} |
---|
2355 | if monitor is free |
---|
2356 | enter |
---|
2357 | elif already own the monitor |
---|
2358 | continue |
---|
2359 | else |
---|
2360 | block |
---|
2361 | increment recursions |
---|
2362 | \end{cfa} |
---|
2363 | \columnbreak |
---|
2364 | Exit |
---|
2365 | \begin{cfa} |
---|
2366 | decrement recursion |
---|
2367 | if recursion == 0 |
---|
2368 | if entry queue not empty |
---|
2369 | wake-up thread |
---|
2370 | \end{cfa} |
---|
2371 | \end{multicols} |
---|
2372 | \begin{cfa}[caption={Initial entry and exit routine for monitors},label={f:entry1}] |
---|
2373 | \end{cfa} |
---|
2374 | \end{figure} |
---|
2375 | |
---|
2376 | \subsection{Details: Interaction with polymorphism} |
---|
2377 | 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. |
---|
2378 | However, it is shown that entry-point locking solves most of the issues. |
---|
2379 | |
---|
2380 | First of all, interaction between @otype@ polymorphism (see Section~\ref{s:ParametricPolymorphism}) and monitors is impossible since monitors do not support copying. |
---|
2381 | Therefore, the main question is how to support @dtype@ polymorphism. |
---|
2382 | It is important to present the difference between the two acquiring options: \textbf{callsite-locking} and entry-point locking, \ie acquiring the monitors before making a mutex routine-call or as the first operation of the mutex routine-call. |
---|
2383 | For example: |
---|
2384 | \begin{table} |
---|
2385 | \begin{center} |
---|
2386 | \begin{tabular}{|c|c|c|} |
---|
2387 | Mutex & \textbf{callsite-locking} & \textbf{entry-point-locking} \\ |
---|
2388 | call & cfa-code & cfa-code \\ |
---|
2389 | \hline |
---|
2390 | \begin{cfa}[tabsize=3] |
---|
2391 | void foo(monitor& mutex a){ |
---|
2392 | |
---|
2393 | // Do Work |
---|
2394 | //... |
---|
2395 | |
---|
2396 | } |
---|
2397 | |
---|
2398 | void main() { |
---|
2399 | monitor a; |
---|
2400 | |
---|
2401 | foo(a); |
---|
2402 | |
---|
2403 | } |
---|
2404 | \end{cfa} & \begin{cfa}[tabsize=3] |
---|
2405 | foo(& a) { |
---|
2406 | |
---|
2407 | // Do Work |
---|
2408 | //... |
---|
2409 | |
---|
2410 | } |
---|
2411 | |
---|
2412 | main() { |
---|
2413 | monitor a; |
---|
2414 | acquire(a); |
---|
2415 | foo(a); |
---|
2416 | release(a); |
---|
2417 | } |
---|
2418 | \end{cfa} & \begin{cfa}[tabsize=3] |
---|
2419 | foo(& a) { |
---|
2420 | acquire(a); |
---|
2421 | // Do Work |
---|
2422 | //... |
---|
2423 | release(a); |
---|
2424 | } |
---|
2425 | |
---|
2426 | main() { |
---|
2427 | monitor a; |
---|
2428 | |
---|
2429 | foo(a); |
---|
2430 | |
---|
2431 | } |
---|
2432 | \end{cfa} |
---|
2433 | \end{tabular} |
---|
2434 | \end{center} |
---|
2435 | \caption{Call-site vs entry-point locking for mutex calls} |
---|
2436 | \label{tbl:locking-site} |
---|
2437 | \end{table} |
---|
2438 | |
---|
2439 | Note the @mutex@ keyword relies on the type system, which means that in cases where a generic monitor-routine is desired, writing the mutex routine is possible with the proper trait, \eg: |
---|
2440 | \begin{cfa} |
---|
2441 | // Incorrect: T may not be monitor |
---|
2442 | forall(dtype T) |
---|
2443 | void foo(T * mutex t); |
---|
2444 | |
---|
2445 | // Correct: this function only works on monitors (any monitor) |
---|
2446 | forall(dtype T | is_monitor(T)) |
---|
2447 | void bar(T * mutex t)); |
---|
2448 | \end{cfa} |
---|
2449 | |
---|
2450 | Both entry point and \textbf{callsite-locking} are feasible implementations. |
---|
2451 | 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. |
---|
2452 | 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, \ie the function body. |
---|
2453 | For example, the monitor call can appear in the middle of an expression. |
---|
2454 | 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. |
---|
2455 | |
---|
2456 | % ====================================================================== |
---|
2457 | % ====================================================================== |
---|
2458 | \section{Threading} \label{impl:thread} |
---|
2459 | % ====================================================================== |
---|
2460 | % ====================================================================== |
---|
2461 | |
---|
2462 | Figure \ref{fig:system1} shows a high-level picture if the \CFA runtime system in regards to concurrency. |
---|
2463 | Each component of the picture is explained in detail in the flowing sections. |
---|
2464 | |
---|
2465 | \begin{figure} |
---|
2466 | \begin{center} |
---|
2467 | {\resizebox{\textwidth}{!}{\input{system.pstex_t}}} |
---|
2468 | \end{center} |
---|
2469 | \caption{Overview of the entire system} |
---|
2470 | \label{fig:system1} |
---|
2471 | \end{figure} |
---|
2472 | |
---|
2473 | \subsection{Processors} |
---|
2474 | Parallelism in \CFA is built around using processors to specify how much parallelism is desired. \CFA processors are object wrappers around kernel threads, specifically @pthread@s in the current implementation of \CFA. |
---|
2475 | Indeed, any parallelism must go through operating-system libraries. |
---|
2476 | However, \textbf{uthread} are still the main source of concurrency, processors are simply the underlying source of parallelism. |
---|
2477 | Indeed, processor \textbf{kthread} simply fetch a \textbf{uthread} from the scheduler and run it; they are effectively executers for user-threads. |
---|
2478 | 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. |
---|
2479 | Processors internally use coroutines to take advantage of the existing context-switching semantics. |
---|
2480 | |
---|
2481 | \subsection{Stack Management} |
---|
2482 | One of the challenges of this system is to reduce the footprint as much as possible. |
---|
2483 | Specifically, all @pthread@s created also have a stack created with them, which should be used as much as possible. |
---|
2484 | 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. |
---|
2485 | The exception to this rule is the Main Processor, \ie the initial \textbf{kthread} that is given to any program. |
---|
2486 | 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. |
---|
2487 | |
---|
2488 | \subsection{Context Switching} |
---|
2489 | 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. |
---|
2490 | To improve performance and simplicity, context-switching is implemented using the following assumption: all context-switches happen inside a specific function call. |
---|
2491 | 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. |
---|
2492 | Note that the instruction pointer can be left untouched since the context-switch is always inside the same function. |
---|
2493 | Threads, however, do not context-switch between each other directly. |
---|
2494 | They context-switch to the scheduler. |
---|
2495 | 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. |
---|
2496 | Obviously, this doubles the context-switch cost because threads must context-switch to an intermediate stack. |
---|
2497 | The alternative 1-step context-switch uses the stack of the ``from'' thread to schedule and then context-switches directly to the ``to'' thread. |
---|
2498 | However, the performance of the 2-step context-switch is still superior to a @pthread_yield@ (see section \ref{results}). |
---|
2499 | 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 @SwitchToFiber@~\cite{switchToWindows} routine). |
---|
2500 | This option is not currently present in \CFA, but the changes required to add it are strictly additive. |
---|
2501 | |
---|
2502 | \subsection{Preemption} \label{preemption} |
---|
2503 | Finally, an important aspect for any complete threading system is preemption. |
---|
2504 | 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. |
---|
2505 | Indeed, preemption is desirable because it adds a degree of isolation among threads. |
---|
2506 | 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. |
---|
2507 | Obviously, preemption is not optimal for every workload. |
---|
2508 | However any preemptive system can become a cooperative system by making the time slices extremely large. |
---|
2509 | Therefore, \CFA uses a preemptive threading system. |
---|
2510 | |
---|
2511 | Preemption in \CFA\footnote{Note that the implementation of preemption is strongly tied with the underlying threading system. |
---|
2512 | 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. |
---|
2513 | Every processor keeps track of the current time and registers an expiration time with the preemption system. |
---|
2514 | 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. |
---|
2515 | These timers use the Linux signal {\tt SIGALRM}, which is delivered to the process rather than the kernel-thread. |
---|
2516 | 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, \ie: |
---|
2517 | \begin{quote} |
---|
2518 | A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked. |
---|
2519 | If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal. |
---|
2520 | SIGNAL(7) - Linux Programmer's Manual |
---|
2521 | \end{quote} |
---|
2522 | 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. |
---|
2523 | |
---|
2524 | Now because of how involuntary context-switches are handled, the kernel thread handling {\tt SIGALRM} cannot also be a processor thread. |
---|
2525 | 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. |
---|
2526 | 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. |
---|
2527 | As a result, a signal handler can start on one kernel thread and terminate on a second kernel thread (but the same user thread). |
---|
2528 | 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. |
---|
2529 | 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.}. |
---|
2530 | However, since the kernel thread handling preemption requires a different signal mask, executing user threads on the kernel-alarm thread can cause deadlocks. |
---|
2531 | For this reason, the alarm thread is in a tight loop around a system call to @sigwaitinfo@, requiring very little CPU time for preemption. |
---|
2532 | One final detail about the alarm thread is how to wake it when additional communication is required (\eg on thread termination). |
---|
2533 | This unblocking is also done using {\tt SIGALRM}, but sent through the @pthread_sigqueue@. |
---|
2534 | Indeed, @sigwait@ can differentiate signals sent from @pthread_sigqueue@ from signals sent from alarms or the kernel. |
---|
2535 | |
---|
2536 | \subsection{Scheduler} |
---|
2537 | Finally, an aspect that was not mentioned yet is the scheduling algorithm. |
---|
2538 | Currently, the \CFA scheduler uses a single ready queue for all processors, which is the simplest approach to scheduling. |
---|
2539 | Further discussion on scheduling is present in section \ref{futur:sched}. |
---|
2540 | |
---|
2541 | % ====================================================================== |
---|
2542 | % ====================================================================== |
---|
2543 | \section{Internal Scheduling} \label{impl:intsched} |
---|
2544 | % ====================================================================== |
---|
2545 | % ====================================================================== |
---|
2546 | The following figure is the traditional illustration of a monitor (repeated from page~\pageref{fig:ClassicalMonitor} for convenience): |
---|
2547 | |
---|
2548 | \begin{figure} |
---|
2549 | \begin{center} |
---|
2550 | {\resizebox{0.4\textwidth}{!}{\input{monitor}}} |
---|
2551 | \end{center} |
---|
2552 | \caption{Traditional illustration of a monitor} |
---|
2553 | \end{figure} |
---|
2554 | |
---|
2555 | This picture has several components, the two most important being the entry queue and the AS-stack. |
---|
2556 | 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. |
---|
2557 | |
---|
2558 | For \CFA, this picture does not have support for blocking multiple monitors on a single condition. |
---|
2559 | To support \textbf{bulk-acq} two changes to this picture are required. |
---|
2560 | First, it is no longer helpful to attach the condition to \emph{a single} monitor. |
---|
2561 | Secondly, the thread waiting on the condition has to be separated across multiple monitors, seen in figure \ref{fig:monitor_cfa}. |
---|
2562 | |
---|
2563 | \begin{figure} |
---|
2564 | \begin{center} |
---|
2565 | {\resizebox{0.8\textwidth}{!}{\input{int_monitor}}} |
---|
2566 | \end{center} |
---|
2567 | \caption{Illustration of \CFA Monitor} |
---|
2568 | \label{fig:monitor_cfa} |
---|
2569 | \end{figure} |
---|
2570 | |
---|
2571 | This picture and the proper entry and leave algorithms (see listing \ref{f:entry2}) is the fundamental implementation of internal scheduling. |
---|
2572 | 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. |
---|
2573 | The thread is woken up when all the pieces have popped from the AS-stacks and made active. |
---|
2574 | In this picture, the threads are split into halves but this is only because there are two monitors. |
---|
2575 | For a specific signalling operation every monitor needs a piece of thread on its AS-stack. |
---|
2576 | |
---|
2577 | \begin{figure} |
---|
2578 | \begin{multicols}{2} |
---|
2579 | Entry |
---|
2580 | \begin{cfa} |
---|
2581 | if monitor is free |
---|
2582 | enter |
---|
2583 | elif already own the monitor |
---|
2584 | continue |
---|
2585 | else |
---|
2586 | block |
---|
2587 | increment recursion |
---|
2588 | |
---|
2589 | \end{cfa} |
---|
2590 | \columnbreak |
---|
2591 | Exit |
---|
2592 | \begin{cfa} |
---|
2593 | decrement recursion |
---|
2594 | if recursion == 0 |
---|
2595 | if signal_stack not empty |
---|
2596 | set_owner to thread |
---|
2597 | if all monitors ready |
---|
2598 | wake-up thread |
---|
2599 | |
---|
2600 | if entry queue not empty |
---|
2601 | wake-up thread |
---|
2602 | \end{cfa} |
---|
2603 | \end{multicols} |
---|
2604 | \begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling},label={f:entry2}] |
---|
2605 | \end{cfa} |
---|
2606 | \end{figure} |
---|
2607 | |
---|
2608 | The solution discussed in \ref{intsched} can be seen in the exit routine of listing \ref{f:entry2}. |
---|
2609 | 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. |
---|
2610 | This solution is deadlock safe as well as preventing any potential barging. |
---|
2611 | 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 @wait@ and @signal_block@ routines. |
---|
2612 | |
---|
2613 | \begin{figure} |
---|
2614 | \begin{center} |
---|
2615 | {\resizebox{0.8\textwidth}{!}{\input{monitor_structs.pstex_t}}} |
---|
2616 | \end{center} |
---|
2617 | \caption{Data structures involved in internal/external scheduling} |
---|
2618 | \label{fig:structs} |
---|
2619 | \end{figure} |
---|
2620 | |
---|
2621 | Figure \ref{fig:structs} shows a high-level representation of these data structures. |
---|
2622 | The main idea behind them is that, a thread cannot contain an arbitrary number of intrusive ``next'' pointers for linking onto monitors. |
---|
2623 | The @condition node@ is the data structure that is queued onto a condition variable and, when signalled, the condition queue is popped and each @condition criterion@ is moved to the AS-stack. |
---|
2624 | 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{f:entry2}. |
---|
2625 | |
---|
2626 | % ====================================================================== |
---|
2627 | % ====================================================================== |
---|
2628 | \section{External Scheduling} |
---|
2629 | % ====================================================================== |
---|
2630 | % ====================================================================== |
---|
2631 | 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}. |
---|
2632 | For internal scheduling, these queues are part of condition variables, which are still unique for a given scheduling operation (\ie no signal statement uses multiple conditions). |
---|
2633 | However, in the case of external scheduling, there is no equivalent object which is associated with @waitfor@ statements. |
---|
2634 | This absence means the queues holding the waiting threads must be stored inside at least one of the monitors that is acquired. |
---|
2635 | These monitors being the only objects that have sufficient lifetime and are available on both sides of the @waitfor@ statement. |
---|
2636 | This requires an algorithm to choose which monitor holds the relevant queue. |
---|
2637 | It is also important that said algorithm be independent of the order in which users list parameters. |
---|
2638 | 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. |
---|
2639 | This assumes that the lock acquiring order is static for the lifetime of all concerned objects but that is a reasonable constraint. |
---|
2640 | |
---|
2641 | This algorithm choice has two consequences: |
---|
2642 | \begin{itemize} |
---|
2643 | \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. |
---|
2644 | These queues need to contain a set of monitors for each of the waiting threads. |
---|
2645 | 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. |
---|
2646 | \item The queue of the lowest priority monitor is both required and potentially unused. |
---|
2647 | 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. |
---|
2648 | \end{itemize} |
---|
2649 | Therefore, the following modifications need to be made to support external scheduling: |
---|
2650 | \begin{itemize} |
---|
2651 | \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. |
---|
2652 | The @mutex@ routine already has all the required information on its stack, so the thread only needs to keep a pointer to that information. |
---|
2653 | \item The monitors need to keep a mask of acceptable routines. |
---|
2654 | This mask contains for each acceptable routine, a routine pointer and an array of monitors to go with it. |
---|
2655 | It also needs storage to keep track of which routine was accepted. |
---|
2656 | 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. |
---|
2657 | Note that if a thread has acquired two monitors but executes a @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. |
---|
2658 | This becomes relevant when @when@ clauses affect the number of monitors passed to a @waitfor@ statement. |
---|
2659 | \item The entry/exit routines need to be updated as shown in listing \ref{f:entry3}. |
---|
2660 | \end{itemize} |
---|
2661 | |
---|
2662 | \subsection{External Scheduling - Destructors} |
---|
2663 | Finally, to support the ordering inversion of destructors, the code generation needs to be modified to use a special entry routine. |
---|
2664 | This routine is needed because of the storage requirements of the call order inversion. |
---|
2665 | 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. |
---|
2666 | For regular @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. |
---|
2667 | The @waitfor@ semantics can then be adjusted correspondingly, as seen in listing \ref{f:entry-dtor} |
---|
2668 | |
---|
2669 | \begin{figure} |
---|
2670 | \begin{multicols}{2} |
---|
2671 | Entry |
---|
2672 | \begin{cfa} |
---|
2673 | if monitor is free |
---|
2674 | enter |
---|
2675 | elif already own the monitor |
---|
2676 | continue |
---|
2677 | elif matches waitfor mask |
---|
2678 | push criteria to AS-stack |
---|
2679 | continue |
---|
2680 | else |
---|
2681 | block |
---|
2682 | increment recursion |
---|
2683 | \end{cfa} |
---|
2684 | \columnbreak |
---|
2685 | Exit |
---|
2686 | \begin{cfa} |
---|
2687 | decrement recursion |
---|
2688 | if recursion == 0 |
---|
2689 | if signal_stack not empty |
---|
2690 | set_owner to thread |
---|
2691 | if all monitors ready |
---|
2692 | wake-up thread |
---|
2693 | endif |
---|
2694 | endif |
---|
2695 | |
---|
2696 | if entry queue not empty |
---|
2697 | wake-up thread |
---|
2698 | endif |
---|
2699 | \end{cfa} |
---|
2700 | \end{multicols} |
---|
2701 | \begin{cfa}[caption={Entry and exit routine for monitors with internal scheduling and external scheduling},label={f:entry3}] |
---|
2702 | \end{cfa} |
---|
2703 | \end{figure} |
---|
2704 | |
---|
2705 | \begin{figure} |
---|
2706 | \begin{multicols}{2} |
---|
2707 | Destructor Entry |
---|
2708 | \begin{cfa} |
---|
2709 | if monitor is free |
---|
2710 | enter |
---|
2711 | elif already own the monitor |
---|
2712 | increment recursion |
---|
2713 | return |
---|
2714 | create wait context |
---|
2715 | if matches waitfor mask |
---|
2716 | reset mask |
---|
2717 | push self to AS-stack |
---|
2718 | baton pass |
---|
2719 | else |
---|
2720 | wait |
---|
2721 | increment recursion |
---|
2722 | \end{cfa} |
---|
2723 | \columnbreak |
---|
2724 | Waitfor |
---|
2725 | \begin{cfa} |
---|
2726 | if matching thread is already there |
---|
2727 | if found destructor |
---|
2728 | push destructor to AS-stack |
---|
2729 | unlock all monitors |
---|
2730 | else |
---|
2731 | push self to AS-stack |
---|
2732 | baton pass |
---|
2733 | endif |
---|
2734 | return |
---|
2735 | endif |
---|
2736 | if non-blocking |
---|
2737 | Unlock all monitors |
---|
2738 | Return |
---|
2739 | endif |
---|
2740 | |
---|
2741 | push self to AS-stack |
---|
2742 | set waitfor mask |
---|
2743 | block |
---|
2744 | return |
---|
2745 | \end{cfa} |
---|
2746 | \end{multicols} |
---|
2747 | \begin{cfa}[caption={Pseudo code for the \protect\lstinline|waitfor| routine and the \protect\lstinline|mutex| entry routine for destructors},label={f:entry-dtor}] |
---|
2748 | \end{cfa} |
---|
2749 | \end{figure} |
---|
2750 | |
---|
2751 | |
---|
2752 | % ====================================================================== |
---|
2753 | % ====================================================================== |
---|
2754 | \section{Putting It All Together} |
---|
2755 | % ====================================================================== |
---|
2756 | % ====================================================================== |
---|
2757 | |
---|
2758 | |
---|
2759 | \section{Threads As Monitors} |
---|
2760 | As it was subtly alluded in section \ref{threads}, @thread@s in \CFA are in fact monitors, which means that all monitor features are available when using threads. |
---|
2761 | For example, here is a very simple two thread pipeline that could be used for a simulator of a game engine: |
---|
2762 | \begin{figure} |
---|
2763 | \begin{cfa}[caption={Toy simulator using \protect\lstinline|thread|s and \protect\lstinline|monitor|s.},label={f:engine-v1}] |
---|
2764 | // Visualization declaration |
---|
2765 | thread Renderer {} renderer; |
---|
2766 | Frame * simulate( Simulator & this ); |
---|
2767 | |
---|
2768 | // Simulation declaration |
---|
2769 | thread Simulator{} simulator; |
---|
2770 | void render( Renderer & this ); |
---|
2771 | |
---|
2772 | // Blocking call used as communication |
---|
2773 | void draw( Renderer & mutex this, Frame * frame ); |
---|
2774 | |
---|
2775 | // Simulation loop |
---|
2776 | void main( Simulator & this ) { |
---|
2777 | while( true ) { |
---|
2778 | Frame * frame = simulate( this ); |
---|
2779 | draw( renderer, frame ); |
---|
2780 | } |
---|
2781 | } |
---|
2782 | |
---|
2783 | // Rendering loop |
---|
2784 | void main( Renderer & this ) { |
---|
2785 | while( true ) { |
---|
2786 | waitfor( draw, this ); |
---|
2787 | render( this ); |
---|
2788 | } |
---|
2789 | } |
---|
2790 | \end{cfa} |
---|
2791 | \end{figure} |
---|
2792 | 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. |
---|
2793 | Luckily, the monitor semantics can also be used to clearly enforce a shutdown order in a concise manner: |
---|
2794 | \begin{figure} |
---|
2795 | \begin{cfa}[caption={Same toy simulator with proper termination condition.},label={f:engine-v2}] |
---|
2796 | // Visualization declaration |
---|
2797 | thread Renderer {} renderer; |
---|
2798 | Frame * simulate( Simulator & this ); |
---|
2799 | |
---|
2800 | // Simulation declaration |
---|
2801 | thread Simulator{} simulator; |
---|
2802 | void render( Renderer & this ); |
---|
2803 | |
---|
2804 | // Blocking call used as communication |
---|
2805 | void draw( Renderer & mutex this, Frame * frame ); |
---|
2806 | |
---|
2807 | // Simulation loop |
---|
2808 | void main( Simulator & this ) { |
---|
2809 | while( true ) { |
---|
2810 | Frame * frame = simulate( this ); |
---|
2811 | draw( renderer, frame ); |
---|
2812 | |
---|
2813 | // Exit main loop after the last frame |
---|
2814 | if( frame->is_last ) break; |
---|
2815 | } |
---|
2816 | } |
---|
2817 | |
---|
2818 | // Rendering loop |
---|
2819 | void main( Renderer & this ) { |
---|
2820 | while( true ) { |
---|
2821 | waitfor( draw, this ); |
---|
2822 | or waitfor( ^?{}, this ) { |
---|
2823 | // Add an exit condition |
---|
2824 | break; |
---|
2825 | } |
---|
2826 | |
---|
2827 | render( this ); |
---|
2828 | } |
---|
2829 | } |
---|
2830 | |
---|
2831 | // Call destructor for simulator once simulator finishes |
---|
2832 | // Call destructor for renderer to signify shutdown |
---|
2833 | \end{cfa} |
---|
2834 | \end{figure} |
---|
2835 | |
---|
2836 | \section{Fibers \& Threads} |
---|
2837 | As mentioned in section \ref{preemption}, \CFA uses preemptive threads by default but can use fibers on demand. |
---|
2838 | Currently, using fibers is done by adding the following line of code to the program~: |
---|
2839 | \begin{cfa} |
---|
2840 | unsigned int default_preemption() { |
---|
2841 | return 0; |
---|
2842 | } |
---|
2843 | \end{cfa} |
---|
2844 | This function is called by the kernel to fetch the default preemption rate, where 0 signifies an infinite time-slice, \ie no preemption. |
---|
2845 | However, once clusters are fully implemented, it will be possible to create fibers and \textbf{uthread} in the same system, as in listing \ref{f:fiber-uthread} |
---|
2846 | \begin{figure} |
---|
2847 | \lstset{language=CFA,deletedelim=**[is][]{`}{`}} |
---|
2848 | \begin{cfa}[caption={Using fibers and \textbf{uthread} side-by-side in \CFA},label={f:fiber-uthread}] |
---|
2849 | // Cluster forward declaration |
---|
2850 | struct cluster; |
---|
2851 | |
---|
2852 | // Processor forward declaration |
---|
2853 | struct processor; |
---|
2854 | |
---|
2855 | // Construct clusters with a preemption rate |
---|
2856 | void ?{}(cluster& this, unsigned int rate); |
---|
2857 | // Construct processor and add it to cluster |
---|
2858 | void ?{}(processor& this, cluster& cluster); |
---|
2859 | // Construct thread and schedule it on cluster |
---|
2860 | void ?{}(thread& this, cluster& cluster); |
---|
2861 | |
---|
2862 | // Declare two clusters |
---|
2863 | cluster thread_cluster = { 10`ms }; // Preempt every 10 ms |
---|
2864 | cluster fibers_cluster = { 0 }; // Never preempt |
---|
2865 | |
---|
2866 | // Construct 4 processors |
---|
2867 | processor processors[4] = { |
---|
2868 | //2 for the thread cluster |
---|
2869 | thread_cluster; |
---|
2870 | thread_cluster; |
---|
2871 | //2 for the fibers cluster |
---|
2872 | fibers_cluster; |
---|
2873 | fibers_cluster; |
---|
2874 | }; |
---|
2875 | |
---|
2876 | // Declares thread |
---|
2877 | thread UThread {}; |
---|
2878 | void ?{}(UThread& this) { |
---|
2879 | // Construct underlying thread to automatically |
---|
2880 | // be scheduled on the thread cluster |
---|
2881 | (this){ thread_cluster } |
---|
2882 | } |
---|
2883 | |
---|
2884 | void main(UThread & this); |
---|
2885 | |
---|
2886 | // Declares fibers |
---|
2887 | thread Fiber {}; |
---|
2888 | void ?{}(Fiber& this) { |
---|
2889 | // Construct underlying thread to automatically |
---|
2890 | // be scheduled on the fiber cluster |
---|
2891 | (this.__thread){ fibers_cluster } |
---|
2892 | } |
---|
2893 | |
---|
2894 | void main(Fiber & this); |
---|
2895 | \end{cfa} |
---|
2896 | \end{figure} |
---|
2897 | |
---|
2898 | |
---|
2899 | % ====================================================================== |
---|
2900 | % ====================================================================== |
---|
2901 | \section{Performance Results} \label{results} |
---|
2902 | % ====================================================================== |
---|
2903 | % ====================================================================== |
---|
2904 | \section{Machine Setup} |
---|
2905 | Table \ref{tab:machine} shows the characteristics of the machine used to run the benchmarks. |
---|
2906 | All tests were made on this machine. |
---|
2907 | \begin{table} |
---|
2908 | \begin{center} |
---|
2909 | \begin{tabular}{| l | r | l | r |} |
---|
2910 | \hline |
---|
2911 | Architecture & x86\_64 & NUMA node(s) & 8 \\ |
---|
2912 | \hline |
---|
2913 | CPU op-mode(s) & 32-bit, 64-bit & Model name & AMD Opteron\texttrademark Processor 6380 \\ |
---|
2914 | \hline |
---|
2915 | Byte Order & Little Endian & CPU Freq & 2.5\si{\giga\hertz} \\ |
---|
2916 | \hline |
---|
2917 | CPU(s) & 64 & L1d cache & \SI{16}{\kibi\byte} \\ |
---|
2918 | \hline |
---|
2919 | Thread(s) per core & 2 & L1i cache & \SI{64}{\kibi\byte} \\ |
---|
2920 | \hline |
---|
2921 | Core(s) per socket & 8 & L2 cache & \SI{2048}{\kibi\byte} \\ |
---|
2922 | \hline |
---|
2923 | Socket(s) & 4 & L3 cache & \SI{6144}{\kibi\byte} \\ |
---|
2924 | \hline |
---|
2925 | \hline |
---|
2926 | Operating system & Ubuntu 16.04.3 LTS & Kernel & Linux 4.4-97-generic \\ |
---|
2927 | \hline |
---|
2928 | Compiler & GCC 6.3 & Translator & CFA 1 \\ |
---|
2929 | \hline |
---|
2930 | Java version & OpenJDK-9 & Go version & 1.9.2 \\ |
---|
2931 | \hline |
---|
2932 | \end{tabular} |
---|
2933 | \end{center} |
---|
2934 | \caption{Machine setup used for the tests} |
---|
2935 | \label{tab:machine} |
---|
2936 | \end{table} |
---|
2937 | |
---|
2938 | \section{Micro Benchmarks} |
---|
2939 | All benchmarks are run using the same harness to produce the results, seen as the @BENCH()@ macro in the following examples. |
---|
2940 | This macro uses the following logic to benchmark the code: |
---|
2941 | \begin{cfa} |
---|
2942 | #define BENCH(run, result) \ |
---|
2943 | before = gettime(); \ |
---|
2944 | run; \ |
---|
2945 | after = gettime(); \ |
---|
2946 | result = (after - before) / N; |
---|
2947 | \end{cfa} |
---|
2948 | The method used to get time is @clock_gettime(CLOCK_THREAD_CPUTIME_ID);@. |
---|
2949 | Each benchmark is using many iterations of a simple call to measure the cost of the call. |
---|
2950 | The specific number of iterations depends on the specific benchmark. |
---|
2951 | |
---|
2952 | \subsection{Context-Switching} |
---|
2953 | The first interesting benchmark is to measure how long context-switches take. |
---|
2954 | The simplest approach to do this is to yield on a thread, which executes a 2-step context switch. |
---|
2955 | 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). |
---|
2956 | 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. |
---|
2957 | Figure~\ref{f:ctx-switch} shows the code for coroutines and threads with the results in table \ref{tab:ctx-switch}. |
---|
2958 | All omitted tests are functionally identical to one of these tests. |
---|
2959 | The difference between coroutines and threads can be attributed to the cost of scheduling. |
---|
2960 | \begin{figure} |
---|
2961 | \begin{multicols}{2} |
---|
2962 | \CFA Coroutines |
---|
2963 | \begin{cfa} |
---|
2964 | coroutine GreatSuspender {}; |
---|
2965 | void main(GreatSuspender& this) { |
---|
2966 | while(true) { suspend(); } |
---|
2967 | } |
---|
2968 | int main() { |
---|
2969 | GreatSuspender s; |
---|
2970 | resume(s); |
---|
2971 | BENCH( |
---|
2972 | for(size_t i=0; i<n; i++) { |
---|
2973 | resume(s); |
---|
2974 | }, |
---|
2975 | result |
---|
2976 | ) |
---|
2977 | printf("%llu\n", result); |
---|
2978 | } |
---|
2979 | \end{cfa} |
---|
2980 | \columnbreak |
---|
2981 | \CFA Threads |
---|
2982 | \begin{cfa} |
---|
2983 | |
---|
2984 | |
---|
2985 | |
---|
2986 | |
---|
2987 | int main() { |
---|
2988 | |
---|
2989 | |
---|
2990 | BENCH( |
---|
2991 | for(size_t i=0; i<n; i++) { |
---|
2992 | yield(); |
---|
2993 | }, |
---|
2994 | result |
---|
2995 | ) |
---|
2996 | printf("%llu\n", result); |
---|
2997 | } |
---|
2998 | \end{cfa} |
---|
2999 | \end{multicols} |
---|
3000 | \begin{cfa}[caption={\CFA benchmark code used to measure context-switches for coroutines and threads.},label={f:ctx-switch}] |
---|
3001 | \end{cfa} |
---|
3002 | \end{figure} |
---|
3003 | |
---|
3004 | \begin{table} |
---|
3005 | \begin{center} |
---|
3006 | \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |} |
---|
3007 | \cline{2-4} |
---|
3008 | \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\ |
---|
3009 | \hline |
---|
3010 | Kernel Thread & 241.5 & 243.86 & 5.08 \\ |
---|
3011 | \CFA Coroutine & 38 & 38 & 0 \\ |
---|
3012 | \CFA Thread & 103 & 102.96 & 2.96 \\ |
---|
3013 | \uC Coroutine & 46 & 45.86 & 0.35 \\ |
---|
3014 | \uC Thread & 98 & 99.11 & 1.42 \\ |
---|
3015 | Goroutine & 150 & 149.96 & 3.16 \\ |
---|
3016 | Java Thread & 289 & 290.68 & 8.72 \\ |
---|
3017 | \hline |
---|
3018 | \end{tabular} |
---|
3019 | \end{center} |
---|
3020 | \caption{Context Switch comparison. |
---|
3021 | All numbers are in nanoseconds(\si{\nano\second})} |
---|
3022 | \label{tab:ctx-switch} |
---|
3023 | \end{table} |
---|
3024 | |
---|
3025 | \subsection{Mutual-Exclusion} |
---|
3026 | The next interesting benchmark is to measure the overhead to enter/leave a critical-section. |
---|
3027 | For monitors, the simplest approach is to measure how long it takes to enter and leave a monitor routine. |
---|
3028 | Figure~\ref{f:mutex} shows the code for \CFA. |
---|
3029 | To put the results in context, the cost of entering a non-inline function and the cost of acquiring and releasing a @pthread_mutex@ lock is also measured. |
---|
3030 | The results can be shown in table \ref{tab:mutex}. |
---|
3031 | |
---|
3032 | \begin{figure} |
---|
3033 | \begin{cfa}[caption={\CFA benchmark code used to measure mutex routines.},label={f:mutex}] |
---|
3034 | monitor M {}; |
---|
3035 | void __attribute__((noinline)) call( M & mutex m /*, m2, m3, m4*/ ) {} |
---|
3036 | |
---|
3037 | int main() { |
---|
3038 | M m/*, m2, m3, m4*/; |
---|
3039 | BENCH( |
---|
3040 | for(size_t i=0; i<n; i++) { |
---|
3041 | call(m/*, m2, m3, m4*/); |
---|
3042 | }, |
---|
3043 | result |
---|
3044 | ) |
---|
3045 | printf("%llu\n", result); |
---|
3046 | } |
---|
3047 | \end{cfa} |
---|
3048 | \end{figure} |
---|
3049 | |
---|
3050 | \begin{table} |
---|
3051 | \begin{center} |
---|
3052 | \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |} |
---|
3053 | \cline{2-4} |
---|
3054 | \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\ |
---|
3055 | \hline |
---|
3056 | C routine & 2 & 2 & 0 \\ |
---|
3057 | FetchAdd + FetchSub & 26 & 26 & 0 \\ |
---|
3058 | Pthreads Mutex Lock & 31 & 31.86 & 0.99 \\ |
---|
3059 | \uC @monitor@ member routine & 30 & 30 & 0 \\ |
---|
3060 | \CFA @mutex@ routine, 1 argument & 41 & 41.57 & 0.9 \\ |
---|
3061 | \CFA @mutex@ routine, 2 argument & 76 & 76.96 & 1.57 \\ |
---|
3062 | \CFA @mutex@ routine, 4 argument & 145 & 146.68 & 3.85 \\ |
---|
3063 | Java synchronized routine & 27 & 28.57 & 2.6 \\ |
---|
3064 | \hline |
---|
3065 | \end{tabular} |
---|
3066 | \end{center} |
---|
3067 | \caption{Mutex routine comparison. |
---|
3068 | All numbers are in nanoseconds(\si{\nano\second})} |
---|
3069 | \label{tab:mutex} |
---|
3070 | \end{table} |
---|
3071 | |
---|
3072 | \subsection{Internal Scheduling} |
---|
3073 | The internal-scheduling benchmark measures the cost of waiting on and signalling a condition variable. |
---|
3074 | Figure~\ref{f:int-sched} shows the code for \CFA, with results table \ref{tab:int-sched}. |
---|
3075 | As with all other benchmarks, all omitted tests are functionally identical to one of these tests. |
---|
3076 | |
---|
3077 | \begin{figure} |
---|
3078 | \begin{cfa}[caption={Benchmark code for internal scheduling},label={f:int-sched}] |
---|
3079 | volatile int go = 0; |
---|
3080 | condition c; |
---|
3081 | monitor M {}; |
---|
3082 | M m1; |
---|
3083 | |
---|
3084 | void __attribute__((noinline)) do_call( M & mutex a1 ) { signal(c); } |
---|
3085 | |
---|
3086 | thread T {}; |
---|
3087 | void ^?{}( T & mutex this ) {} |
---|
3088 | void main( T & this ) { |
---|
3089 | while(go == 0) { yield(); } |
---|
3090 | while(go == 1) { do_call(m1); } |
---|
3091 | } |
---|
3092 | int __attribute__((noinline)) do_wait( M & mutex a1 ) { |
---|
3093 | go = 1; |
---|
3094 | BENCH( |
---|
3095 | for(size_t i=0; i<n; i++) { |
---|
3096 | wait(c); |
---|
3097 | }, |
---|
3098 | result |
---|
3099 | ) |
---|
3100 | printf("%llu\n", result); |
---|
3101 | go = 0; |
---|
3102 | return 0; |
---|
3103 | } |
---|
3104 | int main() { |
---|
3105 | T t; |
---|
3106 | return do_wait(m1); |
---|
3107 | } |
---|
3108 | \end{cfa} |
---|
3109 | \end{figure} |
---|
3110 | |
---|
3111 | \begin{table} |
---|
3112 | \begin{center} |
---|
3113 | \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |} |
---|
3114 | \cline{2-4} |
---|
3115 | \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\ |
---|
3116 | \hline |
---|
3117 | Pthreads Condition Variable & 5902.5 & 6093.29 & 714.78 \\ |
---|
3118 | \uC @signal@ & 322 & 323 & 3.36 \\ |
---|
3119 | \CFA @signal@, 1 @monitor@ & 352.5 & 353.11 & 3.66 \\ |
---|
3120 | \CFA @signal@, 2 @monitor@ & 430 & 430.29 & 8.97 \\ |
---|
3121 | \CFA @signal@, 4 @monitor@ & 594.5 & 606.57 & 18.33 \\ |
---|
3122 | Java @notify@ & 13831.5 & 15698.21 & 4782.3 \\ |
---|
3123 | \hline |
---|
3124 | \end{tabular} |
---|
3125 | \end{center} |
---|
3126 | \caption{Internal scheduling comparison. |
---|
3127 | All numbers are in nanoseconds(\si{\nano\second})} |
---|
3128 | \label{tab:int-sched} |
---|
3129 | \end{table} |
---|
3130 | |
---|
3131 | \subsection{External Scheduling} |
---|
3132 | The Internal scheduling benchmark measures the cost of the @waitfor@ statement (@_Accept@ in \uC). |
---|
3133 | Figure~\ref{f:ext-sched} shows the code for \CFA, with results in table \ref{tab:ext-sched}. |
---|
3134 | As with all other benchmarks, all omitted tests are functionally identical to one of these tests. |
---|
3135 | |
---|
3136 | \begin{figure} |
---|
3137 | \begin{cfa}[caption={Benchmark code for external scheduling},label={f:ext-sched}] |
---|
3138 | volatile int go = 0; |
---|
3139 | monitor M {}; |
---|
3140 | M m1; |
---|
3141 | thread T {}; |
---|
3142 | |
---|
3143 | void __attribute__((noinline)) do_call( M & mutex a1 ) {} |
---|
3144 | |
---|
3145 | void ^?{}( T & mutex this ) {} |
---|
3146 | void main( T & this ) { |
---|
3147 | while(go == 0) { yield(); } |
---|
3148 | while(go == 1) { do_call(m1); } |
---|
3149 | } |
---|
3150 | int __attribute__((noinline)) do_wait( M & mutex a1 ) { |
---|
3151 | go = 1; |
---|
3152 | BENCH( |
---|
3153 | for(size_t i=0; i<n; i++) { |
---|
3154 | waitfor(call, a1); |
---|
3155 | }, |
---|
3156 | result |
---|
3157 | ) |
---|
3158 | printf("%llu\n", result); |
---|
3159 | go = 0; |
---|
3160 | return 0; |
---|
3161 | } |
---|
3162 | int main() { |
---|
3163 | T t; |
---|
3164 | return do_wait(m1); |
---|
3165 | } |
---|
3166 | \end{cfa} |
---|
3167 | \end{figure} |
---|
3168 | |
---|
3169 | \begin{table} |
---|
3170 | \begin{center} |
---|
3171 | \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |} |
---|
3172 | \cline{2-4} |
---|
3173 | \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\ |
---|
3174 | \hline |
---|
3175 | \uC @Accept@ & 350 & 350.61 & 3.11 \\ |
---|
3176 | \CFA @waitfor@, 1 @monitor@ & 358.5 & 358.36 & 3.82 \\ |
---|
3177 | \CFA @waitfor@, 2 @monitor@ & 422 & 426.79 & 7.95 \\ |
---|
3178 | \CFA @waitfor@, 4 @monitor@ & 579.5 & 585.46 & 11.25 \\ |
---|
3179 | \hline |
---|
3180 | \end{tabular} |
---|
3181 | \end{center} |
---|
3182 | \caption{External scheduling comparison. |
---|
3183 | All numbers are in nanoseconds(\si{\nano\second})} |
---|
3184 | \label{tab:ext-sched} |
---|
3185 | \end{table} |
---|
3186 | |
---|
3187 | |
---|
3188 | \subsection{Object Creation} |
---|
3189 | Finally, the last benchmark measures the cost of creation for concurrent objects. |
---|
3190 | Figure~\ref{f:creation} shows the code for @pthread@s and \CFA threads, with results shown in table \ref{tab:creation}. |
---|
3191 | As with all other benchmarks, all omitted tests are functionally identical to one of these tests. |
---|
3192 | 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. |
---|
3193 | |
---|
3194 | \begin{figure} |
---|
3195 | \begin{center} |
---|
3196 | @pthread@ |
---|
3197 | \begin{cfa} |
---|
3198 | int main() { |
---|
3199 | BENCH( |
---|
3200 | for(size_t i=0; i<n; i++) { |
---|
3201 | pthread_t thread; |
---|
3202 | if(pthread_create(&thread,NULL,foo,NULL)<0) { |
---|
3203 | perror( "failure" ); |
---|
3204 | return 1; |
---|
3205 | } |
---|
3206 | |
---|
3207 | if(pthread_join(thread, NULL)<0) { |
---|
3208 | perror( "failure" ); |
---|
3209 | return 1; |
---|
3210 | } |
---|
3211 | }, |
---|
3212 | result |
---|
3213 | ) |
---|
3214 | printf("%llu\n", result); |
---|
3215 | } |
---|
3216 | \end{cfa} |
---|
3217 | |
---|
3218 | |
---|
3219 | |
---|
3220 | \CFA Threads |
---|
3221 | \begin{cfa} |
---|
3222 | int main() { |
---|
3223 | BENCH( |
---|
3224 | for(size_t i=0; i<n; i++) { |
---|
3225 | MyThread m; |
---|
3226 | }, |
---|
3227 | result |
---|
3228 | ) |
---|
3229 | printf("%llu\n", result); |
---|
3230 | } |
---|
3231 | \end{cfa} |
---|
3232 | \end{center} |
---|
3233 | \caption{Benchmark code for \protect\lstinline|pthread|s and \CFA to measure object creation} |
---|
3234 | \label{f:creation} |
---|
3235 | \end{figure} |
---|
3236 | |
---|
3237 | \begin{table} |
---|
3238 | \begin{center} |
---|
3239 | \begin{tabular}{| l | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] | S[table-format=5.2,table-number-alignment=right] |} |
---|
3240 | \cline{2-4} |
---|
3241 | \multicolumn{1}{c |}{} & \multicolumn{1}{c |}{ Median } &\multicolumn{1}{c |}{ Average } & \multicolumn{1}{c |}{ Standard Deviation} \\ |
---|
3242 | \hline |
---|
3243 | Pthreads & 26996 & 26984.71 & 156.6 \\ |
---|
3244 | \CFA Coroutine Lazy & 6 & 5.71 & 0.45 \\ |
---|
3245 | \CFA Coroutine Eager & 708 & 706.68 & 4.82 \\ |
---|
3246 | \CFA Thread & 1173.5 & 1176.18 & 15.18 \\ |
---|
3247 | \uC Coroutine & 109 & 107.46 & 1.74 \\ |
---|
3248 | \uC Thread & 526 & 530.89 & 9.73 \\ |
---|
3249 | Goroutine & 2520.5 & 2530.93 & 61,56 \\ |
---|
3250 | Java Thread & 91114.5 & 92272.79 & 961.58 \\ |
---|
3251 | \hline |
---|
3252 | \end{tabular} |
---|
3253 | \end{center} |
---|
3254 | \caption{Creation comparison. |
---|
3255 | All numbers are in nanoseconds(\si{\nano\second}).} |
---|
3256 | \label{tab:creation} |
---|
3257 | \end{table} |
---|
3258 | |
---|
3259 | |
---|
3260 | |
---|
3261 | \section{Conclusion} |
---|
3262 | This paper has achieved a minimal concurrency \textbf{api} that is simple, efficient and usable as the basis for higher-level features. |
---|
3263 | The approach presented is based on a lightweight thread-system for parallelism, which sits on top of clusters of processors. |
---|
3264 | This M:N model is judged to be both more efficient and allow more flexibility for users. |
---|
3265 | Furthermore, this document introduces monitors as the main concurrency tool for users. |
---|
3266 | This paper also offers a novel approach allowing multiple monitors to be accessed simultaneously without running into the Nested Monitor Problem~\cite{Lister77}. |
---|
3267 | It also offers a full implementation of the concurrency runtime written entirely in \CFA, effectively the largest \CFA code base to date. |
---|
3268 | |
---|
3269 | |
---|
3270 | % ====================================================================== |
---|
3271 | % ====================================================================== |
---|
3272 | \section{Future Work} |
---|
3273 | % ====================================================================== |
---|
3274 | % ====================================================================== |
---|
3275 | |
---|
3276 | \subsection{Performance} \label{futur:perf} |
---|
3277 | This paper presents a first implementation of the \CFA concurrency runtime. |
---|
3278 | Therefore, there is still significant work to improve performance. |
---|
3279 | Many of the data structures and algorithms may change in the future to more efficient versions. |
---|
3280 | For example, the number of monitors in a single \textbf{bulk-acq} is only bound by the stack size, this is probably unnecessarily generous. |
---|
3281 | It may be possible that limiting the number helps increase performance. |
---|
3282 | However, it is not obvious that the benefit would be significant. |
---|
3283 | |
---|
3284 | \subsection{Flexible Scheduling} \label{futur:sched} |
---|
3285 | An important part of concurrency is scheduling. |
---|
3286 | Different scheduling algorithms can affect performance (both in terms of average and variation). |
---|
3287 | However, no single scheduler is optimal for all workloads and therefore there is value in being able to change the scheduler for given programs. |
---|
3288 | One solution is to offer various tweaking options to users, allowing the scheduler to be adjusted to the requirements of the workload. |
---|
3289 | However, in order to be truly flexible, it would be interesting to allow users to add arbitrary data and arbitrary scheduling algorithms. |
---|
3290 | 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. |
---|
3291 | This path of flexible schedulers will be explored for \CFA. |
---|
3292 | |
---|
3293 | \subsection{Non-Blocking I/O} \label{futur:nbio} |
---|
3294 | 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). |
---|
3295 | These types of workloads often require significant engineering around amortizing costs of blocking IO operations. |
---|
3296 | At its core, non-blocking I/O is an operating system level feature that allows queuing IO operations (\eg network operations) and registering for notifications instead of waiting for requests to complete. |
---|
3297 | In this context, the role of the language makes Non-Blocking IO easily available and with low overhead. |
---|
3298 | 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. |
---|
3299 | However, while these are valid solutions, they lead to code that is harder to read and maintain because it is much less linear. |
---|
3300 | |
---|
3301 | \subsection{Other Concurrency Tools} \label{futur:tools} |
---|
3302 | While monitors offer a flexible and powerful concurrent core for \CFA, other concurrency tools are also necessary for a complete multi-paradigm concurrency package. |
---|
3303 | Examples of such tools can include simple locks and condition variables, futures and promises~\cite{promises}, executors and actors. |
---|
3304 | These additional features are useful when monitors offer a level of abstraction that is inadequate for certain tasks. |
---|
3305 | |
---|
3306 | \subsection{Implicit Threading} \label{futur:implcit} |
---|
3307 | Simpler applications can benefit greatly from having implicit parallelism. |
---|
3308 | That is, parallelism that does not rely on the user to write concurrency. |
---|
3309 | This type of parallelism can be achieved both at the language level and at the library level. |
---|
3310 | The canonical example of implicit parallelism is parallel for loops, which are the simplest example of a divide and conquer algorithms~\cite{uC++book}. |
---|
3311 | Table \ref{f:parfor} shows three different code examples that accomplish point-wise sums of large arrays. |
---|
3312 | Note that none of these examples explicitly declare any concurrency or parallelism objects. |
---|
3313 | |
---|
3314 | \begin{table} |
---|
3315 | \begin{center} |
---|
3316 | \begin{tabular}[t]{|c|c|c|} |
---|
3317 | Sequential & Library Parallel & Language Parallel \\ |
---|
3318 | \begin{cfa}[tabsize=3] |
---|
3319 | void big_sum( |
---|
3320 | int* a, int* b, |
---|
3321 | int* o, |
---|
3322 | size_t len) |
---|
3323 | { |
---|
3324 | for( |
---|
3325 | int i = 0; |
---|
3326 | i < len; |
---|
3327 | ++i ) |
---|
3328 | { |
---|
3329 | o[i]=a[i]+b[i]; |
---|
3330 | } |
---|
3331 | } |
---|
3332 | |
---|
3333 | |
---|
3334 | |
---|
3335 | |
---|
3336 | |
---|
3337 | int* a[10000]; |
---|
3338 | int* b[10000]; |
---|
3339 | int* c[10000]; |
---|
3340 | //... fill in a & b |
---|
3341 | big_sum(a,b,c,10000); |
---|
3342 | \end{cfa} &\begin{cfa}[tabsize=3] |
---|
3343 | void big_sum( |
---|
3344 | int* a, int* b, |
---|
3345 | int* o, |
---|
3346 | size_t len) |
---|
3347 | { |
---|
3348 | range ar(a, a+len); |
---|
3349 | range br(b, b+len); |
---|
3350 | range or(o, o+len); |
---|
3351 | parfor( ai, bi, oi, |
---|
3352 | []( int* ai, |
---|
3353 | int* bi, |
---|
3354 | int* oi) |
---|
3355 | { |
---|
3356 | oi=ai+bi; |
---|
3357 | }); |
---|
3358 | } |
---|
3359 | |
---|
3360 | |
---|
3361 | int* a[10000]; |
---|
3362 | int* b[10000]; |
---|
3363 | int* c[10000]; |
---|
3364 | //... fill in a & b |
---|
3365 | big_sum(a,b,c,10000); |
---|
3366 | \end{cfa}&\begin{cfa}[tabsize=3] |
---|
3367 | void big_sum( |
---|
3368 | int* a, int* b, |
---|
3369 | int* o, |
---|
3370 | size_t len) |
---|
3371 | { |
---|
3372 | parfor (ai,bi,oi) |
---|
3373 | in (a, b, o ) |
---|
3374 | { |
---|
3375 | oi = ai + bi; |
---|
3376 | } |
---|
3377 | } |
---|
3378 | |
---|
3379 | |
---|
3380 | |
---|
3381 | |
---|
3382 | |
---|
3383 | |
---|
3384 | |
---|
3385 | int* a[10000]; |
---|
3386 | int* b[10000]; |
---|
3387 | int* c[10000]; |
---|
3388 | //... fill in a & b |
---|
3389 | big_sum(a,b,c,10000); |
---|
3390 | \end{cfa} |
---|
3391 | \end{tabular} |
---|
3392 | \end{center} |
---|
3393 | \caption{For loop to sum numbers: Sequential, using library parallelism and language parallelism.} |
---|
3394 | \label{f:parfor} |
---|
3395 | \end{table} |
---|
3396 | |
---|
3397 | Implicit parallelism is a restrictive solution and therefore has its limitations. |
---|
3398 | 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. |
---|
3399 | |
---|
3400 | |
---|
3401 | % A C K N O W L E D G E M E N T S |
---|
3402 | % ------------------------------- |
---|
3403 | \section{Acknowledgements} |
---|
3404 | |
---|
3405 | Thanks to Aaron Moss, Rob Schluntz and Andrew Beach for their work on the \CFA project as well as all the discussions which helped concretize the ideas in this paper. |
---|
3406 | Partial funding was supplied by the Natural Sciences and Engineering Research Council of Canada and a corporate partnership with Huawei Ltd. |
---|
3407 | |
---|
3408 | |
---|
3409 | % B I B L I O G R A P H Y |
---|
3410 | % ----------------------------- |
---|
3411 | %\bibliographystyle{plain} |
---|
3412 | \bibliography{pl,local} |
---|
3413 | |
---|
3414 | \end{document} |
---|
3415 | |
---|
3416 | % Local Variables: % |
---|
3417 | % tab-width: 4 % |
---|
3418 | % fill-column: 120 % |
---|
3419 | % compile-command: "make" % |
---|
3420 | % End: % |
---|