Changeset 04e6f93
- Timestamp:
- Feb 27, 2020, 4:04:25 PM (6 years ago)
- Branches:
- ADT, arm-eh, ast-experimental, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, pthread-emulation, qualifiedEnum
- Children:
- a037f85
- Parents:
- 41efd33 (diff), 930b504 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the(diff)
links above to see all the changes relative to each parent. - Files:
-
- 24 added
- 3 deleted
- 96 edited
- 18 moved
Legend:
- Unmodified
- Added
- Removed
-
Jenkinsfile
r41efd33 r04e6f93 215 215 216 216 //Then publish the results 217 do_plot(Settings.RunBenchmark && Settings.Publish, 'compile' , groupCompile , false, 'Compilation')218 do_plot(Settings.RunBenchmark && Settings.Publish, 'compile.diff' , groupCompile , true , 'Compilation (relative)')219 do_plot(Settings.RunBenchmark && Settings.Publish, 'ctxswitch' , groupConcurrency, false, 'Context Switching')220 do_plot(Settings.RunBenchmark && Settings.Publish, 'ctxswitch.diff' , groupConcurrency, true , 'Context Switching (relative)')221 do_plot(Settings.RunBenchmark && Settings.Publish, 'mutex' , groupConcurrency, false, 'Mutual Exclusion')222 do_plot(Settings.RunBenchmark && Settings.Publish, 'mutex.diff' , groupConcurrency, true , 'Mutual Exclusion (relative)')223 do_plot(Settings.RunBenchmark && Settings.Publish, 's ignal', groupConcurrency, false, 'Internal and External Scheduling')224 do_plot(Settings.RunBenchmark && Settings.Publish, 's ignal.diff', groupConcurrency, true , 'Internal and External Scheduling (relative)')217 do_plot(Settings.RunBenchmark && Settings.Publish, 'compile' , groupCompile , false, 'Compilation') 218 do_plot(Settings.RunBenchmark && Settings.Publish, 'compile.diff' , groupCompile , true , 'Compilation (relative)') 219 do_plot(Settings.RunBenchmark && Settings.Publish, 'ctxswitch' , groupConcurrency, false, 'Context Switching') 220 do_plot(Settings.RunBenchmark && Settings.Publish, 'ctxswitch.diff' , groupConcurrency, true , 'Context Switching (relative)') 221 do_plot(Settings.RunBenchmark && Settings.Publish, 'mutex' , groupConcurrency, false, 'Mutual Exclusion') 222 do_plot(Settings.RunBenchmark && Settings.Publish, 'mutex.diff' , groupConcurrency, true , 'Mutual Exclusion (relative)') 223 do_plot(Settings.RunBenchmark && Settings.Publish, 'scheduling' , groupConcurrency, false, 'Internal and External Scheduling') 224 do_plot(Settings.RunBenchmark && Settings.Publish, 'scheduling.diff', groupConcurrency, true , 'Internal and External Scheduling (relative)') 225 225 } 226 226 } -
benchmark/Makefile.am
r41efd33 r04e6f93 30 30 BENCH_V_UPP = $(__bench_v_UPP_$(__quiet)) 31 31 BENCH_V_GOC = $(__bench_v_GOC_$(__quiet)) 32 BENCH_V_PY = $(__bench_v_PY_$(__quiet)) 32 33 BENCH_V_RUSTC = $(__bench_v_RUSTC_$(__quiet)) 33 34 BENCH_V_NODEJS = $(__bench_v_NODEJS_$(__quiet)) … … 47 48 __bench_v_UPP_verbose = $(AM_V_UPP) 48 49 __bench_v_GOC_verbose = $(AM_V_GOC) 49 __bench_v_RUSTC_verbose = $(AM_V_RUSTC) 50 __bench_v_PY_verbose = $(AM_V_PY) 51 __bench_v_RUSTC_verbose = $(AM_V_RUST) 50 52 __bench_v_NODEJS_verbose = $(AM_V_NODEJS) 51 53 __bench_v_JAVAC_verbose = $(AM_V_JAVAC) … … 72 74 echo "int main() { return 0; }" > ${@} 73 75 74 #.SILENT: # do not print recipe 75 .ONESHELL: # use one shell to execute recipe 76 .SILENT: # do not print recipe 76 77 .NOTPARALLEL: 77 .PHONY: compile.csv basic.csv ctxswitch.csv mutex.csv schedint.csv78 .PHONY: jenkins cleancsv 78 79 79 80 ## ========================================================================================================= … … 142 143 FIX_NEW_LINES = cat $@ | tr "\n" "\t" | sed -r 's/\t,/,/' | tr "\t" "\n" > $@ 143 144 144 jenkins$(EXEEXT): 145 cleancsv: 146 rm -f compile.csv basic.csv ctxswitch.csv mutex.csv scheduling.csv 147 148 jenkins$(EXEEXT): cleancsv 145 149 @DOifskipcompile@ 146 150 +make compile.csv 147 151 -+make compile.diff.csv 148 152 @DOendif@ 149 +make basic.csv150 -+make basic.diff.csv151 153 +make ctxswitch.csv 152 154 -+make ctxswitch.diff.csv 153 155 +make mutex.csv 154 156 -+make mutex.diff.csv 155 +make sched int.csv156 -+make sched int.diff.csv157 +make scheduling.csv 158 -+make scheduling.diff.csv 157 159 @DOifskipcompile@ 158 160 cat compile.csv 159 161 -cat compile.diff.csv 160 162 @DOendif@ 161 cat basic.csv162 -cat basic.diff.csv163 163 cat ctxswitch.csv 164 164 -cat ctxswitch.diff.csv 165 165 cat mutex.csv 166 166 -cat mutex.diff.csv 167 cat sched int.csv168 -cat sched int.diff.csv167 cat scheduling.csv 168 -cat scheduling.diff.csv 169 169 170 170 compile.csv: 171 echo "building $@" 171 172 echo "array,attributes,empty,expression,io,monitor,operators,typeof" > $@ 172 173 +make TIME_FORMAT='%e,' PRINT_FORMAT='' compile-array.make >> $@ … … 180 181 $(srcdir)/fixcsv.sh $@ 181 182 182 basic.csv:183 echo "generator,coroutine,thread" > $@184 +make basic-cfa_generator.runquiet >> $@ && echo -n ',' >> $@185 +make basic-cfa_coroutine.runquiet >> $@ && echo -n ',' >> $@186 +make basic-cfa_thread.runquiet >> $@187 $(srcdir)/fixcsv.sh $@188 189 183 ctxswitch.csv: 184 echo "building $@" 190 185 echo "generator,coroutine,thread" > $@ 191 186 +make ctxswitch-cfa_generator.runquiet >> $@ && echo -n ',' >> $@ … … 195 190 196 191 mutex.csv: 192 echo "building $@" 197 193 echo "1-monitor,2-monitor" > $@ 198 194 +make mutex-cfa1.runquiet >> $@ && echo -n ',' >> $@ … … 200 196 $(srcdir)/fixcsv.sh $@ 201 197 202 schedint.csv: 198 scheduling.csv: 199 echo "building $@" 203 200 echo "schedint-1,schedint-2,schedext-1,schedext-2" > $@ 204 201 +make schedint-cfa1.runquiet >> $@ && echo -n ',' >> $@ … … 289 286 290 287 ctxswitch-python_coroutine$(EXEEXT): 291 echo "#!/bin/sh" > a.out288 $(BENCH_V_PY)echo "#!/bin/sh" > a.out 292 289 echo "python3.7 $(srcdir)/ctxswitch/python_cor.py" >> a.out 293 290 chmod a+x a.out 294 291 295 292 ctxswitch-nodejs_coroutine$(EXEEXT): 296 echo "#!/bin/sh" > a.out293 $(BENCH_V_NODEJS)echo "#!/bin/sh" > a.out 297 294 echo "nodejs $(srcdir)/ctxswitch/node_cor.js" >> a.out 298 295 chmod a+x a.out 299 296 300 297 ctxswitch-nodejs_await$(EXEEXT): 301 echo "#!/bin/sh" > a.out298 $(BENCH_V_NODEJS)echo "#!/bin/sh" > a.out 302 299 echo "nodejs $(srcdir)/ctxswitch/node_await.js" >> a.out 303 300 chmod a+x a.out … … 452 449 453 450 creation-python_coroutine$(EXEEXT): 454 echo "#!/bin/sh" > a.out451 $(BENCH_V_PY)echo "#!/bin/sh" > a.out 455 452 echo "python3.7 $(srcdir)/creation/python_cor.py" >> a.out 456 453 chmod a+x a.out 457 454 458 455 creation-nodejs_coroutine$(EXEEXT): 459 echo "#!/bin/sh" > a.out456 $(BENCH_V_NODEJS)echo "#!/bin/sh" > a.out 460 457 echo "nodejs $(srcdir)/creation/node_cor.js" >> a.out 461 458 chmod a+x a.out … … 516 513 compile-typeof$(EXEEXT): 517 514 $(CFACOMPILE) -fsyntax-only -w $(testdir)/typeof.cfa 515 516 ## ========================================================================================================= 517 518 size$(EXEEXT) : size-cfa.runquiet 519 520 size-cfa$(EXEEXT): 521 $(BENCH_V_CFA)$(CFACOMPILE) $(srcdir)/size/size.cfa -
benchmark/Makefile.in
r41efd33 r04e6f93 368 368 am__v_GOC_0 = @echo " GOC " $@; 369 369 am__v_GOC_1 = 370 AM_V_PY = $(am__v_PY_@AM_V@) 371 am__v_PY_ = $(am__v_PY_@AM_DEFAULT_V@) 372 am__v_PY_0 = @echo " PYTHON " $@; 373 am__v_PY_1 = 370 374 AM_V_RUST = $(am__v_RUST_@AM_V@) 371 375 am__v_RUST_ = $(am__v_RUST_@AM_DEFAULT_V@) 372 am__v_RUST_0 = @echo " RUST 376 am__v_RUST_0 = @echo " RUST " $@; 373 377 am__v_RUST_1 = 374 378 AM_V_NODEJS = $(am__v_NODEJS_@AM_V@) 375 379 am__v_NODEJS_ = $(am__v_NODEJS_@AM_DEFAULT_V@) 376 am__v_NODEJS_0 = @echo " NODEJS 380 am__v_NODEJS_0 = @echo " NODEJS " $@; 377 381 am__v_NODEJS_1 = 378 382 AM_V_JAVAC = $(am__v_JAVAC_@AM_V@) … … 390 394 BENCH_V_UPP = $(__bench_v_UPP_$(__quiet)) 391 395 BENCH_V_GOC = $(__bench_v_GOC_$(__quiet)) 396 BENCH_V_PY = $(__bench_v_PY_$(__quiet)) 392 397 BENCH_V_RUSTC = $(__bench_v_RUSTC_$(__quiet)) 393 398 BENCH_V_NODEJS = $(__bench_v_NODEJS_$(__quiet)) … … 406 411 __bench_v_UPP_verbose = $(AM_V_UPP) 407 412 __bench_v_GOC_verbose = $(AM_V_GOC) 408 __bench_v_RUSTC_verbose = $(AM_V_RUSTC) 413 __bench_v_PY_verbose = $(AM_V_PY) 414 __bench_v_RUSTC_verbose = $(AM_V_RUST) 409 415 __bench_v_NODEJS_verbose = $(AM_V_NODEJS) 410 416 __bench_v_JAVAC_verbose = $(AM_V_JAVAC) … … 784 790 echo "int main() { return 0; }" > ${@} 785 791 786 #.SILENT: # do not print recipe 787 .ONESHELL: # use one shell to execute recipe 792 .SILENT: # do not print recipe 788 793 .NOTPARALLEL: 789 .PHONY: compile.csv basic.csv ctxswitch.csv mutex.csv schedint.csv794 .PHONY: jenkins cleancsv 790 795 791 796 all : basic$(EXEEXT) ctxswitch$(EXEEXT) mutex$(EXEEXT) schedint$(EXEEXT) schedext$(EXEEXT) creation$(EXEEXT) … … 817 822 +make -C ${abs_top_builddir}/tools repeat 818 823 819 jenkins$(EXEEXT): 824 cleancsv: 825 rm -f compile.csv basic.csv ctxswitch.csv mutex.csv scheduling.csv 826 827 jenkins$(EXEEXT): cleancsv 820 828 @DOifskipcompile@ 821 829 +make compile.csv 822 830 -+make compile.diff.csv 823 831 @DOendif@ 824 +make basic.csv825 -+make basic.diff.csv826 832 +make ctxswitch.csv 827 833 -+make ctxswitch.diff.csv 828 834 +make mutex.csv 829 835 -+make mutex.diff.csv 830 +make sched int.csv831 -+make sched int.diff.csv836 +make scheduling.csv 837 -+make scheduling.diff.csv 832 838 @DOifskipcompile@ 833 839 cat compile.csv 834 840 -cat compile.diff.csv 835 841 @DOendif@ 836 cat basic.csv837 -cat basic.diff.csv838 842 cat ctxswitch.csv 839 843 -cat ctxswitch.diff.csv 840 844 cat mutex.csv 841 845 -cat mutex.diff.csv 842 cat sched int.csv843 -cat sched int.diff.csv846 cat scheduling.csv 847 -cat scheduling.diff.csv 844 848 845 849 compile.csv: 850 echo "building $@" 846 851 echo "array,attributes,empty,expression,io,monitor,operators,typeof" > $@ 847 852 +make TIME_FORMAT='%e,' PRINT_FORMAT='' compile-array.make >> $@ … … 855 860 $(srcdir)/fixcsv.sh $@ 856 861 857 basic.csv:858 echo "generator,coroutine,thread" > $@859 +make basic-cfa_generator.runquiet >> $@ && echo -n ',' >> $@860 +make basic-cfa_coroutine.runquiet >> $@ && echo -n ',' >> $@861 +make basic-cfa_thread.runquiet >> $@862 $(srcdir)/fixcsv.sh $@863 864 862 ctxswitch.csv: 863 echo "building $@" 865 864 echo "generator,coroutine,thread" > $@ 866 865 +make ctxswitch-cfa_generator.runquiet >> $@ && echo -n ',' >> $@ … … 870 869 871 870 mutex.csv: 871 echo "building $@" 872 872 echo "1-monitor,2-monitor" > $@ 873 873 +make mutex-cfa1.runquiet >> $@ && echo -n ',' >> $@ … … 875 875 $(srcdir)/fixcsv.sh $@ 876 876 877 schedint.csv: 877 scheduling.csv: 878 echo "building $@" 878 879 echo "schedint-1,schedint-2,schedext-1,schedext-2" > $@ 879 880 +make schedint-cfa1.runquiet >> $@ && echo -n ',' >> $@ … … 931 932 932 933 ctxswitch-python_coroutine$(EXEEXT): 933 echo "#!/bin/sh" > a.out934 $(BENCH_V_PY)echo "#!/bin/sh" > a.out 934 935 echo "python3.7 $(srcdir)/ctxswitch/python_cor.py" >> a.out 935 936 chmod a+x a.out 936 937 937 938 ctxswitch-nodejs_coroutine$(EXEEXT): 938 echo "#!/bin/sh" > a.out939 $(BENCH_V_NODEJS)echo "#!/bin/sh" > a.out 939 940 echo "nodejs $(srcdir)/ctxswitch/node_cor.js" >> a.out 940 941 chmod a+x a.out 941 942 942 943 ctxswitch-nodejs_await$(EXEEXT): 943 echo "#!/bin/sh" > a.out944 $(BENCH_V_NODEJS)echo "#!/bin/sh" > a.out 944 945 echo "nodejs $(srcdir)/ctxswitch/node_await.js" >> a.out 945 946 chmod a+x a.out … … 1085 1086 1086 1087 creation-python_coroutine$(EXEEXT): 1087 echo "#!/bin/sh" > a.out1088 $(BENCH_V_PY)echo "#!/bin/sh" > a.out 1088 1089 echo "python3.7 $(srcdir)/creation/python_cor.py" >> a.out 1089 1090 chmod a+x a.out 1090 1091 1091 1092 creation-nodejs_coroutine$(EXEEXT): 1092 echo "#!/bin/sh" > a.out1093 $(BENCH_V_NODEJS)echo "#!/bin/sh" > a.out 1093 1094 echo "nodejs $(srcdir)/creation/node_cor.js" >> a.out 1094 1095 chmod a+x a.out … … 1146 1147 $(CFACOMPILE) -fsyntax-only -w $(testdir)/typeof.cfa 1147 1148 1149 size$(EXEEXT) : size-cfa.runquiet 1150 1151 size-cfa$(EXEEXT): 1152 $(BENCH_V_CFA)$(CFACOMPILE) $(srcdir)/size/size.cfa 1153 1148 1154 # Tell versions [3.59,3.63) of GNU make to not export all variables. 1149 1155 # Otherwise a system limit (for SysV at least) may be exceeded. -
benchmark/baselines/x64/schedint.csv
r41efd33 r04e6f93 1 waitfor-2,signal-1,signal-2,waitfor-11 schedext-2,schedint-1,schedint-2,schedext-1 2 2 393.69606249999987,325.99158333333327,409.01025000000004,319.90975000000003 -
benchmark/baselines/x86/schedint.csv
r41efd33 r04e6f93 1 s ignal-2,waitfor-1,waitfor-2,signal-11 schedint-2,schedext-1,schedext-2,schedint-1 2 2 532.5297959183672,413.3084897959184,506.7579591836735,423.78826530612247 -
doc/bibliography/pl.bib
r41efd33 r04e6f93 9 9 % Predefined journal names: 10 10 % acmcs: Computing Surveys acta: Acta Infomatica 11 @string{acta="Acta Infomatica"}12 11 % cacm: Communications of the ACM 13 12 % ibmjrd: IBM J. Research & Development ibmsj: IBM Systems Journal … … 22 21 % tcs: Theoretical Computer Science 23 22 23 @string{acta="Acta Infomatica"} 24 24 string{ieeepds="IEEE Transactions on Parallel and Distributed Systems"} 25 25 @string{ieeepds="IEEE Trans. Parallel Distrib. Syst."} … … 124 124 series = {ACM Distinguished Dissertations}, 125 125 year = 1983, 126 } 127 128 @article{Zhang19, 129 keywords = {Algebraic effects, dynamic scoping, exceptions, parametricity, type systems}, 130 author = {Zhang, Yizhou and Myers, Andrew C.}, 131 title = {Abstraction-safe Effect Handlers via Tunneling}, 132 journal = {Proc. ACM Program. Lang.}, 133 issue_date = {January 2019}, 134 volume = {3}, 135 number = {POPL}, 136 month = jan, 137 year = {2019}, 138 issn = {2475-1421}, 139 pages = {5:1--5:29}, 140 articleno = {5}, 141 publisher = {ACM}, 142 address = {New York, NY, USA}, 143 } 144 145 @inproceedings{Zhang16, 146 keywords = {Exception tunneling, Genus, exception handling}, 147 author = {Zhang, Yizhou and Salvaneschi, Guido and Beightol, Quinn and Liskov, Barbara and Myers, Andrew C.}, 148 title = {Accepting Blame for Safe Tunneled Exceptions}, 149 booktitle = {Proceedings of the 37th ACM SIGPLAN Conference on Programming Language Design and Implementation}, 150 series = {PLDI'16}, 151 year = {2016}, 152 location = {Santa Barbara, CA, USA}, 153 pages = {281--295}, 154 publisher = {ACM}, 155 address = {New York, NY, USA}, 126 156 } 127 157 … … 398 428 journal = sigplan, 399 429 year = 1981, 400 month = feb, volume = 16, number = 2, pages = {48-52}, 430 month = feb, 431 volume = 16, 432 number = 2, 433 pages = {48-52}, 401 434 comment = { 402 435 A one-pass, top-down algorithm for overload resolution. Input is a … … 477 510 title = {An Alternative to Subclassing}, 478 511 journal = sigplan, 479 volume = {21}, number = {11}, 512 volume = {21}, 513 number = {11}, 480 514 pages = {424-428}, 481 month = nov, year = 1986, 515 month = nov, 516 year = 1986, 482 517 comment = { 483 518 The Smalltalk class hierarchy has three uses: factoring out code; … … 533 568 isbn = {3-540-66538-2}, 534 569 location = {Toulouse, France}, 535 doi = {http://doi.acm.org/10.1145/318773.319251},536 570 publisher = {Springer}, 537 571 address = {London, UK}, … … 631 665 year = 2010, 632 666 pages = {39--50}, 633 numpages = {12},634 667 publisher = {IEEE Computer Society}, 635 668 address = {Washington, DC, USA}, … … 922 955 } 923 956 957 @manual{C99, 958 keywords = {ISO/IEC C 9899}, 959 contributer = {pabuhr@plg}, 960 key = {C99}, 961 title = {C Programming Language {ISO/IEC} 9899:1999(E)}, 962 edition = {2nd}, 963 publisher = {International Standard Organization}, 964 address = {\href{https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC98991999R2005}{https://webstore.ansi.org/\-Standards/\-INCITS/\-INCITSISOIEC98991999R2005}}, 965 year = 1999, 966 } 967 924 968 @manual{C11, 925 969 keywords = {ISO/IEC C 11}, … … 1305 1349 location = {London, United Kingdom}, 1306 1350 pages = {41--53}, 1307 numpages = {13},1308 url = {http://doi.acm.org/10.1145/360204.360207},1309 doi = {10.1145/360204.360207},1310 acmid = {360207},1311 1351 publisher = {ACM}, 1312 1352 address = {New York, NY, USA}, … … 2408 2448 year = 1993, 2409 2449 pages = {201--208}, 2410 url = {http://doi.acm.org/10.1145/155360.155580},2411 2450 publisher = {ACM}, 2412 2451 address = {New York, NY, USA}, … … 2606 2645 location = {Boulder, Colorado, USA}, 2607 2646 pages = {91--97}, 2608 numpages = {7},2609 2647 publisher = {ACM}, 2610 2648 address = {New York, NY, USA}, … … 2637 2675 issn = {0004-5411}, 2638 2676 pages = {215--225}, 2639 numpages = {11},2640 url = {http://doi.acm.org/10.1145/321879.321884},2641 doi = {10.1145/321879.321884},2642 acmid = {321884},2643 2677 publisher = {ACM}, 2644 2678 address = {New York, NY, USA}, … … 2708 2742 } 2709 2743 2744 @misc{Drepper13, 2745 keywords = {thread-local storage}, 2746 contributer = {pabuhr@plg}, 2747 author = {Ulrich Drepper}, 2748 title = {{ELF} Handling For Thread-Local Storage}, 2749 year = 2013, 2750 month = aug, 2751 note = {WikipediA}, 2752 howpublished= {\href{http://www.akkadia.org/drepper/tls.pdf} 2753 {http://\-www.akkadia.org/\-drepper/\-tls.pdf}}, 2754 } 2755 2710 2756 @misc{Turley99, 2711 2757 keywords = {embedded system, micrprocessor}, … … 2718 2764 howpublished= {\href{https://www.eetimes.com/author.asp?sectionid=36&doc_id=1287712} 2719 2765 {https://\-www.eetimes.com/\-author.asp?sectionid=\-36&doc_id=1287712}}, 2766 } 2767 2768 @article{Xiao19, 2769 keywords = {bug classification, fault trigger, Linux operating system, regression bug}, 2770 contributer = {pabuhr@plg}, 2771 author = {Guanping Xiao and Zheng Zheng and Beibei Yin and Kishor S. Trivedi and Xiaoting Du and Kai-Yuan Cai}, 2772 title = {An Empirical Study of Fault Triggers in the Linux Operating System: An Evolutionary Perspective}, 2773 journal = {IEEE Transactions on Reliability}, 2774 month = dec, 2775 year = 2019, 2776 volume = 68, 2777 number = 4, 2778 pages = {1356-1383}, 2720 2779 } 2721 2780 … … 3137 3196 } 3138 3197 3198 @inproceedings{Palix11, 3199 keywords = {Linux, fault-finding tools}, 3200 contributer = {pabuhr@plg}, 3201 author = {Nicolas Palix and Ga\"el Thomas and Suman Saha and Christophe Calv\`es and Julia Lawall and Gilles Muller}, 3202 title = {Faults in Linux: Ten Years Later}, 3203 booktitle = {Proc. of the 16 International Conf. on Arch. Support for Prog. Lang. and Oper. Sys.}, 3204 series = {ASPLOS'11}, 3205 month = mar, 3206 year = 2011, 3207 location = {Newport Beach, California, USA}, 3208 pages = {305-318}, 3209 publisher = {ACM}, 3210 address = {New York, NY, USA}, 3211 } 3212 3139 3213 @article{Lamport87, 3140 3214 keywords = {software solutions, mutual exclusion, fast}, … … 3258 3332 issn = {0001-0782}, 3259 3333 pages = {107--115}, 3260 numpages = {9},3261 url = {http://doi.acm.org/10.1145/1538788.1538814},3262 doi = {10.1145/1538788.1538814},3263 acmid = {1538814},3264 3334 publisher = {ACM}, 3265 3335 address = {New York, NY, USA}, … … 3664 3734 } 3665 3735 3736 @mastersthesis{Radhakrishnan19, 3737 author = {Srihari Radhakrishnan}, 3738 title = {High Performance Web Servers: A Study In Concurrent Programming Models}, 3739 school = {School of Computer Sc., University of Waterloo}, 3740 year = 2019, 3741 optaddress = {Waterloo, Ontario, Canada, N2L 3G1}, 3742 note = {\href{https://uwspace.uwaterloo.ca/handle/10012/14706}{https://\-uwspace.uwaterloo.ca/\-handle/\-10012/\-14706}}, 3743 } 3744 3666 3745 @article{katzenelson83b, 3667 3746 contributer = {gjditchfield@plg}, … … 3697 3776 pages = {115-138}, 3698 3777 year = 1971, 3778 } 3779 3780 @inproceedings{Hagersten03, 3781 keywords = {cache storage, parallel architectures, performance evaluation, shared memory systems}, 3782 author = {Zoran Radovi\'{c} and Erik Hagersten}, 3783 title = {Hierarchical backoff locks for nonuniform communication architectures}, 3784 booktitle = {Proceedings of the Ninth International Symposium on High-Performance Computer Architecture}, 3785 year = {2003}, 3786 location = {Anaheim, CA, USA}, 3787 pages = {241-252}, 3788 publisher = {IEEE}, 3699 3789 } 3700 3790 … … 4365 4455 } 4366 4456 4457 @misc{gccValueLabels, 4458 keywords = {gcc extension, value labels}, 4459 contributer = {pabuhr@plg}, 4460 key = {Labels as Values}, 4461 author = {{gcc Extension}}, 4462 title = {Labels as Values}, 4463 year = {since gcc-3}, 4464 howpublished= {\href{https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html} 4465 {https:\-//gcc.gnu.org/\-onlinedocs/\-gcc/\-Labels-as-Values.html}}, 4466 } 4467 4367 4468 @mastersthesis{Clarke90, 4368 4469 keywords = {concurrency, postponing requests}, … … 4457 4558 4458 4559 @article{Pierce00, 4459 keywords = {Scala },4560 keywords = {Scala, polymorphism, subtyping, type inference}, 4460 4561 contributer = {a3moss@uwaterloo.ca}, 4461 4562 author = {Pierce, Benjamin C. and Turner, David N.}, … … 4469 4570 issn = {0164-0925}, 4470 4571 pages = {1--44}, 4471 numpages = {44},4472 url = {http://doi.acm.org/10.1145/345099.345100},4473 doi = {10.1145/345099.345100},4474 acmid = {345100},4475 4572 publisher = {ACM}, 4476 4573 address = {New York, NY, USA}, 4477 keywords = {polymorphism, subtyping, type inference},4478 4574 } 4575 4576 @article{Dice15, 4577 keywords = {Concurrency, NUMA, hierarchical locks, locks, multicore, mutex, mutual exclusion, spin locks}, 4578 author = {Dice, David and Marathe, Virendra J. and Shavit, Nir}, 4579 title = {Lock Cohorting: A General Technique for Designing NUMA Locks}, 4580 journal = {ACM Trans. Parallel Comput.}, 4581 issue_date = {January 2015}, 4582 volume = 1, 4583 number = 2, 4584 month = feb, 4585 year = 2015, 4586 pages = {13:1--13:42}, 4587 publisher = {ACM}, 4588 address = {New York, NY, USA}, 4589 } 4479 4590 4480 4591 @article{Sundell08, … … 4554 4665 journal = sigplan, 4555 4666 year = 1989, 4556 month = jun, volume = 24, number = 6, pages = {37-48}, 4667 month = jun, 4668 volume = 24, 4669 number = 6, 4670 pages = {37-48}, 4557 4671 abstract = { 4558 4672 This paper describes a scheme we have used to manage a large … … 4995 5109 year = 1986, 4996 5110 pages = {313--326}, 4997 numpages = {14},4998 5111 publisher = {ACM}, 4999 5112 address = {New York, NY, USA}, … … 5011 5124 year = 1986, 5012 5125 pages = {327--348}, 5013 numpages = {22},5014 5126 publisher = {ACM}, 5015 5127 address = {New York, NY, USA}, … … 5208 5320 year = 2005, 5209 5321 pages = {146-196}, 5210 numpages = {51},5211 5322 publisher = {ACM}, 5212 5323 address = {New York, NY, USA}, … … 5354 5465 year = 2000, 5355 5466 pages = {29-46}, 5356 note = {OOPSLA'00, Oct. 15--19, 2000, Minneapolis, Minn esota, U.S.A.},5467 note = {OOPSLA'00, Oct. 15--19, 2000, Minneapolis, Minn., U.S.A.}, 5357 5468 } 5358 5469 … … 5468 5579 location = {San Diego, California, USA}, 5469 5580 pages = {101--112}, 5470 numpages = {12},5471 url = {http://doi.acm.org/10.1145/2535838.2535878},5472 doi = {10.1145/2535838.2535878},5473 acmid = {2535878},5474 5581 publisher = {ACM}, 5475 5582 address = {New York, NY, USA}, … … 5575 5682 issn = {0362-1340}, 5576 5683 pages = {30--42}, 5577 numpages = {13},5578 url = {http://doi.acm.org/10.1145/947586.947589},5579 doi = {10.1145/947586.947589},5580 5684 publisher = {ACM}, 5581 5685 address = {New York, NY, USA} … … 6112 6216 month = 9, 6113 6217 year = 2005, 6218 } 6219 6220 @article{Bauer15, 6221 keywords = {resumption exceptions, theory}, 6222 contributer = {pabuhr@plg}, 6223 author = {Andrej Bauer and Matija Pretnar}, 6224 title = {Programming with Algebraic Effects and Handlers}, 6225 journal = {Journal of Logical and Algebraic Methods in Programming}, 6226 publisher = {Elsevier BV}, 6227 volume = 84, 6228 number = 1, 6229 month = jan, 6230 year = 2015, 6231 pages = {108-123}, 6114 6232 } 6115 6233 … … 6499 6617 issn = {0164-0925}, 6500 6618 pages = {429-475}, 6501 url = {http://doi.acm.org/10.1145/1133651.1133653},6502 doi = {10.1145/1133651.1133653},6503 acmid = {1133653},6504 6619 publisher = {ACM}, 6505 6620 address = {New York, NY, USA}, … … 6879 6994 issn = {0001-0782}, 6880 6995 pages = {565--569}, 6881 numpages = {5},6882 url = {http://doi.acm.org/10.1145/359545.359566},6883 doi = {10.1145/359545.359566},6884 acmid = {359566},6885 6996 publisher = {ACM}, 6886 6997 address = {New York, NY, USA} … … 6900 7011 issn = {0362-1340}, 6901 7012 pages = {145--147}, 6902 numpages = {3},6903 url = {http://doi.acm.org/10.1145/122598.122614},6904 doi = {10.1145/122598.122614},6905 acmid = {122614},6906 7013 publisher = {ACM}, 6907 7014 address = {New York, NY, USA}, … … 7006 7113 issn = {0362-1340}, 7007 7114 pages = {82--87}, 7008 numpages = {6},7009 url = {http://doi.acm.org/10.1145/947680.947688},7010 doi = {10.1145/947680.947688},7011 7115 publisher = {ACM}, 7012 7116 address = {New York, NY, USA}, … … 7153 7257 } 7154 7258 7259 @article{Cascaval08, 7260 author = {Cascaval, Calin and Blundell, Colin and Michael, Maged and Cain, Harold W. and Wu, Peng and Chiras, Stefanie and Chatterjee, Siddhartha}, 7261 title = {Software Transactional Memory: Why Is It Only a Research Toy?}, 7262 journal = {Queue}, 7263 volume = {6}, 7264 number = {5}, 7265 month = sep, 7266 year = {2008}, 7267 pages = {40:46--40:58}, 7268 publisher = {ACM}, 7269 address = {New York, NY, USA}, 7270 } 7271 7155 7272 @article{Dijkstra65a, 7156 7273 keywords = {N-thread software-solution mutual exclusion}, … … 7363 7480 year = 1974, 7364 7481 pages = {261-301}, 7365 issn = {0360-0300},7366 doi = {http://doi.acm.org/10.1145/356635.356640},7367 7482 publisher = {ACM}, 7368 7483 address = {New York, NY, USA}, … … 7454 7569 publisher = {ACM Press}, 7455 7570 address = {New York, NY, USA}, 7456 doi = {http://doi.acm.org/10.1145/356586.356588},7457 7571 } 7458 7572 … … 7755 7869 howpublished= {\href{https://projects.eclipse.org/proposals/trace-compass}{https://\-projects.eclipse.org/\-proposals/\-trace-compass}}, 7756 7870 } 7757 7871 7872 @inproceedings{Boehm09, 7873 author = {Boehm, Hans-J.}, 7874 title = {Transactional Memory Should Be an Implementation Technique, Not a Programming Interface}, 7875 booktitle = {Proceedings of the First USENIX Conference on Hot Topics in Parallelism}, 7876 series = {HotPar'09}, 7877 year = {2009}, 7878 location = {Berkeley, California}, 7879 publisher = {USENIX Association}, 7880 address = {Berkeley, CA, USA}, 7881 } 7882 7758 7883 @article{Leroy00, 7759 7884 keywords = {type-systems, exceptions}, … … 7805 7930 number = {2}, 7806 7931 pages = {204-214}, 7807 month = apr, year = 1988, 7932 month = apr, 7933 year = 1988, 7808 7934 comment = { 7809 7935 Extended record types add fields to their base record. Assignment … … 8110 8236 issn = {0004-5411}, 8111 8237 pages = {245--281}, 8112 numpages = {37},8113 url = {http://doi.acm.org/10.1145/62.2160},8114 doi = {10.1145/62.2160},8115 acmid = {2160},8116 8238 publisher = {ACM}, 8117 8239 address = {New York, NY, USA}, … … 8126 8248 contributer = {pabuhr@plg}, 8127 8249 author = {Boehm, Hans-J. and Adve, Sarita V.}, 8128 title = {You Don' TKnow Jack About Shared Variables or Memory Models},8250 title = {You Don't Know Jack About Shared Variables or Memory Models}, 8129 8251 journal = cacm, 8130 8252 volume = 55, -
doc/papers/concurrency/Paper.tex
r41efd33 r04e6f93 61 61 \newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name 62 62 \newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name 63 \newcommand{\Csharp}{C\raisebox{-0.7ex}{\ Large$^\sharp$}\xspace} % C# symbolic name63 \newcommand{\Csharp}{C\raisebox{-0.7ex}{\large$^\sharp$}\xspace} % C# symbolic name 64 64 65 65 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% … … 127 127 \newcommand*{\etc}{% 128 128 \@ifnextchar{.}{\ETC}% 129 129 {\ETC.\xspace}% 130 130 }}{}% 131 131 \@ifundefined{etal}{ 132 132 \newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}} 133 133 \newcommand*{\etal}{% 134 \@ifnextchar{.}{\ protect\ETAL}%135 {\ protect\ETAL.\xspace}%134 \@ifnextchar{.}{\ETAL}% 135 {\ETAL.\xspace}% 136 136 }}{}% 137 137 \@ifundefined{viz}{ … … 163 163 __float80, float80, __float128, float128, forall, ftype, generator, _Generic, _Imaginary, __imag, __imag__, 164 164 inline, __inline, __inline__, __int128, int128, __label__, monitor, mutex, _Noreturn, one_t, or, 165 otype, restrict, __restrict, __restrict__, __signed, __signed__, _Static_assert, thread,165 otype, restrict, resume, __restrict, __restrict__, __signed, __signed__, _Static_assert, suspend, thread, 166 166 _Thread_local, throw, throwResume, timeout, trait, try, ttype, typeof, __typeof, __typeof__, 167 167 virtual, __volatile, __volatile__, waitfor, when, with, zero_t}, 168 168 moredirectives={defined,include_next}, 169 169 % replace/adjust listing characters that look bad in sanserif 170 literate={-}{\makebox[1ex][c]{\raisebox{0. 4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1170 literate={-}{\makebox[1ex][c]{\raisebox{0.5ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptstyle\land\,$}}1 171 171 {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1 172 172 {<}{\textrm{\textless}}1 {>}{\textrm{\textgreater}}1 … … 197 197 _Else, _Enable, _Event, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask, 198 198 _Resume, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw}, 199 }200 \lstdefinelanguage{Golang}{201 morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},202 morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,203 bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},204 morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},205 morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},206 morekeywords=[5]{Println,Printf,Error,},207 sensitive=true,208 morecomment=[l]{//},209 morecomment=[s]{/*}{*/},210 morestring=[b]',211 morestring=[b]",212 morestring=[s]{`}{`},213 199 } 214 200 … … 241 227 {} 242 228 \lstnewenvironment{uC++}[1][] 243 {\lstset{ #1}}229 {\lstset{language=uC++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}} 244 230 {} 245 231 \lstnewenvironment{Go}[1][] … … 282 268 \CFA is a polymorphic, non-object-oriented, concurrent, backwards-compatible extension of the C programming language. 283 269 This paper discusses the design philosophy and implementation of its advanced control-flow and concurrent/parallel features, along with the supporting runtime written in \CFA. 284 These features are created from scratch as ISO C has only low-level and/or unimplemented concurrency, so C programmers continue to rely on library features like pthreads.270 These features are created from scratch as ISO C has only low-level and/or unimplemented concurrency, so C programmers continue to rely on library approaches like pthreads. 285 271 \CFA introduces modern language-level control-flow mechanisms, like generators, coroutines, user-level threading, and monitors for mutual exclusion and synchronization. 286 272 % Library extension for executors, futures, and actors are built on these basic mechanisms. … … 295 281 296 282 \begin{document} 297 \linenumbers 283 \linenumbers % comment out to turn off line numbering 298 284 299 285 \maketitle … … 302 288 \section{Introduction} 303 289 304 This paper discusses the design philosophy and implementation of advanced language-level control-flow and concurrent/parallel features in \CFA~\cite{Moss18,Cforall} and its runtime, which is written entirely in \CFA. 305 \CFA is a modern, polymorphic, non-object-oriented\footnote{ 306 \CFA has features often associated with object-oriented programming languages, such as constructors, destructors, virtuals and simple inheritance. 290 \CFA~\cite{Moss18,Cforall} is a modern, polymorphic, non-object-oriented\footnote{ 291 \CFA has object-oriented features, such as constructors, destructors, virtuals and simple trait/interface inheritance. 292 % Go interfaces, Rust traits, Swift Protocols, Haskell Type Classes and Java Interfaces. 293 % "Trait inheritance" works for me. "Interface inheritance" might also be a good choice, and distinguish clearly from implementation inheritance. 294 % You'll want to be a little bit careful with terms like "structural" and "nominal" inheritance as well. CFA has structural inheritance (I think Go as well) -- it's inferred based on the structure of the code. Java, Rust, and Haskell (not sure about Swift) have nominal inheritance, where there needs to be a specific statement that "this type inherits from this type". 307 295 However, functions \emph{cannot} be nested in structures, so there is no lexical binding between a structure and set of functions (member/method) implemented by an implicit \lstinline@this@ (receiver) parameter.}, 308 296 backwards-compatible extension of the C programming language. 309 In many ways, \CFA is to C as Scala~\cite{Scala} is to Java, providing a \emph{research vehicle} for new typing and control-flow capabilities on top of a highly popular programming language allowing immediate dissemination. 310 Within the \CFA framework, new control-flow features are created from scratch because ISO \Celeven defines only a subset of the \CFA extensions, where the overlapping features are concurrency~\cite[\S~7.26]{C11}. 311 However, \Celeven concurrency is largely wrappers for a subset of the pthreads library~\cite{Butenhof97,Pthreads}, and \Celeven and pthreads concurrency is simple, based on thread fork/join in a function and mutex/condition locks, which is low-level and error-prone; 312 no high-level language concurrency features are defined. 313 Interestingly, almost a decade after publication of the \Celeven standard, neither gcc-8, clang-9 nor msvc-19 (most recent versions) support the \Celeven include @threads.h@, indicating little interest in the C11 concurrency approach (possibly because the effort to add concurrency to \CC). 314 Finally, while the \Celeven standard does not state a threading model, the historical association with pthreads suggests implementations would adopt kernel-level threading (1:1)~\cite{ThreadModel}. 315 297 In many ways, \CFA is to C as Scala~\cite{Scala} is to Java, providing a \emph{research vehicle} for new typing and control-flow capabilities on top of a highly popular programming language\footnote{ 298 The TIOBE index~\cite{TIOBE} for December 2019 ranks the top five \emph{popular} programming languages as Java 17\%, C 16\%, Python 10\%, and \CC 6\%, \Csharp 5\% = 54\%, and over the past 30 years, C has always ranked either first or second in popularity.} 299 allowing immediate dissemination. 300 This paper discusses the design philosophy and implementation of advanced language-level control-flow and concurrent/parallel features in \CFA and its runtime, which is written entirely in \CFA. 301 The \CFA control-flow framework extends ISO \Celeven~\cite{C11} with new call/return and concurrent/parallel control-flow. 302 303 % The call/return extensions retain state between callee and caller versus losing the callee's state on return; 304 % the concurrency extensions allow high-level management of threads. 305 306 Call/return control-flow with argument/parameter passing appeared in the first programming languages. 307 Over the past 50 years, call/return has been augmented with features like static/dynamic call, exceptions (multi-level return) and generators/coroutines (retain state between calls). 308 While \CFA has mechanisms for dynamic call (algebraic effects) and exceptions\footnote{ 309 \CFA exception handling will be presented in a separate paper. 310 The key feature that dovetails with this paper is nonlocal exceptions allowing exceptions to be raised across stacks, with synchronous exceptions raised among coroutines and asynchronous exceptions raised among threads, similar to that in \uC~\cite[\S~5]{uC++}}, this work only discusses retaining state between calls via generators/coroutines. 311 \newterm{Coroutining} was introduced by Conway~\cite{Conway63} (1963), discussed by Knuth~\cite[\S~1.4.2]{Knuth73V1}, implemented in Simula67~\cite{Simula67}, formalized by Marlin~\cite{Marlin80}, and is now popular and appears in old and new programming languages: CLU~\cite{CLU}, \Csharp~\cite{Csharp}, Ruby~\cite{Ruby}, Python~\cite{Python}, JavaScript~\cite{JavaScript}, Lua~\cite{Lua}, \CCtwenty~\cite{C++20Coroutine19}. 312 Coroutining is sequential execution requiring direct handoff among coroutines, \ie only the programmer is controlling execution order. 313 If coroutines transfer to an internal event-engine for scheduling the next coroutines, the program transitions into the realm of concurrency~\cite[\S~3]{Buhr05a}. 314 Coroutines are only a stepping stone towards concurrency where the commonality is that coroutines and threads retain state between calls. 315 316 \Celeven/\CCeleven define concurrency~\cite[\S~7.26]{C11}, but it is largely wrappers for a subset of the pthreads library~\cite{Pthreads}.\footnote{Pthreads concurrency is based on simple thread fork/join in a function and mutex/condition locks, which is low-level and error-prone} 317 Interestingly, almost a decade after the \Celeven standard, neither gcc-9, clang-9 nor msvc-19 (most recent versions) support the \Celeven include @threads.h@, indicating no interest in the C11 concurrency approach (possibly because of the recent effort to add concurrency to \CC). 318 While the \Celeven standard does not state a threading model, the historical association with pthreads suggests implementations would adopt kernel-level threading (1:1)~\cite{ThreadModel}, as for \CC. 316 319 In contrast, there has been a renewed interest during the past decade in user-level (M:N, green) threading in old and new programming languages. 317 320 As multi-core hardware became available in the 1980/90s, both user and kernel threading were examined. 318 321 Kernel threading was chosen, largely because of its simplicity and fit with the simpler operating systems and hardware architectures at the time, which gave it a performance advantage~\cite{Drepper03}. 319 322 Libraries like pthreads were developed for C, and the Solaris operating-system switched from user (JDK 1.1~\cite{JDK1.1}) to kernel threads. 320 As a result, languages like Java, Scala, Objective-C~\cite{obj-c-book}, \CCeleven~\cite{C11}, and C\#~\cite{Csharp} adopt the 1:1 kernel-threading model, with a variety of presentation mechanisms.321 From 2000 onwards, languages like Go~\cite{Go}, Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, D~\cite{D}, and \uC~\cite{uC++,uC++book} have championed the M:N user-threading model, and many user-threading libraries have appeared~\cite{Qthreads,MPC,Marcel}, including putting green threads back into Java~\cite{Quasar}.322 The main argument for user-level threading is that it is lighter weight than kernel threading (locking and context switching do not cross the kernel boundary), so there is less restriction on programming styles that encourage large numbers of threads performing medium work unitsto facilitate load balancing by the runtime~\cite{Verch12}.323 As a result, many current languages implementations adopt the 1:1 kernel-threading model, like Java (Scala), Objective-C~\cite{obj-c-book}, \CCeleven~\cite{C11}, C\#~\cite{Csharp} and Rust~\cite{Rust}, with a variety of presentation mechanisms. 324 From 2000 onwards, several language implementations have championed the M:N user-threading model, like Go~\cite{Go}, Erlang~\cite{Erlang}, Haskell~\cite{Haskell}, D~\cite{D}, and \uC~\cite{uC++,uC++book}, including putting green threads back into Java~\cite{Quasar}, and many user-threading libraries have appeared~\cite{Qthreads,MPC,Marcel}. 325 The main argument for user-level threading is that it is lighter weight than kernel threading (locking and context switching do not cross the kernel boundary), so there is less restriction on programming styles that encourages large numbers of threads performing medium-sized work to facilitate load balancing by the runtime~\cite{Verch12}. 323 326 As well, user-threading facilitates a simpler concurrency approach using thread objects that leverage sequential patterns versus events with call-backs~\cite{Adya02,vonBehren03}. 324 327 Finally, performant user-threading implementations (both time and space) meet or exceed direct kernel-threading implementations, while achieving the programming advantages of high concurrency levels and safety. 325 328 326 A further effort over the past two decades is the development of language memory models to deal with the conflict between language features and compiler/hardware optimizations, \ iesome language features are unsafe in the presence of aggressive sequential optimizations~\cite{Buhr95a,Boehm05}.329 A further effort over the past two decades is the development of language memory models to deal with the conflict between language features and compiler/hardware optimizations, \eg some language features are unsafe in the presence of aggressive sequential optimizations~\cite{Buhr95a,Boehm05}. 327 330 The consequence is that a language must provide sufficient tools to program around safety issues, as inline and library code is all sequential to the compiler. 328 331 One solution is low-level qualifiers and functions (\eg @volatile@ and atomics) allowing \emph{programmers} to explicitly write safe (race-free~\cite{Boehm12}) programs. 329 A safer solution is high-level language constructs so the \emph{compiler} knows the optimization boundaries, and hence, provides implicit safety. 330 This problem is best known with respect to concurrency, but applies to other complex control-flow, like exceptions\footnote{ 331 \CFA exception handling will be presented in a separate paper. 332 The key feature that dovetails with this paper is nonlocal exceptions allowing exceptions to be raised across stacks, with synchronous exceptions raised among coroutines and asynchronous exceptions raised among threads, similar to that in \uC~\cite[\S~5]{uC++} 333 } and coroutines. 334 Finally, language solutions allow matching constructs with language paradigm, \ie imperative and functional languages often have different presentations of the same concept to fit their programming model. 335 336 Finally, it is important for a language to provide safety over performance \emph{as the default}, allowing careful reduction of safety for performance when necessary. 337 Two concurrency violations of this philosophy are \emph{spurious wakeup} (random wakeup~\cite[\S~8]{Buhr05a}) and \emph{barging}\footnote{ 338 The notion of competitive succession instead of direct handoff, \ie a lock owner releases the lock and an arriving thread acquires it ahead of preexisting waiter threads. 332 A safer solution is high-level language constructs so the \emph{compiler} knows the concurrency boundaries (where mutual exclusion and synchronization are acquired/released) and provide implicit safety at and across these boundaries. 333 While the optimization problem is best known with respect to concurrency, it applies to other complex control-flow, like exceptions and coroutines. 334 As well, language solutions allow matching the language paradigm with the approach, \eg matching the functional paradigm with data-flow programming or the imperative paradigm with thread programming. 335 336 Finally, it is important for a language to provide safety over performance \emph{as the default}, allowing careful reduction of safety (unsafe code) for performance when necessary. 337 Two concurrency violations of this philosophy are \emph{spurious wakeup} (random wakeup~\cite[\S~9]{Buhr05a}) and \emph{barging}\footnote{ 338 Barging is competitive succession instead of direct handoff, \ie after a lock is released both arriving and preexisting waiter threads compete to acquire the lock. 339 Hence, an arriving thread can temporally \emph{barge} ahead of threads already waiting for an event, which can repeat indefinitely leading to starvation of waiter threads. 339 340 } (signals-as-hints~\cite[\S~8]{Buhr05a}), where one is a consequence of the other, \ie once there is spurious wakeup, signals-as-hints follow. 340 However, spurious wakeup is \emph{not} a foundational concurrency property~\cite[\S~8]{Buhr05a}, it is a performance design choice. 341 Similarly, signals-as-hints are often a performance decision. 342 We argue removing spurious wakeup and signals-as-hints make concurrent programming significantly safer because it removes local non-determinism and matches with programmer expectation. 343 (Author experience teaching concurrency is that students are highly confused by these semantics.) 344 Clawing back performance, when local non-determinism is unimportant, should be an option not the default. 345 346 \begin{comment} 347 Most augmented traditional (Fortran 18~\cite{Fortran18}, Cobol 14~\cite{Cobol14}, Ada 12~\cite{Ada12}, Java 11~\cite{Java11}) and new languages (Go~\cite{Go}, Rust~\cite{Rust}, and D~\cite{D}), except \CC, diverge from C with different syntax and semantics, only interoperate indirectly with C, and are not systems languages, for those with managed memory. 348 As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten. 349 While \CC, like \CFA, takes an evolutionary approach to extend C, \CC's constantly growing complex and interdependent features-set (\eg objects, inheritance, templates, etc.) mean idiomatic \CC code is difficult to use from C, and C programmers must expend significant effort learning \CC. 350 Hence, rewriting and retraining costs for these languages, even \CC, are prohibitive for companies with a large C software-base. 351 \CFA with its orthogonal feature-set, its high-performance runtime, and direct access to all existing C libraries circumvents these problems. 352 \end{comment} 353 354 \CFA embraces user-level threading, language extensions for advanced control-flow, and safety as the default. 355 We present comparative examples so the reader can judge if the \CFA control-flow extensions are better and safer than those in other concurrent, imperative programming languages, and perform experiments to show the \CFA runtime is competitive with other similar mechanisms. 341 (Author experience teaching concurrency is that students are confused by these semantics.) 342 However, spurious wakeup is \emph{not} a foundational concurrency property~\cite[\S~9]{Buhr05a}; 343 it is a performance design choice. 344 We argue removing spurious wakeup and signals-as-hints make concurrent programming simpler and safer as there is less local non-determinism to manage. 345 If barging acquisition is allowed, its specialized performance advantage should be available as an option not the default. 346 347 \CFA embraces language extensions for advanced control-flow, user-level threading, and safety as the default. 348 We present comparative examples to support our argument that the \CFA control-flow extensions are as expressive and safe as those in other concurrent imperative programming languages, and perform experiments to show the \CFA runtime is competitive with other similar mechanisms. 356 349 The main contributions of this work are: 357 \begin{itemize}[topsep=3pt,itemsep= 1pt]350 \begin{itemize}[topsep=3pt,itemsep=0pt] 358 351 \item 359 language-level generators, coroutines and user-level threading, which respect the expectations of C programmers. 352 a set of fundamental execution properties that dictate which language-level control-flow features need to be supported, 353 360 354 \item 361 monitor synchronization without barging, and the ability to safely acquiring multiple monitors \emph{simultaneously} (deadlock free), while seamlessly integrating these capabilities with all monitor synchronization mechanisms. 355 integration of these language-level control-flow features, while respecting the style and expectations of C programmers, 356 362 357 \item 363 providing statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features. 358 monitor synchronization without barging, and the ability to safely acquiring multiple monitors \emph{simultaneously} (deadlock free), while seamlessly integrating these capabilities with all monitor synchronization mechanisms, 359 360 \item 361 providing statically type-safe interfaces that integrate with the \CFA polymorphic type-system and other language features, 362 364 363 % \item 365 364 % library extensions for executors, futures, and actors built on the basic mechanisms. 365 366 366 \item 367 a runtime system with no spurious wakeup. 367 a runtime system without spurious wake-up and no performance loss, 368 368 369 \item 369 a dynamic partitioning mechanism to segregate the execution environment for specialized requirements. 370 a dynamic partitioning mechanism to segregate groups of executing user and kernel threads performing specialized work (\eg web-server or compute engine) or requiring different scheduling (\eg NUMA or real-time). 371 370 372 % \item 371 373 % a non-blocking I/O library 374 372 375 \item 373 experimental results showing comparable performance of the new features with similar mechanisms in other programminglanguages.376 experimental results showing comparable performance of the \CFA features with similar mechanisms in other languages. 374 377 \end{itemize} 375 378 376 Section~\ref{s:StatefulFunction} begins advanced control by introducing sequential functions that retain data and execution state between calls, which produces constructs @generator@ and @coroutine@. 377 Section~\ref{s:Concurrency} begins concurrency, or how to create (fork) and destroy (join) a thread, which produces the @thread@ construct. 379 Section~\ref{s:FundamentalExecutionProperties} presents the compositional hierarchy of execution properties directing the design of control-flow features in \CFA. 380 Section~\ref{s:StatefulFunction} begins advanced control by introducing sequential functions that retain data and execution state between calls producing constructs @generator@ and @coroutine@. 381 Section~\ref{s:Concurrency} begins concurrency, or how to create (fork) and destroy (join) a thread producing the @thread@ construct. 378 382 Section~\ref{s:MutualExclusionSynchronization} discusses the two mechanisms to restricted nondeterminism when controlling shared access to resources (mutual exclusion) and timing relationships among threads (synchronization). 379 383 Section~\ref{s:Monitor} shows how both mutual exclusion and synchronization are safely embedded in the @monitor@ and @thread@ constructs. 380 384 Section~\ref{s:CFARuntimeStructure} describes the large-scale mechanism to structure (cluster) threads and virtual processors (kernel threads). 381 Section~\ref{s:Performance} uses a series of microbenchmarks to compare \CFA threading with pthreads, Java OpenJDK-9, Go 1.12.6 and \uC 7.0.0. 385 Section~\ref{s:Performance} uses a series of microbenchmarks to compare \CFA threading with pthreads, Java 11.0.6, Go 1.12.6, Rust 1.37.0, Python 3.7.6, Node.js 12.14.1, and \uC 7.0.0. 386 387 388 \section{Fundamental Execution Properties} 389 \label{s:FundamentalExecutionProperties} 390 391 The features in a programming language should be composed from a set of fundamental properties rather than an ad hoc collection chosen by the designers. 392 To this end, the control-flow features created for \CFA are based on the fundamental properties of any language with function-stack control-flow (see also \uC~\cite[pp.~140-142]{uC++}). 393 The fundamental properties are execution state, thread, and mutual-exclusion/synchronization (MES). 394 These independent properties can be used alone, in pairs, or in triplets to compose different language features, forming a compositional hierarchy where the most advanced feature has all the properties (state/thread/MES). 395 While it is possible for a language to only support the most advanced feature~\cite{Hermes90}, this unnecessarily complicates and makes inefficient solutions to certain classes of problems. 396 As is shown, each of the (non-rejected) composed features solves a particular set of problems, and hence, has a defensible position in a programming language. 397 If a compositional feature is missing, a programmer has too few/many fundamental properties resulting in a complex and/or is inefficient solution. 398 399 In detail, the fundamental properties are: 400 \begin{description}[leftmargin=\parindent,topsep=3pt,parsep=0pt] 401 \item[\newterm{execution state}:] 402 is the state information needed by a control-flow feature to initialize, manage compute data and execution location(s), and de-initialize. 403 State is retained in fixed-sized aggregate structures and dynamic-sized stack(s), often allocated in the heap(s) managed by the runtime system. 404 The lifetime of the state varies with the control-flow feature, where longer life-time and dynamic size provide greater power but also increase usage complexity and cost. 405 Control-flow transfers among execution states occurs in multiple ways, such as function call, context switch, asynchronous await, etc. 406 Because the programming language determines what constitutes an execution state, implicitly manages this state, and defines movement mechanisms among states, execution state is an elementary property of the semantics of a programming language. 407 % An execution-state is related to the notion of a process continuation \cite{Hieb90}. 408 409 \item[\newterm{threading}:] 410 is execution of code that occurs independently of other execution, \ie the execution resulting from a thread is sequential. 411 Multiple threads provide \emph{concurrent execution}; 412 concurrent execution becomes parallel when run on multiple processing units (hyper-threading, cores, sockets). 413 There must be language mechanisms to create, block/unblock, and join with a thread. 414 415 \item[\newterm{MES}:] 416 is the concurrency mechanisms to perform an action without interruption and establish timing relationships among multiple threads. 417 These two properties are independent, \ie mutual exclusion cannot provide synchronization and vice versa without introducing additional threads~\cite[\S~4]{Buhr05a}. 418 Limiting MES, \eg no access to shared data, results in contrived solutions and inefficiency on multi-core von Neumann computers where shared memory is a foundational aspect of its design. 419 \end{description} 420 These properties are fundamental because they cannot be built from existing language features, \eg a basic programming language like C99~\cite{C99} cannot create new control-flow features, concurrency, or provide MES using atomic hardware mechanisms. 421 422 423 \subsection{Execution Properties} 424 425 Table~\ref{t:ExecutionPropertyComposition} shows how the three fundamental execution properties: state, thread, and mutual exclusion compose a hierarchy of control-flow features needed in a programming language. 426 (When doing case analysis, not all combinations are meaningful.) 427 Note, basic von Neumann execution requires at least one thread and an execution state providing some form of call stack. 428 For table entries missing these minimal components, the property is borrowed from the invoker (caller). 429 430 Case 1 is a function that borrows storage for its state (stack frame/activation) and a thread from its invoker and retains this state across \emph{callees}, \ie function local-variables are retained on the stack across calls. 431 Case 2 is case 1 with access to shared state so callers are restricted during update (mutual exclusion) and scheduling for other threads (synchronization). 432 Case 3 is a stateful function supporting resume/suspend along with call/return to retain state across \emph{callers}, but has some restrictions because the function's state is stackless. 433 Note, stackless functions still borrow the caller's stack and thread, where the stack is used to preserve state across its callees. 434 Case 4 is cases 2 and 3 with protection to shared state for stackless functions. 435 Cases 5 and 6 are the same as 3 and 4 but only the thread is borrowed as the function state is stackful, so resume/suspend is a context switch from the caller's to the function's stack. 436 Cases 7 and 8 are rejected because a function that is given a new thread must have its own stack where the thread begins and stack frames are stored for calls, \ie there is no stack to borrow. 437 Cases 9 and 10 are rejected because a thread with a fixed state (no stack) cannot accept calls, make calls, block, or be preempted, all of which require an unknown amount of additional dynamic state. 438 Hence, once started, this kind of thread must execute to completion, \ie computation only, which severely restricts runtime management. 439 Cases 11 and 12 have a stackful thread with and without safe access to shared state. 440 Execution properties increase the cost of creation and execution along with complexity of usage. 441 442 \begin{table} 443 \caption{Execution property composition} 444 \centering 445 \label{t:ExecutionPropertyComposition} 446 \renewcommand{\arraystretch}{1.25} 447 %\setlength{\tabcolsep}{5pt} 448 \begin{tabular}{c|c||l|l} 449 \multicolumn{2}{c||}{execution properties} & \multicolumn{2}{c}{mutual exclusion / synchronization} \\ 450 \hline 451 stateful & thread & \multicolumn{1}{c|}{No} & \multicolumn{1}{c}{Yes} \\ 452 \hline 453 \hline 454 No & No & \textbf{1}\ \ \ function & \textbf{2}\ \ \ @monitor@ function \\ 455 \hline 456 Yes (stackless) & No & \textbf{3}\ \ \ @generator@ & \textbf{4}\ \ \ @monitor@ @generator@ \\ 457 \hline 458 Yes (stackful) & No & \textbf{5}\ \ \ @coroutine@ & \textbf{6}\ \ \ @monitor@ @coroutine@ \\ 459 \hline 460 No & Yes & \textbf{7}\ \ \ {\color{red}rejected} & \textbf{8}\ \ \ {\color{red}rejected} \\ 461 \hline 462 Yes (stackless) & Yes & \textbf{9}\ \ \ {\color{red}rejected} & \textbf{10}\ \ \ {\color{red}rejected} \\ 463 \hline 464 Yes (stackful) & Yes & \textbf{11}\ \ \ @thread@ & \textbf{12}\ \ @monitor@ @thread@ \\ 465 \end{tabular} 466 \end{table} 467 468 Given the execution-properties taxonomy, programmers can now answer three basic questions: is state necessary across calls and how much, is a separate thread necessary, is access to shared state necessary. 469 The answers define the optimal language feature need for implementing a programming problem. 470 The next sections discusses how \CFA fills in the table with language features, while other programming languages may only provide a subset of the table. 471 472 473 \subsection{Design Requirements} 474 475 The following design requirements largely stem from building \CFA on top of C. 476 \begin{itemize}[topsep=3pt,parsep=0pt] 477 \item 478 All communication must be statically type checkable for early detection of errors and efficient code generation. 479 This requirement is consistent with the fact that C is a statically-typed programming-language. 480 481 \item 482 Direct interaction among language features must be possible allowing any feature to be selected without restricting comm\-unication. 483 For example, many concurrent languages do not provide direct communication (calls) among threads, \ie threads only communicate indirectly through monitors, channels, messages, and/or futures. 484 Indirect communication increases the number of objects, consuming more resources, and require additional synchronization and possibly data transfer. 485 486 \item 487 All communication is performed using function calls, \ie data is transmitted from argument to parameter and results are returned from function calls. 488 Alternative forms of communication, such as call-backs, message passing, channels, or communication ports, step outside of C's normal form of communication. 489 490 \item 491 All stateful features must follow the same declaration scopes and lifetimes as other language data. 492 For C that means at program startup, during block and function activation, and on demand using dynamic allocation. 493 494 \item 495 MES must be available implicitly in language constructs as well as explicitly for specialized requirements, because requiring programmers to build MES using low-level locks often leads to incorrect programs. 496 Furthermore, reducing synchronization scope by encapsulating it within language constructs further reduces errors in concurrent programs. 497 498 \item 499 Both synchronous and asynchronous communication are needed. 500 However, we believe the best way to provide asynchrony, such as call-buffering/chaining and/or returning futures~\cite{multilisp}, is building it from expressive synchronous features. 501 502 \item 503 Synchronization must be able to control the service order of requests including prioritizing selection from different kinds of outstanding requests, and postponing a request for an unspecified time while continuing to accept new requests. 504 Otherwise, certain concurrency problems are difficult, e.g.\ web server, disk scheduling, and the amount of concurrency is inhibited~\cite{Gentleman81}. 505 \end{itemize} 506 We have satisfied these requirements in \CFA while maintaining backwards compatibility with the huge body of legacy C programs. 507 % In contrast, other new programming languages must still access C programs (\eg operating-system service routines), but do so through fragile C interfaces. 508 509 510 \subsection{Asynchronous Await / Call} 511 512 Asynchronous await/call is a caller mechanism for structuring programs and/or increasing concurrency, where the caller (client) postpones an action into the future, which is subsequently executed by a callee (server). 513 The caller detects the action's completion through a \newterm{future}/\newterm{promise}. 514 The benefit is asynchronous caller execution with respect to the callee until future resolution. 515 For single-threaded languages like JavaScript, an asynchronous call passes a callee action, which is queued in the event-engine, and continues execution with a promise. 516 When the caller needs the promise to be fulfilled, it executes @await@. 517 A promise-completion call-back can be part of the callee action or the caller is rescheduled; 518 in either case, the call back is executed after the promise is fulfilled. 519 While asynchronous calls generate new callee (server) events, we content this mechanism is insufficient for advanced control-flow mechanisms like generators or coroutines (which are discussed next). 520 Specifically, control between caller and callee occurs indirectly through the event-engine precluding direct handoff and cycling among events, and requires complex resolution of a control promise and data. 521 Note, @async-await@ is just syntactic-sugar over the event engine so it does not solve these deficiencies. 522 For multi-threaded languages like Java, the asynchronous call queues a callee action with an executor (server), which subsequently executes the work by a thread in the executor thread-pool. 523 The problem is when concurrent work-units need to interact and/or block as this effects the executor, \eg stops threads. 524 While it is possible to extend this approach to support the necessary mechanisms, \eg message passing in Actors, we show monitors and threads provide an equally competitive approach that does not deviate from normal call communication and can be used to build asynchronous call, as is done in Java. 382 525 383 526 … … 385 528 \label{s:StatefulFunction} 386 529 387 The stateful function is an old idea~\cite{Conway63,Marlin80} that is new again~\cite{C++20Coroutine19}, where execution is temporarily suspended and later resumed, \eg plugin, device driver, finite-state machine. 388 Hence, a stateful function may not end when it returns to its caller, allowing it to be restarted with the data and execution location present at the point of suspension. 389 This capability is accomplished by retaining a data/execution \emph{closure} between invocations. 390 If the closure is fixed size, we call it a \emph{generator} (or \emph{stackless}), and its control flow is restricted, \eg suspending outside the generator is prohibited. 391 If the closure is variable size, we call it a \emph{coroutine} (or \emph{stackful}), and as the names implies, often implemented with a separate stack with no programming restrictions. 392 Hence, refactoring a stackless coroutine may require changing it to stackful. 393 A foundational property of all \emph{stateful functions} is that resume/suspend \emph{do not} cause incremental stack growth, \ie resume/suspend operations are remembered through the closure not the stack. 394 As well, activating a stateful function is \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles). 395 A fixed closure activated by modified call/return is faster than a variable closure activated by context switching. 396 Additionally, any storage management for the closure (especially in unmanaged languages, \ie no garbage collection) must also be factored into design and performance. 397 Therefore, selecting between stackless and stackful semantics is a tradeoff between programming requirements and performance, where stackless is faster and stackful is more general. 398 Note, creation cost is amortized across usage, so activation cost is usually the dominant factor. 530 A \emph{stateful function} has the ability to remember state between calls, where state can be either data or execution, \eg plugin, device driver, finite-state machine (FSM). 531 A simple technique to retain data state between calls is @static@ declarations within a function, which is often implemented by hoisting the declarations to the global scope but hiding the names within the function using name mangling. 532 However, each call starts the function at the top making it difficult to determine the last point of execution in an algorithm, and requiring multiple flag variables and testing to reestablish the continuation point. 533 Hence, the next step of generalizing function state is implicitly remembering the return point between calls and reentering the function at this point rather than the top, called \emph{generators}\,/\,\emph{iterators} or \emph{stackless coroutines}. 534 For example, a Fibonacci generator retains data and execution state allowing it to remember prior values needed to generate the next value and the location in the algorithm to compute that value. 535 The next step of generalization is instantiating the function to allow multiple named instances, \eg multiple Fibonacci generators, where each instance has its own state, and hence, can generate an independent sequence of values. 536 Note, a subset of generator state is a function \emph{closure}, \ie the technique of capturing lexical references when returning a nested function. 537 A further generalization is adding a stack to a generator's state, called a \emph{coroutine}, so it can suspend outside of itself, \eg call helper functions to arbitrary depth before suspending back to its resumer without unwinding these calls. 538 For example, a coroutine iterator for a binary tree can stop the traversal at the visit point (pre, infix, post traversal), return the node value to the caller, and then continue the recursive traversal from the current node on the next call. 539 540 There are two styles of activating a stateful function, \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles). 541 These styles \emph{do not} cause incremental stack growth, \eg a million resume/suspend or resume/resume cycles do not remember each cycle just the last resumer for each cycle. 542 Selecting between stackless/stackful semantics and asymmetric/symmetric style is a tradeoff between programming requirements, performance, and design, where stackless is faster and smaller (modified call/return between closures), stackful is more general but slower and larger (context switching between distinct stacks), and asymmetric is simpler control-flow than symmetric. 543 Additionally, storage management for the closure/stack (especially in unmanaged languages, \ie no garbage collection) must be factored into design and performance. 544 Note, creation cost (closure/stack) is amortized across usage, so activation cost (resume/suspend) is usually the dominant factor. 545 546 % The stateful function is an old idea~\cite{Conway63,Marlin80} that is new again~\cite{C++20Coroutine19}, where execution is temporarily suspended and later resumed, \eg plugin, device driver, finite-state machine. 547 % Hence, a stateful function may not end when it returns to its caller, allowing it to be restarted with the data and execution location present at the point of suspension. 548 % If the closure is fixed size, we call it a \emph{generator} (or \emph{stackless}), and its control flow is restricted, \eg suspending outside the generator is prohibited. 549 % If the closure is variable size, we call it a \emph{coroutine} (or \emph{stackful}), and as the names implies, often implemented with a separate stack with no programming restrictions. 550 % Hence, refactoring a stackless coroutine may require changing it to stackful. 551 % A foundational property of all \emph{stateful functions} is that resume/suspend \emph{do not} cause incremental stack growth, \ie resume/suspend operations are remembered through the closure not the stack. 552 % As well, activating a stateful function is \emph{asymmetric} or \emph{symmetric}, identified by resume/suspend (no cycles) and resume/resume (cycles). 553 % A fixed closure activated by modified call/return is faster than a variable closure activated by context switching. 554 % Additionally, any storage management for the closure (especially in unmanaged languages, \ie no garbage collection) must also be factored into design and performance. 555 % Therefore, selecting between stackless and stackful semantics is a tradeoff between programming requirements and performance, where stackless is faster and stackful is more general. 556 % nppNote, creation cost is amortized across usage, so activation cost is usually the dominant factor. 557 558 For example, Python presents asymmetric generators as a function object, \uC presents symmetric coroutines as a \lstinline[language=C++]|class|-like object, and many languages present threading using function pointers, @pthreads@~\cite{Butenhof97}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}. 559 \begin{center} 560 \begin{tabular}{@{}l|l|l@{}} 561 \multicolumn{1}{@{}c|}{Python asymmetric generator} & \multicolumn{1}{c|}{\uC symmetric coroutine} & \multicolumn{1}{c@{}}{Pthreads thread} \\ 562 \hline 563 \begin{python} 564 `def Gen():` $\LstCommentStyle{\color{red}// function}$ 565 ... yield val ... 566 gen = Gen() 567 for i in range( 10 ): 568 print( next( gen ) ) 569 \end{python} 570 & 571 \begin{uC++} 572 `_Coroutine Cycle {` $\LstCommentStyle{\color{red}// class}$ 573 Cycle * p; 574 void main() { p->cycle(); } 575 void cycle() { resume(); } `};` 576 Cycle c1, c2; c1.p=&c2; c2.p=&c1; c1.cycle(); 577 \end{uC++} 578 & 579 \begin{cfa} 580 void * rtn( void * arg ) { ... } 581 int i = 3, rc; 582 pthread_t t; $\C{// thread id}$ 583 $\LstCommentStyle{\color{red}// function pointer}$ 584 rc=pthread_create(&t, `rtn`, (void *)i); 585 \end{cfa} 586 \end{tabular} 587 \end{center} 588 \CFA's preferred presentation model for generators/coroutines/threads is a hybrid of functions and classes, giving an object-oriented flavour. 589 Essentially, the generator/coroutine/thread function is semantically coupled with a generator/coroutine/thread custom type via the type's name. 590 The custom type solves several issues, while accessing the underlying mechanisms used by the custom types is still allowed for flexibility reasons. 591 Each custom type is discussed in detail in the following sections. 592 593 594 \subsection{Generator} 595 596 Stackless generators (Table~\ref{t:ExecutionPropertyComposition} case 3) have the potential to be very small and fast, \ie as small and fast as function call/return for both creation and execution. 597 The \CFA goal is to achieve this performance target, possibly at the cost of some semantic complexity. 598 A series of different kinds of generators and their implementation demonstrate how this goal is accomplished.\footnote{ 599 The \CFA operator syntax uses \lstinline|?| to denote operands, which allows precise definitions for pre, post, and infix operators, \eg \lstinline|?++|, \lstinline|++?|, and \lstinline|?+?|, in addition \lstinline|?\{\}| denotes a constructor, as in \lstinline|foo `f` = `\{`...`\}`|, \lstinline|^?\{\}| denotes a destructor, and \lstinline|?()| is \CC function call \lstinline|operator()|. 600 Operator \lstinline+|+ is overloaded for printing, like bit-shift \lstinline|<<| in \CC. 601 The \CFA \lstinline|with| clause opens an aggregate scope making its fields directly accessible, like Pascal \lstinline|with|, but using parallel semantics; 602 multiple aggregates may be opened. 603 \CFA has rebindable references \lstinline|int i, & ip = i, j; `&ip = &j;`| and non-rebindable references \lstinline|int i, & `const` ip = i, j; `&ip = &j;` // disallowed|. 604 }% 399 605 400 606 \begin{figure} … … 410 616 411 617 618 619 412 620 int fn = f->fn; f->fn = f->fn1; 413 621 f->fn1 = f->fn + fn; 414 622 return fn; 415 416 623 } 417 624 int main() { … … 432 639 void `main(Fib & fib)` with(fib) { 433 640 641 434 642 [fn1, fn] = [1, 0]; 435 643 for () { … … 451 659 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 452 660 typedef struct { 453 int fn1, fn; void * `next`;661 int `restart`, fn1, fn; 454 662 } Fib; 455 #define FibCtor { 1, 0, NULL}663 #define FibCtor { `0`, 1, 0 } 456 664 Fib * comain( Fib * f ) { 457 if ( f->next ) goto *f->next; 458 f->next = &&s1; 665 `static void * states[] = {&&s0, &&s1};` 666 `goto *states[f->restart];` 667 s0: f->`restart` = 1; 459 668 for ( ;; ) { 460 669 return f; 461 670 s1:; int fn = f->fn + f->fn1; 462 671 f->fn1 = f->fn; f->fn = fn; 463 672 } 464 673 } … … 472 681 \end{lrbox} 473 682 474 \subfloat[C asymmetric generator]{\label{f:CFibonacci}\usebox\myboxA}683 \subfloat[C]{\label{f:CFibonacci}\usebox\myboxA} 475 684 \hspace{3pt} 476 685 \vrule 477 686 \hspace{3pt} 478 \subfloat[\CFA asymmetric generator]{\label{f:CFAFibonacciGen}\usebox\myboxB}687 \subfloat[\CFA]{\label{f:CFAFibonacciGen}\usebox\myboxB} 479 688 \hspace{3pt} 480 689 \vrule 481 690 \hspace{3pt} 482 \subfloat[C generat or implementation]{\label{f:CFibonacciSim}\usebox\myboxC}691 \subfloat[C generated code for \CFA version]{\label{f:CFibonacciSim}\usebox\myboxC} 483 692 \caption{Fibonacci (output) asymmetric generator} 484 693 \label{f:FibonacciAsymmetricGenerator} … … 493 702 }; 494 703 void ?{}( Fmt & fmt ) { `resume(fmt);` } // constructor 495 void ^?{}( Fmt & f ) with(f) { $\C[ 1.75in]{// destructor}$704 void ^?{}( Fmt & f ) with(f) { $\C[2.25in]{// destructor}$ 496 705 if ( g != 0 || b != 0 ) sout | nl; } 497 706 void `main( Fmt & f )` with(f) { … … 499 708 for ( ; g < 5; g += 1 ) { $\C{// groups}$ 500 709 for ( ; b < 4; b += 1 ) { $\C{// blocks}$ 501 `suspend;` $\C{// wait for character}$502 while ( ch == '\n' ) `suspend;` // ignore503 sout | ch; // newline504 } sout | " "; // block spacer505 } sout | nl; // group newline710 do { `suspend;` $\C{// wait for character}$ 711 while ( ch == '\n' ); // ignore newline 712 sout | ch; $\C{// print character}$ 713 } sout | " "; $\C{// block separator}$ 714 } sout | nl; $\C{// group separator}$ 506 715 } 507 716 } … … 521 730 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 522 731 typedef struct { 523 void * next;732 int `restart`, g, b; 524 733 char ch; 525 int g, b;526 734 } Fmt; 527 735 void comain( Fmt * f ) { 528 if ( f->next ) goto *f->next; 529 f->next = &&s1; 736 `static void * states[] = {&&s0, &&s1};` 737 `goto *states[f->restart];` 738 s0: f->`restart` = 1; 530 739 for ( ;; ) { 531 740 for ( f->g = 0; f->g < 5; f->g += 1 ) { 532 741 for ( f->b = 0; f->b < 4; f->b += 1 ) { 533 return;534 s1:; while ( f->ch == '\n' ) return;742 do { return; s1: ; 743 } while ( f->ch == '\n' ); 535 744 printf( "%c", f->ch ); 536 745 } printf( " " ); … … 539 748 } 540 749 int main() { 541 Fmt fmt = { NULL}; comain( &fmt ); // prime750 Fmt fmt = { `0` }; comain( &fmt ); // prime 542 751 for ( ;; ) { 543 752 scanf( "%c", &fmt.ch ); … … 550 759 \end{lrbox} 551 760 552 \subfloat[\CFA asymmetric generator]{\label{f:CFAFormatGen}\usebox\myboxA}553 \hspace{3 pt}761 \subfloat[\CFA]{\label{f:CFAFormatGen}\usebox\myboxA} 762 \hspace{35pt} 554 763 \vrule 555 764 \hspace{3pt} 556 \subfloat[C generat or simulation]{\label{f:CFormatSim}\usebox\myboxB}765 \subfloat[C generated code for \CFA version]{\label{f:CFormatGenImpl}\usebox\myboxB} 557 766 \hspace{3pt} 558 767 \caption{Formatter (input) asymmetric generator} … … 560 769 \end{figure} 561 770 562 Stateful functions appear as generators, coroutines, and threads, where presentations are based on function objects or pointers~\cite{Butenhof97, C++14, MS:VisualC++, BoostCoroutines15}. 563 For example, Python presents generators as a function object: 564 \begin{python} 565 def Gen(): 566 ... `yield val` ... 567 gen = Gen() 568 for i in range( 10 ): 569 print( next( gen ) ) 570 \end{python} 571 Boost presents coroutines in terms of four functor object-types: 572 \begin{cfa} 573 asymmetric_coroutine<>::pull_type 574 asymmetric_coroutine<>::push_type 575 symmetric_coroutine<>::call_type 576 symmetric_coroutine<>::yield_type 577 \end{cfa} 578 and many languages present threading using function pointers, @pthreads@~\cite{Butenhof97}, \Csharp~\cite{Csharp}, Go~\cite{Go}, and Scala~\cite{Scala}, \eg pthreads: 579 \begin{cfa} 580 void * rtn( void * arg ) { ... } 581 int i = 3, rc; 582 pthread_t t; $\C{// thread id}$ 583 `rc = pthread_create( &t, rtn, (void *)i );` $\C{// create and initialized task, type-unsafe input parameter}$ 584 \end{cfa} 585 % void mycor( pthread_t cid, void * arg ) { 586 % int * value = (int *)arg; $\C{// type unsafe, pointer-size only}$ 587 % // thread body 588 % } 589 % int main() { 590 % int input = 0, output; 591 % coroutine_t cid = coroutine_create( &mycor, (void *)&input ); $\C{// type unsafe, pointer-size only}$ 592 % coroutine_resume( cid, (void *)input, (void **)&output ); $\C{// type unsafe, pointer-size only}$ 593 % } 594 \CFA's preferred presentation model for generators/coroutines/threads is a hybrid of objects and functions, with an object-oriented flavour. 595 Essentially, the generator/coroutine/thread function is semantically coupled with a generator/coroutine/thread custom type. 596 The custom type solves several issues, while accessing the underlying mechanisms used by the custom types is still allowed. 597 598 599 \subsection{Generator} 600 601 Stackless generators have the potential to be very small and fast, \ie as small and fast as function call/return for both creation and execution. 602 The \CFA goal is to achieve this performance target, possibly at the cost of some semantic complexity. 603 A series of different kinds of generators and their implementation demonstrate how this goal is accomplished. 604 605 Figure~\ref{f:FibonacciAsymmetricGenerator} shows an unbounded asymmetric generator for an infinite sequence of Fibonacci numbers written in C and \CFA, with a simple C implementation for the \CFA version. 771 Figure~\ref{f:FibonacciAsymmetricGenerator} shows an unbounded asymmetric generator for an infinite sequence of Fibonacci numbers written (left to right) in C, \CFA, and showing the underlying C implementation for the \CFA version. 606 772 This generator is an \emph{output generator}, producing a new result on each resumption. 607 773 To compute Fibonacci, the previous two values in the sequence are retained to generate the next value, \ie @fn1@ and @fn@, plus the execution location where control restarts when the generator is resumed, \ie top or middle. … … 611 777 The C version only has the middle execution state because the top execution state is declaration initialization. 612 778 Figure~\ref{f:CFAFibonacciGen} shows the \CFA approach, which also has a manual closure, but replaces the structure with a custom \CFA @generator@ type. 613 This generator type is then connected to a function that \emph{must be named \lstinline|main|},\footnote{ 614 The name \lstinline|main| has special meaning in C, specifically the function where a program starts execution. 615 Hence, overloading this name for other starting points (generator/coroutine/thread) is a logical extension.} 616 called a \emph{generator main},which takes as its only parameter a reference to the generator type. 779 Each generator type must have a function named \lstinline|main|, 780 % \footnote{ 781 % The name \lstinline|main| has special meaning in C, specifically the function where a program starts execution. 782 % Leveraging starting semantics to this name for generator/coroutine/thread is a logical extension.} 783 called a \emph{generator main} (leveraging the starting semantics for program @main@ in C), which is connected to the generator type via its single reference parameter. 617 784 The generator main contains @suspend@ statements that suspend execution without ending the generator versus @return@. 618 For the Fibonacci generator-main,\footnote{ 619 The \CFA \lstinline|with| opens an aggregate scope making its fields directly accessible, like Pascal \lstinline|with|, but using parallel semantics. 620 Multiple aggregates may be opened.} 785 For the Fibonacci generator-main, 621 786 the top initialization state appears at the start and the middle execution state is denoted by statement @suspend@. 622 787 Any local variables in @main@ \emph{are not retained} between calls; … … 627 792 Resuming an ended (returned) generator is undefined. 628 793 Function @resume@ returns its argument generator so it can be cascaded in an expression, in this case to print the next Fibonacci value @fn@ computed in the generator instance. 629 Figure~\ref{f:CFibonacciSim} shows the C implementation of the \CFA generator only needs one additional field, @next@, to handle retention of execution state. 630 The computed @goto@ at the start of the generator main, which branches after the previous suspend, adds very little cost to the resume call. 631 Finally, an explicit generator type provides both design and performance benefits, such as multiple type-safe interface functions taking and returning arbitrary types.\footnote{ 632 The \CFA operator syntax uses \lstinline|?| to denote operands, which allows precise definitions for pre, post, and infix operators, \eg \lstinline|++?|, \lstinline|?++|, and \lstinline|?+?|, in addition \lstinline|?\{\}| denotes a constructor, as in \lstinline|foo `f` = `\{`...`\}`|, \lstinline|^?\{\}| denotes a destructor, and \lstinline|?()| is \CC function call \lstinline|operator()|. 633 }% 794 Figure~\ref{f:CFibonacciSim} shows the C implementation of the \CFA asymmetric generator. 795 Only one execution-state field, @restart@, is needed to subscript the suspension points in the generator. 796 At the start of the generator main, the @static@ declaration, @states@, is initialized to the N suspend points in the generator (where operator @&&@ dereferences/references a label~\cite{gccValueLabels}). 797 Next, the computed @goto@ selects the last suspend point and branches to it. 798 The cost of setting @restart@ and branching via the computed @goto@ adds very little cost to the suspend/resume calls. 799 800 An advantage of the \CFA explicit generator type is the ability to allow multiple type-safe interface functions taking and returning arbitrary types. 634 801 \begin{cfa} 635 802 int ?()( Fib & fib ) { return `resume( fib )`.fn; } $\C[3.9in]{// function-call interface}$ 636 int ?()( Fib & fib, int N ) { for ( N - 1 ) `fib()`; return `fib()`; } $\C{// use function-call interface to skip N values}$ 637 double ?()( Fib & fib ) { return (int)`fib()` / 3.14159; } $\C{// different return type, cast prevents recursive call}\CRT$ 638 sout | (int)f1() | (double)f1() | f2( 2 ); // alternative interface, cast selects call based on return type, step 2 values 803 int ?()( Fib & fib, int N ) { for ( N - 1 ) `fib()`; return `fib()`; } $\C{// add parameter to skip N values}$ 804 double ?()( Fib & fib ) { return (int)`fib()` / 3.14159; } $\C{// different return type, cast prevents recursive call}$ 805 Fib f; int i; double d; 806 i = f(); i = f( 2 ); d = f(); $\C{// alternative interfaces}\CRT$ 639 807 \end{cfa} 640 808 Now, the generator can be a separately compiled opaque-type only accessed through its interface functions. 641 809 For contrast, Figure~\ref{f:PythonFibonacci} shows the equivalent Python Fibonacci generator, which does not use a generator type, and hence only has a single interface, but an implicit closure. 642 810 643 Having to manually create the generator closure by moving local-state variables into the generator type is an additional programmer burden. 644 (This restriction is removed by the coroutine in Section~\ref{s:Coroutine}.) 645 This requirement follows from the generality of variable-size local-state, \eg local state with a variable-length array requires dynamic allocation because the array size is unknown at compile time. 811 \begin{figure} 812 %\centering 813 \newbox\myboxA 814 \begin{lrbox}{\myboxA} 815 \begin{python}[aboveskip=0pt,belowskip=0pt] 816 def Fib(): 817 fn1, fn = 0, 1 818 while True: 819 `yield fn1` 820 fn1, fn = fn, fn1 + fn 821 f1 = Fib() 822 f2 = Fib() 823 for i in range( 10 ): 824 print( next( f1 ), next( f2 ) ) 825 826 827 828 829 830 831 832 833 834 835 \end{python} 836 \end{lrbox} 837 838 \newbox\myboxB 839 \begin{lrbox}{\myboxB} 840 \begin{python}[aboveskip=0pt,belowskip=0pt] 841 def Fmt(): 842 try: 843 while True: $\C[2.5in]{\# until destructor call}$ 844 for g in range( 5 ): $\C{\# groups}$ 845 for b in range( 4 ): $\C{\# blocks}$ 846 while True: 847 ch = (yield) $\C{\# receive from send}$ 848 if '\n' not in ch: $\C{\# ignore newline}$ 849 break 850 print( ch, end='' ) $\C{\# print character}$ 851 print( ' ', end='' ) $\C{\# block separator}$ 852 print() $\C{\# group separator}$ 853 except GeneratorExit: $\C{\# destructor}$ 854 if g != 0 | b != 0: $\C{\# special case}$ 855 print() 856 fmt = Fmt() 857 `next( fmt )` $\C{\# prime, next prewritten}$ 858 for i in range( 41 ): 859 `fmt.send( 'a' );` $\C{\# send to yield}$ 860 \end{python} 861 \end{lrbox} 862 863 \hspace{30pt} 864 \subfloat[Fibonacci]{\label{f:PythonFibonacci}\usebox\myboxA} 865 \hspace{3pt} 866 \vrule 867 \hspace{3pt} 868 \subfloat[Formatter]{\label{f:PythonFormatter}\usebox\myboxB} 869 \caption{Python generator} 870 \label{f:PythonGenerator} 871 \end{figure} 872 873 Having to manually create the generator closure by moving local-state variables into the generator type is an additional programmer burden (removed by the coroutine in Section~\ref{s:Coroutine}). 874 This manual requirement follows from the generality of allowing variable-size local-state, \eg local state with a variable-length array requires dynamic allocation as the array size is unknown at compile time. 646 875 However, dynamic allocation significantly increases the cost of generator creation/destruction and is a showstopper for embedded real-time programming. 647 876 But more importantly, the size of the generator type is tied to the local state in the generator main, which precludes separate compilation of the generator main, \ie a generator must be inlined or local state must be dynamically allocated. 648 With respect to safety, we believe static analysis can discriminate local state from temporary variables in a generator, \ie variable usage spanning @suspend@, and generate a compile-time error.649 Finally, our current experience is that most generatorproblems have simple data state, including local state, but complex execution state, so the burden of creating the generator type is small.877 With respect to safety, we believe static analysis can discriminate persistent generator state from temporary generator-main state and raise a compile-time error for temporary usage spanning suspend points. 878 Our experience using generators is that the problems have simple data state, including local state, but complex execution state, so the burden of creating the generator type is small. 650 879 As well, C programmers are not afraid of this kind of semantic programming requirement, if it results in very small, fast generators. 651 880 … … 669 898 The example takes advantage of resuming a generator in the constructor to prime the loops so the first character sent for formatting appears inside the nested loops. 670 899 The destructor provides a newline, if formatted text ends with a full line. 671 Figure~\ref{f:CFormatSim} shows the C implementation of the \CFA input generator with one additional field and the computed @goto@. 672 For contrast, Figure~\ref{f:PythonFormatter} shows the equivalent Python format generator with the same properties as the Fibonacci generator. 673 674 Figure~\ref{f:DeviceDriverGen} shows a \emph{killer} asymmetric generator, a device-driver, because device drivers caused 70\%-85\% of failures in Windows/Linux~\cite{Swift05}. 675 Device drives follow the pattern of simple data state but complex execution state, \ie finite state-machine (FSM) parsing a protocol. 676 For example, the following protocol: 900 Figure~\ref{f:CFormatGenImpl} shows the C implementation of the \CFA input generator with one additional field and the computed @goto@. 901 For contrast, Figure~\ref{f:PythonFormatter} shows the equivalent Python format generator with the same properties as the format generator. 902 903 % https://dl-acm-org.proxy.lib.uwaterloo.ca/ 904 905 Figure~\ref{f:DeviceDriverGen} shows an important application for an asymmetric generator, a device-driver, because device drivers are a significant source of operating-system errors: 85\% in Windows XP~\cite[p.~78]{Swift05} and 51.6\% in Linux~\cite[p.~1358,]{Xiao19}. %\cite{Palix11} 906 Swift \etal~\cite[p.~86]{Swift05} restructure device drivers using the Extension Procedure Call (XPC) within the kernel via functions @nooks_driver_call@ and @nooks_kernel_call@, which have coroutine properties context switching to separate stacks with explicit hand-off calls; 907 however, the calls do not retain execution state, and hence always start from the top. 908 The alternative approach for implementing device drivers is using stack-ripping. 909 However, Adya \etal~\cite{Adya02} argue against stack ripping in Section 3.2 and suggest a hybrid approach in Section 4 using cooperatively scheduled \emph{fibers}, which is coroutining. 910 911 As an example, the following protocol: 677 912 \begin{center} 678 913 \ldots\, STX \ldots\, message \ldots\, ESC ETX \ldots\, message \ldots\, ETX 2-byte crc \ldots 679 914 \end{center} 680 is anetwork message beginning with the control character STX, ending with an ETX, and followed by a 2-byte cyclic-redundancy check.915 is for a simple network message beginning with the control character STX, ending with an ETX, and followed by a 2-byte cyclic-redundancy check. 681 916 Control characters may appear in a message if preceded by an ESC. 682 917 When a message byte arrives, it triggers an interrupt, and the operating system services the interrupt by calling the device driver with the byte read from a hardware register. 683 The device driver returns a status code of its current state, and when a complete message is obtained, the operating system knows the message is in the message buffer. 684 Hence, the device driver is an input/output generator. 685 686 Note, the cost of creating and resuming the device-driver generator, @Driver@, is virtually identical to call/return, so performance in an operating-system kernel is excellent. 687 As well, the data state is small, where variables @byte@ and @msg@ are communication variables for passing in message bytes and returning the message, and variables @lnth@, @crc@, and @sum@ are local variable that must be retained between calls and are manually hoisted into the generator type. 688 % Manually, detecting and hoisting local-state variables is easy when the number is small. 689 In contrast, the execution state is large, with one @resume@ and seven @suspend@s. 690 Hence, the key benefits of the generator are correctness, safety, and maintenance because the execution states are transcribed directly into the programming language rather than using a table-driven approach. 691 Because FSMs can be complex and frequently occur in important domains, direct generator support is important in a system programming language. 918 The device driver returns a status code of its current state, and when a complete message is obtained, the operating system read the message accumulated in the supplied buffer. 919 Hence, the device driver is an input/output generator, where the cost of resuming the device-driver generator is the same as call/return, so performance in an operating-system kernel is excellent. 920 The key benefits of using a generator are correctness, safety, and maintenance because the execution states are transcribed directly into the programming language rather than table lookup or stack ripping. 921 The conclusion is that FSMs are complex and occur in important domains, so direct generator support is important in a system programming language. 692 922 693 923 \begin{figure} 694 924 \centering 695 \newbox\myboxA696 \begin{lrbox}{\myboxA}697 \begin{python}[aboveskip=0pt,belowskip=0pt]698 def Fib():699 fn1, fn = 0, 1700 while True:701 `yield fn1`702 fn1, fn = fn, fn1 + fn703 f1 = Fib()704 f2 = Fib()705 for i in range( 10 ):706 print( next( f1 ), next( f2 ) )707 708 709 710 711 712 713 \end{python}714 \end{lrbox}715 716 \newbox\myboxB717 \begin{lrbox}{\myboxB}718 \begin{python}[aboveskip=0pt,belowskip=0pt]719 def Fmt():720 try:721 while True:722 for g in range( 5 ):723 for b in range( 4 ):724 print( `(yield)`, end='' )725 print( ' ', end='' )726 print()727 except GeneratorExit:728 if g != 0 | b != 0:729 print()730 fmt = Fmt()731 `next( fmt )` # prime, next prewritten732 for i in range( 41 ):733 `fmt.send( 'a' );` # send to yield734 \end{python}735 \end{lrbox}736 \subfloat[Fibonacci]{\label{f:PythonFibonacci}\usebox\myboxA}737 \hspace{3pt}738 \vrule739 \hspace{3pt}740 \subfloat[Formatter]{\label{f:PythonFormatter}\usebox\myboxB}741 \caption{Python generator}742 \label{f:PythonGenerator}743 744 \bigskip745 746 925 \begin{tabular}{@{}l|l@{}} 747 926 \begin{cfa}[aboveskip=0pt,belowskip=0pt] … … 750 929 `generator` Driver { 751 930 Status status; 752 unsignedchar byte, * msg; // communication753 unsignedint lnth, sum; // local state754 unsignedshort int crc;931 char byte, * msg; // communication 932 int lnth, sum; // local state 933 short int crc; 755 934 }; 756 935 void ?{}( Driver & d, char * m ) { d.msg = m; } … … 800 979 (The trivial cycle is a generator resuming itself.) 801 980 This control flow is similar to recursion for functions but without stack growth. 802 The steps for symmetric control-flow are creating, executing, and terminating the cycle.981 Figure~\ref{f:PingPongFullCoroutineSteps} shows the steps for symmetric control-flow are creating, executing, and terminating the cycle. 803 982 Constructing the cycle must deal with definition-before-use to close the cycle, \ie, the first generator must know about the last generator, which is not within scope. 804 983 (This issue occurs for any cyclic data structure.) 805 % The example creates all the generatorsand then assigns the partners that form the cycle.806 % Alternatively, the constructor can assign the partners as they are declared, except the first, and the first-generator partner is set after the last generator declaration to close the cycle.807 Once the cycle is formed, the program main resumes one of the generators, and the generators can then traverse an arbitrary cycle using @resume@ to activate partner generator(s).984 The example creates the generators, @ping@/@pong@, and then assigns the partners that form the cycle. 985 % (Alternatively, the constructor can assign the partners as they are declared, except the first, and the first-generator partner is set after the last generator declaration to close the cycle.) 986 Once the cycle is formed, the program main resumes one of the generators, @ping@, and the generators can then traverse an arbitrary cycle using @resume@ to activate partner generator(s). 808 987 Terminating the cycle is accomplished by @suspend@ or @return@, both of which go back to the stack frame that started the cycle (program main in the example). 988 Note, the creator and starter may be different, \eg if the creator calls another function that starts the cycle. 809 989 The starting stack-frame is below the last active generator because the resume/resume cycle does not grow the stack. 810 Also, since local variables are not retained in the generator function, it does not contain any objects with destructors that must be called, so the cost is the same as a function return. 811 Destructor cost occurs when the generator instance is deallocated, which is easily controlled by the programmer. 812 813 Figure~\ref{f:CPingPongSim} shows the implementation of the symmetric generator, where the complexity is the @resume@, which needs an extension to the calling convention to perform a forward rather than backward jump. 814 This jump-starts at the top of the next generator main to re-execute the normal calling convention to make space on the stack for its local variables. 815 However, before the jump, the caller must reset its stack (and any registers) equivalent to a @return@, but subsequently jump forward. 816 This semantics is basically a tail-call optimization, which compilers already perform. 817 The example shows the assembly code to undo the generator's entry code before the direct jump. 818 This assembly code depends on what entry code is generated, specifically if there are local variables and the level of optimization. 819 To provide this new calling convention requires a mechanism built into the compiler, which is beyond the scope of \CFA at this time. 820 Nevertheless, it is possible to hand generate any symmetric generators for proof of concept and performance testing. 821 A compiler could also eliminate other artifacts in the generator simulation to further increase performance, \eg LLVM has various coroutine support~\cite{CoroutineTS}, and \CFA can leverage this support should it fork @clang@. 990 Also, since local variables are not retained in the generator function, there are no objects with destructors to be called, so the cost is the same as a function return. 991 Destructor cost occurs when the generator instance is deallocated by the creator. 822 992 823 993 \begin{figure} … … 826 996 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 827 997 `generator PingPong` { 998 int N, i; // local state 828 999 const char * name; 829 int N;830 int i; // local state831 1000 PingPong & partner; // rebindable reference 832 1001 }; 833 1002 834 1003 void `main( PingPong & pp )` with(pp) { 1004 1005 835 1006 for ( ; i < N; i += 1 ) { 836 1007 sout | name | i; … … 850 1021 \begin{cfa}[escapechar={},aboveskip=0pt,belowskip=0pt] 851 1022 typedef struct PingPong { 1023 int restart, N, i; 852 1024 const char * name; 853 int N, i;854 1025 struct PingPong * partner; 855 void * next;856 1026 } PingPong; 857 #define PPCtor(name, N) { name,N,0,NULL,NULL}1027 #define PPCtor(name, N) {0, N, 0, name, NULL} 858 1028 void comain( PingPong * pp ) { 859 if ( pp->next ) goto *pp->next; 860 pp->next = &&cycle; 1029 static void * states[] = {&&s0, &&s1}; 1030 goto *states[pp->restart]; 1031 s0: pp->restart = 1; 861 1032 for ( ; pp->i < pp->N; pp->i += 1 ) { 862 1033 printf( "%s %d\n", pp->name, pp->i ); 863 1034 asm( "mov %0,%%rdi" : "=m" (pp->partner) ); 864 1035 asm( "mov %rdi,%rax" ); 865 asm( "popq %rbx" ); 1036 asm( "add $16, %rsp" ); 1037 asm( "popq %rbp" ); 866 1038 asm( "jmp comain" ); 867 cycle: ;1039 s1: ; 868 1040 } 869 1041 } … … 881 1053 \end{figure} 882 1054 883 Finally, part of this generator work was inspired by the recent \CCtwenty generator proposal~\cite{C++20Coroutine19} (which they call coroutines). 1055 \begin{figure} 1056 \centering 1057 \input{FullCoroutinePhases.pstex_t} 1058 \vspace*{-10pt} 1059 \caption{Symmetric coroutine steps: Ping / Pong} 1060 \label{f:PingPongFullCoroutineSteps} 1061 \end{figure} 1062 1063 Figure~\ref{f:CPingPongSim} shows the C implementation of the \CFA symmetric generator, where there is still only one additional field, @restart@, but @resume@ is more complex because it does a forward rather than backward jump. 1064 Before the jump, the parameter for the next call @partner@ is placed into the register used for the first parameter, @rdi@, and the remaining registers are reset for a return. 1065 The @jmp comain@ restarts the function but with a different parameter, so the new call's behaviour depends on the state of the coroutine type, i.e., branch to restart location with different data state. 1066 While the semantics of call forward is a tail-call optimization, which compilers perform, the generator state is different on each call rather a common state for a tail-recursive function (i.e., the parameter to the function never changes during the forward calls. 1067 However, this assembler code depends on what entry code is generated, specifically if there are local variables and the level of optimization. 1068 Hence, internal compiler support is necessary for any forward call (or backwards return), \eg LLVM has various coroutine support~\cite{CoroutineTS}, and \CFA can leverage this support should it eventually fork @clang@. 1069 For this reason, \CFA does not support general symmetric generators at this time, but, it is possible to hand generate any symmetric generators (as in Figure~\ref{f:CPingPongSim}) for proof of concept and performance testing. 1070 1071 Finally, part of this generator work was inspired by the recent \CCtwenty coroutine proposal~\cite{C++20Coroutine19}, which uses the general term coroutine to mean generator. 884 1072 Our work provides the same high-performance asymmetric generators as \CCtwenty, and extends their work with symmetric generators. 885 1073 An additional \CCtwenty generator feature allows @suspend@ and @resume@ to be followed by a restricted compound statement that is executed after the current generator has reset its stack but before calling the next generator, specified with \CFA syntax: … … 896 1084 \label{s:Coroutine} 897 1085 898 Stackful coroutines extend generator semantics, \ie there is an implicit closure and @suspend@ may appear in a helper function called from the coroutine main.1086 Stackful coroutines (Table~\ref{t:ExecutionPropertyComposition} case 5) extend generator semantics, \ie there is an implicit closure and @suspend@ may appear in a helper function called from the coroutine main. 899 1087 A coroutine is specified by replacing @generator@ with @coroutine@ for the type. 900 Coroutine generality results in higher cost for creation, due to dynamic stack allocation, execution, due to context switching among stacks, andterminating, due to possible stack unwinding and dynamic stack deallocation.1088 Coroutine generality results in higher cost for creation, due to dynamic stack allocation, for execution, due to context switching among stacks, and for terminating, due to possible stack unwinding and dynamic stack deallocation. 901 1089 A series of different kinds of coroutines and their implementations demonstrate how coroutines extend generators. 902 1090 903 1091 First, the previous generator examples are converted to their coroutine counterparts, allowing local-state variables to be moved from the generator type into the coroutine main. 904 \begin{description} 905 \item[Fibonacci] 906 Move the declaration of @fn1@ to the start of coroutine main. 1092 \begin{center} 1093 \begin{tabular}{@{}l|l|l|l@{}} 1094 \multicolumn{1}{c|}{Fibonacci} & \multicolumn{1}{c|}{Formatter} & \multicolumn{1}{c|}{Device Driver} & \multicolumn{1}{c}{PingPong} \\ 1095 \hline 907 1096 \begin{cfa}[xleftmargin=0pt] 908 void main( Fib & fib ) with(fib) {1097 void main( Fib & fib ) ... 909 1098 `int fn1;` 910 \end{cfa} 911 \item[Formatter] 912 Move the declaration of @g@ and @b@ to the for loops in the coroutine main. 1099 1100 1101 \end{cfa} 1102 & 913 1103 \begin{cfa}[xleftmargin=0pt] 914 1104 for ( `g`; 5 ) { 915 1105 for ( `b`; 4 ) { 916 \end{cfa} 917 \item[Device Driver] 918 Move the declaration of @lnth@ and @sum@ to their points of initialization. 1106 1107 1108 \end{cfa} 1109 & 919 1110 \begin{cfa}[xleftmargin=0pt] 920 status = CONT; 921 `unsigned int lnth = 0, sum = 0;` 922 ... 923 `unsigned short int crc = byte << 8;` 924 \end{cfa} 925 \item[PingPong] 926 Move the declaration of @i@ to the for loop in the coroutine main. 1111 status = CONT; 1112 `int lnth = 0, sum = 0;` 1113 ... 1114 `short int crc = byte << 8;` 1115 \end{cfa} 1116 & 927 1117 \begin{cfa}[xleftmargin=0pt] 928 void main( PingPong & pp ) with(pp) {1118 void main( PingPong & pp ) ... 929 1119 for ( `i`; N ) { 930 \end{cfa} 931 \end{description} 1120 1121 1122 \end{cfa} 1123 \end{tabular} 1124 \end{center} 932 1125 It is also possible to refactor code containing local-state and @suspend@ statements into a helper function, like the computation of the CRC for the device driver. 933 1126 \begin{cfa} 934 unsignedint Crc() {1127 int Crc() { 935 1128 `suspend;` 936 unsignedshort int crc = byte << 8;1129 short int crc = byte << 8; 937 1130 `suspend;` 938 1131 status = (crc | byte) == sum ? MSG : ECRC; … … 945 1138 946 1139 \begin{comment} 947 Figure~\ref{f:Coroutine3States} creates a @coroutine@ type, @`coroutine` Fib { int fn; }@, which provides communication, @fn@, for the \newterm{coroutine main}, @main@, which runs on the coroutine stack, and possibly multiple interface functions, \eg @ next@.1140 Figure~\ref{f:Coroutine3States} creates a @coroutine@ type, @`coroutine` Fib { int fn; }@, which provides communication, @fn@, for the \newterm{coroutine main}, @main@, which runs on the coroutine stack, and possibly multiple interface functions, \eg @restart@. 948 1141 Like the structure in Figure~\ref{f:ExternalState}, the coroutine type allows multiple instances, where instances of this type are passed to the (overloaded) coroutine main. 949 1142 The coroutine main's stack holds the state for the next generation, @f1@ and @f2@, and the code represents the three states in the Fibonacci formula via the three suspend points, to context switch back to the caller's @resume@. 950 The interface function @ next@, takes a Fibonacci instance and context switches to it using @resume@;1143 The interface function @restart@, takes a Fibonacci instance and context switches to it using @resume@; 951 1144 on restart, the Fibonacci field, @fn@, contains the next value in the sequence, which is returned. 952 1145 The first @resume@ is special because it allocates the coroutine stack and cocalls its coroutine main on that stack; … … 1114 1307 \begin{figure} 1115 1308 \centering 1116 \lstset{language=CFA,escapechar={},moredelim=**[is][\protect\color{red}]{`}{`}}% allow $1117 1309 \begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}} 1118 1310 \begin{cfa} 1119 1311 `coroutine` Prod { 1120 Cons & c; // communication1312 Cons & c; $\C[1.5in]{// communication}$ 1121 1313 int N, money, receipt; 1122 1314 }; 1123 1315 void main( Prod & prod ) with( prod ) { 1124 // 1st resume starts here 1125 for ( i; N ) { 1316 for ( i; N ) { $\C{// 1st resume}\CRT$ 1126 1317 int p1 = random( 100 ), p2 = random( 100 ); 1127 sout | p1 | " " | p2;1128 1318 int status = delivery( c, p1, p2 ); 1129 sout | " $" | money | nl | status;1130 1319 receipt += 1; 1131 1320 } 1132 1321 stop( c ); 1133 sout | "prod stops";1134 1322 } 1135 1323 int payment( Prod & prod, int money ) { … … 1152 1340 \begin{cfa} 1153 1341 `coroutine` Cons { 1154 Prod & p; // communication1342 Prod & p; $\C[1.5in]{// communication}$ 1155 1343 int p1, p2, status; 1156 1344 bool done; 1157 1345 }; 1158 1346 void ?{}( Cons & cons, Prod & p ) { 1159 &cons.p = &p; // reassignable reference1347 &cons.p = &p; $\C{// reassignable reference}$ 1160 1348 cons.[status, done ] = [0, false]; 1161 1349 } 1162 1350 void main( Cons & cons ) with( cons ) { 1163 // 1st resume starts here 1164 int money = 1, receipt; 1351 int money = 1, receipt; $\C{// 1st resume}\CRT$ 1165 1352 for ( ; ! done; ) { 1166 sout | p1 | " " | p2 | nl | " $" | money;1167 1353 status += 1; 1168 1354 receipt = payment( p, money ); 1169 sout | " #" | receipt;1170 1355 money += 1; 1171 1356 } 1172 sout | "cons stops";1173 1357 } 1174 1358 int delivery( Cons & cons, int p1, int p2 ) { … … 1191 1375 This example is illustrative because both producer/consumer have two interface functions with @resume@s that suspend execution in these interface (helper) functions. 1192 1376 The program main creates the producer coroutine, passes it to the consumer coroutine in its initialization, and closes the cycle at the call to @start@ along with the number of items to be produced. 1193 The first @resume@ of @prod@ creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it. 1194 @prod@'s coroutine main starts, creates local-state variables that are retained between coroutine activations, and executes $N$ iterations, each generating two random values, calling the consumer to deliver the values, and printing the status returned from the consumer. 1195 1377 The call to @start@ is the first @resume@ of @prod@, which remembers the program main as the starter and creates @prod@'s stack with a frame for @prod@'s coroutine main at the top, and context switches to it. 1378 @prod@'s coroutine main starts, creates local-state variables that are retained between coroutine activations, and executes $N$ iterations, each generating two random values, calling the consumer's @deliver@ function to transfer the values, and printing the status returned from the consumer. 1196 1379 The producer call to @delivery@ transfers values into the consumer's communication variables, resumes the consumer, and returns the consumer status. 1197 On the first resume, @cons@'s stack is created and initialized, holding local-state variables retained between subsequent activations of the coroutine. 1198 The consumer iterates until the @done@ flag is set, prints the values delivered by the producer, increments status, and calls back to the producer via @payment@, and on return from @payment@, prints the receipt from the producer and increments @money@ (inflation). 1199 The call from the consumer to @payment@ introduces the cycle between producer and consumer. 1200 When @payment@ is called, the consumer copies values into the producer's communication variable and a resume is executed. 1201 The context switch restarts the producer at the point where it last context switched, so it continues in @delivery@ after the resume. 1202 @delivery@ returns the status value in @prod@'s coroutine main, where the status is printed. 1203 The loop then repeats calling @delivery@, where each call resumes the consumer coroutine. 1204 The context switch to the consumer continues in @payment@. 1205 The consumer increments and returns the receipt to the call in @cons@'s coroutine main. 1206 The loop then repeats calling @payment@, where each call resumes the producer coroutine. 1380 Similarly on the first resume, @cons@'s stack is created and initialized, holding local-state variables retained between subsequent activations of the coroutine. 1381 The symmetric coroutine cycle forms when the consumer calls the producer's @payment@ function, which resumes the producer in the consumer's delivery function. 1382 When the producer calls @delivery@ again, it resumes the consumer in the @payment@ function. 1383 Both interface function than return to the their corresponding coroutine-main functions for the next cycle. 1207 1384 Figure~\ref{f:ProdConsRuntimeStacks} shows the runtime stacks of the program main, and the coroutine mains for @prod@ and @cons@ during the cycling. 1385 As a consequence of a coroutine retaining its last resumer for suspending back, these reverse pointers allow @suspend@ to cycle \emph{backwards} around a symmetric coroutine cycle. 1208 1386 1209 1387 \begin{figure} … … 1214 1392 \caption{Producer / consumer runtime stacks} 1215 1393 \label{f:ProdConsRuntimeStacks} 1216 1217 \medskip1218 1219 \begin{center}1220 \input{FullCoroutinePhases.pstex_t}1221 \end{center}1222 \vspace*{-10pt}1223 \caption{Ping / Pong coroutine steps}1224 \label{f:PingPongFullCoroutineSteps}1225 1394 \end{figure} 1226 1395 1227 1396 Terminating a coroutine cycle is more complex than a generator cycle, because it requires context switching to the program main's \emph{stack} to shutdown the program, whereas generators started by the program main run on its stack. 1228 Furthermore, each deallocated coroutine must guarantee all destructors are run for object allocated in the coroutine type \emph{and} allocated on the coroutine's stack at the point of suspension, which can be arbitrarily deep. 1229 When a coroutine's main ends, its stack is already unwound so any stack allocated objects with destructors have been finalized. 1397 Furthermore, each deallocated coroutine must execute all destructors for object allocated in the coroutine type \emph{and} allocated on the coroutine's stack at the point of suspension, which can be arbitrarily deep. 1398 In the example, termination begins with the producer's loop stopping after N iterations and calling the consumer's @stop@ function, which sets the @done@ flag, resumes the consumer in function @payment@, terminating the call, and the consumer's loop in its coroutine main. 1399 % (Not shown is having @prod@ raise a nonlocal @stop@ exception at @cons@ after it finishes generating values and suspend back to @cons@, which catches the @stop@ exception to terminate its loop.) 1400 When the consumer's main ends, its stack is already unwound so any stack allocated objects with destructors are finalized. 1401 The question now is where does control continue? 1402 1230 1403 The na\"{i}ve semantics for coroutine-cycle termination is to context switch to the last resumer, like executing a @suspend@/@return@ in a generator. 1231 1404 However, for coroutines, the last resumer is \emph{not} implicitly below the current stack frame, as for generators, because each coroutine's stack is independent. 1232 1405 Unfortunately, it is impossible to determine statically if a coroutine is in a cycle and unrealistic to check dynamically (graph-cycle problem). 1233 1406 Hence, a compromise solution is necessary that works for asymmetric (acyclic) and symmetric (cyclic) coroutines. 1234 1235 Our solution is to context switch back to the first resumer (starter) once the coroutine ends.1407 Our solution is to retain a coroutine's starter (first resumer), and context switch back to the starter when the coroutine ends. 1408 Hence, the consumer restarts its first resumer, @prod@, in @stop@, and when the producer ends, it restarts its first resumer, program main, in @start@ (see dashed lines from the end of the coroutine mains in Figure~\ref{f:ProdConsRuntimeStacks}). 1236 1409 This semantics works well for the most common asymmetric and symmetric coroutine usage patterns. 1237 For asymmetric coroutines, it is common for the first resumer (starter) coroutine to be the only resumer. 1238 All previous generators converted to coroutines have this property. 1239 For symmetric coroutines, it is common for the cycle creator to persist for the lifetime of the cycle. 1240 Hence, the starter coroutine is remembered on the first resume and ending the coroutine resumes the starter. 1241 Figure~\ref{f:ProdConsRuntimeStacks} shows this semantic by the dashed lines from the end of the coroutine mains: @prod@ starts @cons@ so @cons@ resumes @prod@ at the end, and the program main starts @prod@ so @prod@ resumes the program main at the end. 1410 For asymmetric coroutines, it is common for the first resumer (starter) coroutine to be the only resumer; 1411 for symmetric coroutines, it is common for the cycle creator to persist for the lifetime of the cycle. 1242 1412 For other scenarios, it is always possible to devise a solution with additional programming effort, such as forcing the cycle forward (backward) to a safe point before starting termination. 1243 1413 1244 The producer/consumer example does not illustrate the full power of the starter semantics because @cons@ always ends first. 1245 Assume generator @PingPong@ is converted to a coroutine. 1246 Figure~\ref{f:PingPongFullCoroutineSteps} shows the creation, starter, and cyclic execution steps of the coroutine version. 1247 The program main creates (declares) coroutine instances @ping@ and @pong@. 1248 Next, program main resumes @ping@, making it @ping@'s starter, and @ping@'s main resumes @pong@'s main, making it @pong@'s starter. 1249 Execution forms a cycle when @pong@ resumes @ping@, and cycles $N$ times. 1250 By adjusting $N$ for either @ping@/@pong@, it is possible to have either one finish first, instead of @pong@ always ending first. 1251 If @pong@ ends first, it resumes its starter @ping@ in its coroutine main, then @ping@ ends and resumes its starter the program main in function @start@. 1252 If @ping@ ends first, it resumes its starter the program main in function @start@. 1253 Regardless of the cycle complexity, the starter stack always leads back to the program main, but the stack can be entered at an arbitrary point. 1254 Once back at the program main, coroutines @ping@ and @pong@ are deallocated. 1255 For generators, deallocation runs the destructors for all objects in the generator type. 1256 For coroutines, deallocation deals with objects in the coroutine type and must also run the destructors for any objects pending on the coroutine's stack for any unterminated coroutine. 1257 Hence, if a coroutine's destructor detects the coroutine is not ended, it implicitly raises a cancellation exception (uncatchable exception) at the coroutine and resumes it so the cancellation exception can propagate to the root of the coroutine's stack destroying all local variable on the stack. 1258 So the \CFA semantics for the generator and coroutine, ensure both can be safely deallocated at any time, regardless of their current state, like any other aggregate object. 1259 Explicitly raising normal exceptions at another coroutine can replace flag variables, like @stop@, \eg @prod@ raises a @stop@ exception at @cons@ after it finishes generating values and resumes @cons@, which catches the @stop@ exception to terminate its loop. 1260 1261 Finally, there is an interesting effect for @suspend@ with symmetric coroutines. 1262 A coroutine must retain its last resumer to suspend back because the resumer is on a different stack. 1263 These reverse pointers allow @suspend@ to cycle \emph{backwards}, which may be useful in certain cases. 1264 However, there is an anomaly if a coroutine resumes itself, because it overwrites its last resumer with itself, losing the ability to resume the last external resumer. 1265 To prevent losing this information, a self-resume does not overwrite the last resumer. 1414 Note, the producer/consumer example does not illustrate the full power of the starter semantics because @cons@ always ends first. 1415 Assume generator @PingPong@ in Figure~\ref{f:PingPongSymmetricGenerator} is converted to a coroutine. 1416 Unlike generators, coroutines have a starter structure with multiple levels, where the program main starts @ping@ and @ping@ starts @pong@. 1417 By adjusting $N$ for either @ping@/@pong@, it is possible to have either finish first. 1418 If @pong@ ends first, it resumes its starter @ping@ in its coroutine main, then @ping@ ends and resumes its starter the program main on return; 1419 if @ping@ ends first, it resumes its starter the program main on return. 1420 Regardless of the cycle complexity, the starter structure always leads back to the program main, but the path can be entered at an arbitrary point. 1421 Once back at the program main (creator), coroutines @ping@ and @pong@ are deallocated, runnning any destructors for objects within the coroutine and possibly deallocating any coroutine stacks for non-terminated coroutines, where stack deallocation implies stack unwinding to find destructors for allocated objects on the stack. 1422 Hence, the \CFA termination semantics for the generator and coroutine ensure correct deallocation semnatics, regardless of the coroutine's state (terminated or active), like any other aggregate object. 1266 1423 1267 1424 … … 1294 1451 Users wanting to extend custom types or build their own can only do so in ways offered by the language. 1295 1452 Furthermore, implementing custom types without language support may display the power of a programming language. 1296 \CFA blends the two approaches, providing custom type for idiomatic \CFA code, while extending and building new custom types is still possible, similar to Java concurrency with builtin and library .1453 \CFA blends the two approaches, providing custom type for idiomatic \CFA code, while extending and building new custom types is still possible, similar to Java concurrency with builtin and library (@java.util.concurrent@) monitors. 1297 1454 1298 1455 Part of the mechanism to generalize custom types is the \CFA trait~\cite[\S~2.3]{Moss18}, \eg the definition for custom-type @coroutine@ is anything satisfying the trait @is_coroutine@, and this trait both enforces and restricts the coroutine-interface functions. … … 1304 1461 forall( `dtype` T | is_coroutine(T) ) void $suspend$( T & ), resume( T & ); 1305 1462 \end{cfa} 1306 Note, copying generators/coroutines/threads is not meaningful. 1307 For example, both the resumer and suspender descriptors can have bidirectional pointers; 1308 copying these coroutines does not update the internal pointers so behaviour of both copies would be difficult to understand. 1309 Furthermore, two coroutines cannot logically execute on the same stack. 1310 A deep coroutine copy, which copies the stack, is also meaningless in an unmanaged language (no garbage collection), like C, because the stack may contain pointers to object within it that require updating for the copy. 1463 Note, copying generators/coroutines/threads is undefined because muliple objects cannot execute on a shared stack and stack copying does not work in unmanaged languages (no garbage collection), like C, because the stack may contain pointers to objects within it that require updating for the copy. 1311 1464 The \CFA @dtype@ property provides no \emph{implicit} copying operations and the @is_coroutine@ trait provides no \emph{explicit} copying operations, so all coroutines must be passed by reference (pointer). 1312 1465 The function definitions ensure there is a statically typed @main@ function that is the starting point (first stack frame) of a coroutine, and a mechanism to get (read) the coroutine descriptor from its handle. … … 1352 1505 The combination of custom types and fundamental @trait@ description of these types allows a concise specification for programmers and tools, while more advanced programmers can have tighter control over memory layout and initialization. 1353 1506 1354 Figure~\ref{f:CoroutineMemoryLayout} shows different memory-layout options for a coroutine (where a t askis similar).1507 Figure~\ref{f:CoroutineMemoryLayout} shows different memory-layout options for a coroutine (where a thread is similar). 1355 1508 The coroutine handle is the @coroutine@ instance containing programmer specified type global/communication variables across interface functions. 1356 1509 The coroutine descriptor contains all implicit declarations needed by the runtime, \eg @suspend@/@resume@, and can be part of the coroutine handle or separate. 1357 1510 The coroutine stack can appear in a number of locations and be fixed or variable sized. 1358 Hence, the coroutine's stack could be a VLS\footnote{1359 We are examining variable-sized structures (VLS), where fields can be variable-sized structures or arrays.1511 Hence, the coroutine's stack could be a variable-length structure (VLS)\footnote{ 1512 We are examining VLSs, where fields can be variable-sized structures or arrays. 1360 1513 Once allocated, a VLS is fixed sized.} 1361 1514 on the allocating stack, provided the allocating stack is large enough. 1362 1515 For a VLS stack allocation/deallocation is an inexpensive adjustment of the stack pointer, modulo any stack constructor costs (\eg initial frame setup). 1363 For heap stack allocation, allocation/deallocation is an expensive heap allocation (where the heap can be a shared resource), modulo any stack constructor costs.1364 With heap stack allocation, it is also possible to use a split (segmented) stack calling convention, available with gcc and clang, so the stack is variable sized.1516 For stack allocation in the heap, allocation/deallocation is an expensive allocation, where the heap can be a shared resource, modulo any stack constructor costs. 1517 It is also possible to use a split (segmented) stack calling convention, available with gcc and clang, allowing a variable-sized stack via a set of connected blocks in the heap. 1365 1518 Currently, \CFA supports stack/heap allocated descriptors but only fixed-sized heap allocated stacks. 1366 1519 In \CFA debug-mode, the fixed-sized stack is terminated with a write-only page, which catches most stack overflows. 1367 1520 Experience teaching concurrency with \uC~\cite{CS343} shows fixed-sized stacks are rarely an issue for students. 1368 Split-stack allocation is under development but requires recompilation of legacy code, which may be impossible.1521 Split-stack allocation is under development but requires recompilation of legacy code, which is not always possible. 1369 1522 1370 1523 \begin{figure} … … 1380 1533 1381 1534 Concurrency is nondeterministic scheduling of independent sequential execution paths (threads), where each thread has its own stack. 1382 A single thread with multiple call stacks, \newterm{coroutining}~\cite{Conway63,Marlin80}, does \emph{not} imply concurrency~\cite[\S~2]{Buhr05a}.1383 In coroutining, coroutinesself-schedule the thread across stacks so execution is deterministic.1535 A single thread with multiple stacks, \ie coroutining, does \emph{not} imply concurrency~\cite[\S~3]{Buhr05a}. 1536 Coroutining self-schedule the thread across stacks so execution is deterministic. 1384 1537 (It is \emph{impossible} to generate a concurrency error when coroutining.) 1385 However, coroutines are a stepping stone towards concurrency. 1386 1387 The transition to concurrency, even for a single thread with multiple stacks, occurs when coroutines context switch to a \newterm{scheduling coroutine}, introducing non-determinism from the coroutine perspective~\cite[\S~3,]{Buhr05a}. 1538 1539 The transition to concurrency, even for a single thread with multiple stacks, occurs when coroutines context switch to a \newterm{scheduling coroutine}, introducing non-determinism from the coroutine perspective~\cite[\S~3]{Buhr05a}. 1388 1540 Therefore, a minimal concurrency system requires coroutines \emph{in conjunction with a nondeterministic scheduler}. 1389 The resulting execution system now follows a cooperative threading model~\cite{Adya02,libdill}, called \newterm{non-preemptive scheduling}. 1390 Adding \newterm{preemption} introduces non-cooperative scheduling, where context switching occurs randomly between any two instructions often based on a timer interrupt, called \newterm{preemptive scheduling}. 1391 While a scheduler introduces uncertain execution among explicit context switches, preemption introduces uncertainty by introducing implicit context switches. 1541 The resulting execution system now follows a cooperative threading-model~\cite{Adya02,libdill} because context-switching points to the scheduler (blocking) are known, but the next unblocking point is unknown due to the scheduler. 1542 Adding \newterm{preemption} introduces \newterm{non-cooperative} or \newterm{preemptive} scheduling, where context switching points to the scheduler are unknown as they can occur randomly between any two instructions often based on a timer interrupt. 1392 1543 Uncertainty gives the illusion of parallelism on a single processor and provides a mechanism to access and increase performance on multiple processors. 1393 1544 The reason is that the scheduler/runtime have complete knowledge about resources and how to best utilized them. 1394 However, the introduction of unrestricted nondeterminism results in the need for \newterm{mutual exclusion} and \newterm{synchronization} , which restrict nondeterminism for correctness;1545 However, the introduction of unrestricted nondeterminism results in the need for \newterm{mutual exclusion} and \newterm{synchronization}~\cite[\S~4]{Buhr05a}, which restrict nondeterminism for correctness; 1395 1546 otherwise, it is impossible to write meaningful concurrent programs. 1396 1547 Optimal concurrent performance is often obtained by having as much nondeterminism as mutual exclusion and synchronization correctness allow. 1397 1548 1398 A scheduler can either be astackless or stackful.1549 A scheduler can also be stackless or stackful. 1399 1550 For stackless, the scheduler performs scheduling on the stack of the current coroutine and switches directly to the next coroutine, so there is one context switch. 1400 1551 For stackful, the current coroutine switches to the scheduler, which performs scheduling, and it then switches to the next coroutine, so there are two context switches. … … 1405 1556 \label{s:threads} 1406 1557 1407 Threading needs the ability to start a thread and wait for its completion.1558 Threading (Table~\ref{t:ExecutionPropertyComposition} case 11) needs the ability to start a thread and wait for its completion. 1408 1559 A common API for this ability is @fork@ and @join@. 1409 \begin{cquote} 1410 \begin{tabular}{@{}lll@{}} 1411 \multicolumn{1}{c}{\textbf{Java}} & \multicolumn{1}{c}{\textbf{\Celeven}} & \multicolumn{1}{c}{\textbf{pthreads}} \\ 1412 \begin{cfa} 1413 class MyTask extends Thread {...} 1414 mytask t = new MyTask(...); 1560 \vspace{4pt} 1561 \par\noindent 1562 \begin{tabular}{@{}l|l|l@{}} 1563 \multicolumn{1}{c|}{\textbf{Java}} & \multicolumn{1}{c|}{\textbf{\Celeven}} & \multicolumn{1}{c}{\textbf{pthreads}} \\ 1564 \hline 1565 \begin{cfa} 1566 class MyThread extends Thread {...} 1567 mythread t = new MyThread(...); 1415 1568 `t.start();` // start 1416 1569 // concurrency … … 1419 1572 & 1420 1573 \begin{cfa} 1421 class MyT ask{ ... } // functor1422 MyT ask mytask;1423 `thread t( myt ask, ... );` // start1574 class MyThread { ... } // functor 1575 MyThread mythread; 1576 `thread t( mythread, ... );` // start 1424 1577 // concurrency 1425 1578 `t.join();` // wait … … 1434 1587 \end{cfa} 1435 1588 \end{tabular} 1436 \end{cquote} 1589 \vspace{1pt} 1590 \par\noindent 1437 1591 \CFA has a simpler approach using a custom @thread@ type and leveraging declaration semantics (allocation/deallocation), where threads implicitly @fork@ after construction and @join@ before destruction. 1438 1592 \begin{cfa} 1439 thread MyT ask{};1440 void main( MyT ask& this ) { ... }1593 thread MyThread {}; 1594 void main( MyThread & this ) { ... } 1441 1595 int main() { 1442 MyT askteam`[10]`; $\C[2.5in]{// allocate stack-based threads, implicit start after construction}$1596 MyThread team`[10]`; $\C[2.5in]{// allocate stack-based threads, implicit start after construction}$ 1443 1597 // concurrency 1444 1598 } $\C{// deallocate stack-based threads, implicit joins before destruction}$ … … 1448 1602 Arbitrary topologies are possible using dynamic allocation, allowing threads to outlive their declaration scope, identical to normal dynamic allocation. 1449 1603 \begin{cfa} 1450 MyT ask* factory( int N ) { ... return `anew( N )`; } $\C{// allocate heap-based threads, implicit start after construction}$1604 MyThread * factory( int N ) { ... return `anew( N )`; } $\C{// allocate heap-based threads, implicit start after construction}$ 1451 1605 int main() { 1452 MyT ask* team = factory( 10 );1606 MyThread * team = factory( 10 ); 1453 1607 // concurrency 1454 1608 `delete( team );` $\C{// deallocate heap-based threads, implicit joins before destruction}\CRT$ … … 1496 1650 1497 1651 Threads in \CFA are user level run by runtime kernel threads (see Section~\ref{s:CFARuntimeStructure}), where user threads provide concurrency and kernel threads provide parallelism. 1498 Like coroutines, and for the same design reasons, \CFA provides a custom @thread@ type and a @trait@ to enforce and restrict the t ask-interface functions.1652 Like coroutines, and for the same design reasons, \CFA provides a custom @thread@ type and a @trait@ to enforce and restrict the thread-interface functions. 1499 1653 \begin{cquote} 1500 1654 \begin{tabular}{@{}c@{\hspace{3\parindentlnth}}c@{}} … … 1527 1681 \label{s:MutualExclusionSynchronization} 1528 1682 1529 Unrestricted nondeterminism is meaningless as there is no way to know when the result is completed without synchronization.1683 Unrestricted nondeterminism is meaningless as there is no way to know when a result is completed and safe to access. 1530 1684 To produce meaningful execution requires clawing back some determinism using mutual exclusion and synchronization, where mutual exclusion provides access control for threads using shared data, and synchronization is a timing relationship among threads~\cite[\S~4]{Buhr05a}. 1531 Some concurrent systems eliminate mutable shared-state by switching to stateless communication like message passing~\cite{Thoth,Harmony,V-Kernel,MPI} (Erlang, MPI), channels~\cite{CSP} (CSP,Go), actors~\cite{Akka} (Akka, Scala), or functional techniques (Haskell). 1685 The shared data protected by mutual exlusion is called a \newterm{critical section}~\cite{Dijkstra65}, and the protection can be simple (only 1 thread) or complex (only N kinds of threads, \eg group~\cite{Joung00} or readers/writer~\cite{Courtois71}). 1686 Without synchronization control in a critical section, an arriving thread can barge ahead of preexisting waiter threads resulting in short/long-term starvation, staleness/freshness problems, and/or incorrect transfer of data. 1687 Preventing or detecting barging is a challenge with low-level locks, but made easier through higher-level constructs. 1688 This challenge is often split into two different approaches: barging \emph{avoidance} and \emph{prevention}. 1689 Approaches that unconditionally releasing a lock for competing threads to acquire must use barging avoidance with flag/counter variable(s) to force barging threads to wait; 1690 approaches that conditionally hold locks during synchronization, \eg baton-passing~\cite{Andrews89}, prevent barging completely. 1691 1692 At the lowest level, concurrent control is provided by atomic operations, upon which different kinds of locking mechanisms are constructed, \eg spin locks, semaphores~\cite{Dijkstra68b}, barriers, and path expressions~\cite{Campbell74}. 1693 However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}. 1694 A significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock. 1695 Easing composability is another feature higher-level mutual-exclusion mechanisms can offer. 1696 Some concurrent systems eliminate mutable shared-state by switching to non-shared communication like message passing~\cite{Thoth,Harmony,V-Kernel,MPI} (Erlang, MPI), channels~\cite{CSP} (CSP,Go), actors~\cite{Akka} (Akka, Scala), or functional techniques (Haskell). 1532 1697 However, these approaches introduce a new communication mechanism for concurrency different from the standard communication using function call/return. 1533 1698 Hence, a programmer must learn and manipulate two sets of design/programming patterns. 1534 1699 While this distinction can be hidden away in library code, effective use of the library still has to take both paradigms into account. 1535 In contrast, approaches based on stateful models more closely resemble the standard call/return programming model, resulting in a single programming paradigm. 1536 1537 At the lowest level, concurrent control is implemented by atomic operations, upon which different kinds of locking mechanisms are constructed, \eg semaphores~\cite{Dijkstra68b}, barriers, and path expressions~\cite{Campbell74}. 1538 However, for productivity it is always desirable to use the highest-level construct that provides the necessary efficiency~\cite{Hochstein05}. 1539 A newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}. 1540 While this approach is pursued in hardware~\cite{Nakaike15} and system languages, like \CC~\cite{Cpp-Transactions}, the performance and feature set is still too restrictive to be the main concurrency paradigm for system languages, which is why it is rejected as the core paradigm for concurrency in \CFA. 1541 1542 One of the most natural, elegant, and efficient mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor}. 1543 First proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}, many concurrent programming languages provide monitors as an explicit language construct: \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}. 1544 In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as mutex locks or semaphores to simulate monitors. 1545 For these reasons, \CFA selected monitors as the core high-level concurrency construct, upon which higher-level approaches can be easily constructed. 1546 1547 1548 \subsection{Mutual Exclusion} 1549 1550 A group of instructions manipulating a specific instance of shared data that must be performed atomically is called a \newterm{critical section}~\cite{Dijkstra65}, which is enforced by \newterm{simple mutual-exclusion}. 1551 The generalization is called a \newterm{group critical-section}~\cite{Joung00}, where multiple tasks with the same session use the resource simultaneously and different sessions are segregated, which is enforced by \newterm{complex mutual-exclusion} providing the correct kind and number of threads using a group critical-section. 1552 The readers/writer problem~\cite{Courtois71} is an instance of a group critical-section, where readers share a session but writers have a unique session. 1553 1554 However, many solutions exist for mutual exclusion, which vary in terms of performance, flexibility and ease of use. 1555 Methods range from low-level locks, which are fast and flexible but require significant attention for correctness, to higher-level concurrency techniques, which sacrifice some performance to improve ease of use. 1556 Ease of use comes by either guaranteeing some problems cannot occur, \eg deadlock free, or by offering a more explicit coupling between shared data and critical section. 1557 For example, the \CC @std::atomic<T>@ offers an easy way to express mutual-exclusion on a restricted set of operations, \eg reading/writing, for numerical types. 1558 However, a significant challenge with locks is composability because it takes careful organization for multiple locks to be used while preventing deadlock. 1559 Easing composability is another feature higher-level mutual-exclusion mechanisms can offer. 1560 1561 1562 \subsection{Synchronization} 1563 1564 Synchronization enforces relative ordering of execution, and synchronization tools provide numerous mechanisms to establish these timing relationships. 1565 Low-level synchronization primitives offer good performance and flexibility at the cost of ease of use; 1566 higher-level mechanisms often simplify usage by adding better coupling between synchronization and data, \eg receive-specific versus receive-any thread in message passing or offering specialized solutions, \eg barrier lock. 1567 Often synchronization is used to order access to a critical section, \eg ensuring a waiting writer thread enters the critical section before a calling reader thread. 1568 If the calling reader is scheduled before the waiting writer, the reader has barged. 1569 Barging can result in staleness/freshness problems, where a reader barges ahead of a writer and reads temporally stale data, or a writer barges ahead of another writer overwriting data with a fresh value preventing the previous value from ever being read (lost computation). 1570 Preventing or detecting barging is an involved challenge with low-level locks, which is made easier through higher-level constructs. 1571 This challenge is often split into two different approaches: barging avoidance and prevention. 1572 Algorithms that unconditionally releasing a lock for competing threads to acquire use barging avoidance during synchronization to force a barging thread to wait; 1573 algorithms that conditionally hold locks during synchronization, \eg baton-passing~\cite{Andrews89}, prevent barging completely. 1700 In contrast, approaches based on shared-state models more closely resemble the standard call/return programming model, resulting in a single programming paradigm. 1701 Finally, a newer approach for restricting non-determinism is transactional memory~\cite{Herlihy93}. 1702 While this approach is pursued in hardware~\cite{Nakaike15} and system languages, like \CC~\cite{Cpp-Transactions}, the performance and feature set is still too restrictive~\cite{Cascaval08,Boehm09} to be the main concurrency paradigm for system languages. 1574 1703 1575 1704 … … 1577 1706 \label{s:Monitor} 1578 1707 1579 A \textbf{monitor} is a set of functions that ensure mutual exclusion when accessing shared state. 1580 More precisely, a monitor is a programming technique that implicitly binds mutual exclusion to static function scope, as opposed to locks, where mutual-exclusion is defined by acquire/release calls, independent of lexical context (analogous to block and heap storage allocation). 1708 One of the most natural, elegant, efficient, high-level mechanisms for mutual exclusion and synchronization for shared-memory systems is the \emph{monitor} (Table~\ref{t:ExecutionPropertyComposition} case 2). 1709 First proposed by Brinch Hansen~\cite{Hansen73} and later described and extended by C.A.R.~Hoare~\cite{Hoare74}, many concurrent programming languages provide monitors as an explicit language construct: \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}. 1710 In addition, operating-system kernels and device drivers have a monitor-like structure, although they often use lower-level primitives such as mutex locks or semaphores to manually implement a monitor. 1711 For these reasons, \CFA selected monitors as the core high-level concurrency construct, upon which higher-level approaches can be easily constructed. 1712 1713 Specifically, a \textbf{monitor} is a set of functions that ensure mutual exclusion when accessing shared state. 1714 More precisely, a monitor is a programming technique that implicitly binds mutual exclusion to static function scope by call/return, as opposed to locks, where mutual-exclusion is defined by acquire/release calls, independent of lexical context (analogous to block and heap storage allocation). 1581 1715 Restricting acquire/release points eases programming, comprehension, and maintenance, at a slight cost in flexibility and efficiency. 1582 1716 \CFA uses a custom @monitor@ type and leverages declaration semantics (deallocation) to protect active or waiting threads in a monitor. 1583 1717 1584 1718 The following is a \CFA monitor implementation of an atomic counter. 1585 \begin{cfa} [morekeywords=nomutex]1719 \begin{cfa} 1586 1720 `monitor` Aint { int cnt; }; $\C[4.25in]{// atomic integer counter}$ 1587 int ++?( Aint & `mutex`$\(_{opt}\)$ this ) with( this ) { return ++cnt; } $\C{// increment}$ 1588 int ?=?( Aint & `mutex`$\(_{opt}\)$ lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions with int}\CRT$ 1589 int ?=?( int & lhs, Aint & `mutex`$\(_{opt}\)$ rhs ) with( rhs ) { lhs = cnt; } 1590 \end{cfa} 1591 % The @Aint@ constructor, @?{}@, uses the \lstinline[morekeywords=nomutex]@nomutex@ qualifier indicating mutual exclusion is unnecessary during construction because an object is inaccessible (private) until after it is initialized. 1592 % (While a constructor may publish its address into a global variable, doing so generates a race-condition.) 1593 The prefix increment operation, @++?@, is normally @mutex@, indicating mutual exclusion is necessary during function execution, to protect the incrementing from race conditions, unless there is an atomic increment instruction for the implementation type. 1594 The assignment operators provide bidirectional conversion between an atomic and normal integer without accessing field @cnt@; 1595 these operations only need @mutex@, if reading/writing the implementation type is not atomic. 1596 The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics, which is similar to the \CC template @std::atomic@. 1721 int ++?( Aint & `mutex` this ) with( this ) { return ++cnt; } $\C{// increment}$ 1722 int ?=?( Aint & `mutex` lhs, int rhs ) with( lhs ) { cnt = rhs; } $\C{// conversions with int, mutex optional}\CRT$ 1723 int ?=?( int & lhs, Aint & `mutex` rhs ) with( rhs ) { lhs = cnt; } 1724 \end{cfa} 1725 The operators use the parameter-only declaration type-qualifier @mutex@ to mark which parameters require locking during function execution to protect from race conditions. 1726 The assignment operators provide bidirectional conversion between an atomic and normal integer without accessing field @cnt@. 1727 (These operations only need @mutex@, if reading/writing the implementation type is not atomic.) 1728 The atomic counter is used without any explicit mutual-exclusion and provides thread-safe semantics. 1597 1729 \begin{cfa} 1598 1730 int i = 0, j = 0, k = 5; … … 1602 1734 i = x; j = y; k = z; 1603 1735 \end{cfa} 1736 Note, like other concurrent programming languages, \CFA has specializations for the basic types using atomic instructions for performance and a general trait similar to the \CC template @std::atomic@. 1604 1737 1605 1738 \CFA monitors have \newterm{multi-acquire} semantics so the thread in the monitor may acquire it multiple times without deadlock, allowing recursion and calling other interface functions. 1739 \newpage 1606 1740 \begin{cfa} 1607 1741 monitor M { ... } m; … … 1612 1746 \end{cfa} 1613 1747 \CFA monitors also ensure the monitor lock is released regardless of how an acquiring function ends (normal or exceptional), and returning a shared variable is safe via copying before the lock is released. 1614 Similar safety is offered by \emph{explicit} mechanisms like \CC RAII; 1615 monitor \emph{implicit} safety ensures no programmer usage errors. 1748 Similar safety is offered by \emph{explicit} opt-in disciplines like \CC RAII versus the monitor \emph{implicit} language-enforced safety guarantee ensuring no programmer usage errors. 1616 1749 Furthermore, RAII mechanisms cannot handle complex synchronization within a monitor, where the monitor lock may not be released on function exit because it is passed to an unblocking thread; 1617 1750 RAII is purely a mutual-exclusion mechanism (see Section~\ref{s:Scheduling}). … … 1639 1772 \end{cquote} 1640 1773 The @dtype@ property prevents \emph{implicit} copy operations and the @is_monitor@ trait provides no \emph{explicit} copy operations, so monitors must be passed by reference (pointer). 1641 % Copying a lock is insecure because it is possible to copy an open lock and then use the open copy when the original lock is closed to simultaneously access the shared data.1642 % Copying a monitor is secure because both the lock and shared data are copies, but copying the shared data is meaningless because it no longer represents a unique entity.1643 1774 Similarly, the function definitions ensures there is a mechanism to get (read) the monitor descriptor from its handle, and a special destructor to prevent deallocation if a thread using the shared data. 1644 1775 The custom monitor type also inserts any locks needed to implement the mutual exclusion semantics. … … 1652 1783 For example, a monitor may be passed through multiple helper functions before it is necessary to acquire the monitor's mutual exclusion. 1653 1784 1654 The benefit of mandatory monitor qualifiers is self-documentation, but requiring both @mutex@ and \lstinline[morekeywords=nomutex]@nomutex@ for all monitor parameters is redundant. 1655 Instead, the semantics has one qualifier as the default and the other required. 1656 For example, make the safe @mutex@ qualifier the default because assuming \lstinline[morekeywords=nomutex]@nomutex@ may cause subtle errors. 1657 Alternatively, make the unsafe \lstinline[morekeywords=nomutex]@nomutex@ qualifier the default because it is the \emph{normal} parameter semantics while @mutex@ parameters are rare. 1658 Providing a default qualifier implies knowing whether a parameter is a monitor. 1659 Since \CFA relies heavily on traits as an abstraction mechanism, types can coincidentally match the monitor trait but not be a monitor, similar to inheritance where a shape and playing card can both be drawable. 1660 For this reason, \CFA requires programmers to identify the kind of parameter with the @mutex@ keyword and uses no keyword to mean \lstinline[morekeywords=nomutex]@nomutex@. 1785 \CFA requires programmers to identify the kind of parameter with the @mutex@ keyword and uses no keyword to mean \lstinline[morekeywords=nomutex]@nomutex@, because @mutex@ parameters are rare and no keyword is the \emph{normal} parameter semantics. 1786 Hence, @mutex@ parameters are documentation, at the function and its prototype, to both programmer and compiler, without other redundant keywords. 1787 Furthermore, \CFA relies heavily on traits as an abstraction mechanism, so the @mutex@ qualifier prevents coincidentally matching of a monitor trait with a type that is not a monitor, similar to coincidental inheritance where a shape and playing card can both be drawable. 1661 1788 1662 1789 The next semantic decision is establishing which parameter \emph{types} may be qualified with @mutex@. … … 1672 1799 Function @f3@ has a multiple object matrix, and @f4@ a multiple object data structure. 1673 1800 While shown shortly, multiple object acquisition is possible, but the number of objects must be statically known. 1674 Therefore, \CFA only acquires one monitor per parameter with at most one level of indirection, excluding pointers as it is impossible to statically determine the size.1801 Therefore, \CFA only acquires one monitor per parameter with exactly one level of indirection, and exclude pointer types to unknown sized arrays. 1675 1802 1676 1803 For object-oriented monitors, \eg Java, calling a mutex member \emph{implicitly} acquires mutual exclusion of the receiver object, @`rec`.foo(...)@. … … 1679 1806 While object-oriented monitors can be extended with a mutex qualifier for multiple-monitor members, no prior example of this feature could be found.} 1680 1807 called \newterm{bulk acquire}. 1681 \CFA guarantees acquisition order is consistent across calls to @mutex@ functions using the same monitors as arguments, so acquiring multiple monitorsis safe from deadlock.1808 \CFA guarantees bulk acquisition order is consistent across calls to @mutex@ functions using the same monitors as arguments, so acquiring multiple monitors in a bulk acquire is safe from deadlock. 1682 1809 Figure~\ref{f:BankTransfer} shows a trivial solution to the bank transfer problem~\cite{BankTransfer}, where two resources must be locked simultaneously, using \CFA monitors with implicit locking and \CC with explicit locking. 1683 1810 A \CFA programmer only has to manage when to acquire mutual exclusion; … … 1699 1826 void transfer( BankAccount & `mutex` my, 1700 1827 BankAccount & `mutex` your, int me2you ) { 1701 1828 // bulk acquire 1702 1829 deposit( my, -me2you ); // debit 1703 1830 deposit( your, me2you ); // credit … … 1729 1856 void transfer( BankAccount & my, 1730 1857 BankAccount & your, int me2you ) { 1731 `scoped_lock lock( my.m, your.m );` 1858 `scoped_lock lock( my.m, your.m );` // bulk acquire 1732 1859 deposit( my, -me2you ); // debit 1733 1860 deposit( your, me2you ); // credit … … 1757 1884 \end{figure} 1758 1885 1759 Users can still force the acquiring order by using @mutex@/\lstinline[morekeywords=nomutex]@nomutex@.1886 Users can still force the acquiring order by using or not using @mutex@. 1760 1887 \begin{cfa} 1761 1888 void foo( M & mutex m1, M & mutex m2 ); $\C{// acquire m1 and m2}$ 1762 void bar( M & mutex m1, M & /* nomutex */ m2 ) { $\C{//acquire m1}$1889 void bar( M & mutex m1, M & m2 ) { $\C{// only acquire m1}$ 1763 1890 ... foo( m1, m2 ); ... $\C{// acquire m2}$ 1764 1891 } 1765 void baz( M & /* nomutex */ m1, M & mutex m2 ) { $\C{//acquire m2}$1892 void baz( M & m1, M & mutex m2 ) { $\C{// only acquire m2}$ 1766 1893 ... foo( m1, m2 ); ... $\C{// acquire m1}$ 1767 1894 } … … 1806 1933 % There are many aspects of scheduling in a concurrency system, all related to resource utilization by waiting threads, \ie which thread gets the resource next. 1807 1934 % Different forms of scheduling include access to processors by threads (see Section~\ref{s:RuntimeStructureCluster}), another is access to a shared resource by a lock or monitor. 1808 This section discusses monitor scheduling for waiting threads eligible for entry, \ie which thread gets the shared resource next. (See Section~\ref{s:RuntimeStructureCluster} for scheduling threads on virtual processors.) 1809 While monitor mutual-exclusion provides safe access to shared data, the monitor data may indicate that a thread accessing it cannot proceed, \eg a bounded buffer may be full/empty so produce/consumer threads must block. 1810 Leaving the monitor and trying again (busy waiting) is impractical for high-level programming. 1811 Monitors eliminate busy waiting by providing synchronization to schedule threads needing access to the shared data, where threads block versus spinning. 1935 This section discusses scheduling for waiting threads eligible for monitor entry, \ie which user thread gets the shared resource next. (See Section~\ref{s:RuntimeStructureCluster} for scheduling kernel threads on virtual processors.) 1936 While monitor mutual-exclusion provides safe access to its shared data, the data may indicate a thread cannot proceed, \eg a bounded buffer may be full/\-empty so produce/consumer threads must block. 1937 Leaving the monitor and retrying (busy waiting) is impractical for high-level programming. 1938 1939 Monitors eliminate busy waiting by providing synchronization within the monitor critical-section to schedule threads needing access to the shared data, where threads block versus spin. 1812 1940 Synchronization is generally achieved with internal~\cite{Hoare74} or external~\cite[\S~2.9.2]{uC++} scheduling. 1813 \newterm{Internal scheduling} is characterized by each thread entering the monitor and making an individual decision about proceeding or blocking, while \newterm{external scheduling} is characterized by an entering thread making a decision about proceeding for itself and on behalf of other threads attempting entry. 1814 Finally, \CFA monitors do not allow calling threads to barge ahead of signalled threads, which simplifies synchronization among threads in the monitor and increases correctness. 1815 If barging is allowed, synchronization between a signaller and signallee is difficult, often requiring additional flags and multiple unblock/block cycles. 1816 In fact, signals-as-hints is completely opposite from that proposed by Hoare in the seminal paper on monitors~\cite[p.~550]{Hoare74}. 1941 \newterm{Internal} (largely) schedules threads located \emph{inside} the monitor and is accomplished using condition variables with signal and wait. 1942 \newterm{External} (largely) schedules threads located \emph{outside} the monitor and is accomplished with the @waitfor@ statement. 1943 Note, internal scheduling has a small amount of external scheduling and vice versus, so the naming denotes where the majority of the block threads reside (inside or outside) for scheduling. 1944 For complex scheduling, the approaches can be combined, so there can be an equal number of threads waiting inside and outside. 1945 1946 \CFA monitors do not allow calling threads to barge ahead of signalled threads (via barging prevention), which simplifies synchronization among threads in the monitor and increases correctness. 1947 A direct consequence of this semantics is that unblocked waiting threads are not required to recheck the waiting condition, \ie waits are not in a starvation-prone busy-loop as required by the signals-as-hints style with barging. 1948 Preventing barging comes directly from Hoare's semantics in the seminal paper on monitors~\cite[p.~550]{Hoare74}. 1817 1949 % \begin{cquote} 1818 1950 % However, we decree that a signal operation be followed immediately by resumption of a waiting program, without possibility of an intervening procedure call from yet a third program. 1819 1951 % It is only in this way that a waiting program has an absolute guarantee that it can acquire the resource just released by the signalling program without any danger that a third program will interpose a monitor entry and seize the resource instead.~\cite[p.~550]{Hoare74} 1820 1952 % \end{cquote} 1821 Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implicit form of self barging. 1822 Hence, a \CFA @wait@ statement is not enclosed in a @while@ loop retesting a blocking predicate, which can cause thread starvation due to barging. 1823 1824 Figure~\ref{f:MonitorScheduling} shows general internal/external scheduling (for the bounded-buffer example in Figure~\ref{f:InternalExternalScheduling}). 1825 External calling threads block on the calling queue, if the monitor is occupied, otherwise they enter in FIFO order. 1826 Internal threads block on condition queues via @wait@ and reenter from the condition in FIFO order. 1827 Alternatively, internal threads block on urgent from the @signal_block@ or @waitfor@, and reenter implicitly when the monitor becomes empty, \ie, the thread in the monitor exits or waits. 1828 1829 There are three signalling mechanisms to unblock waiting threads to enter the monitor. 1830 Note, signalling cannot have the signaller and signalled thread in the monitor simultaneously because of the mutual exclusion, so either the signaller or signallee can proceed. 1831 For internal scheduling, threads are unblocked from condition queues using @signal@, where the signallee is moved to urgent and the signaller continues (solid line). 1832 Multiple signals move multiple signallees to urgent until the condition is empty. 1833 When the signaller exits or waits, a thread blocked on urgent is processed before calling threads to prevent barging. 1953 Furthermore, \CFA concurrency has no spurious wakeup~\cite[\S~9]{Buhr05a}, which eliminates an implicit self barging. 1954 1955 Monitor mutual-exclusion means signalling cannot have the signaller and signalled thread in the monitor simultaneously, so only the signaller or signallee can proceed. 1956 Figure~\ref{f:MonitorScheduling} shows internal/external scheduling for the bounded-buffer examples in Figure~\ref{f:GenericBoundedBuffer}. 1957 For internal scheduling in Figure~\ref{f:BBInt}, the @signal@ moves the signallee (front thread of the specified condition queue) to urgent and the signaller continues (solid line). 1958 Multiple signals move multiple signallees to urgent until the condition queue is empty. 1959 When the signaller exits or waits, a thread is implicitly unblocked from urgent (if available) before unblocking a calling thread to prevent barging. 1834 1960 (Java conceptually moves the signalled thread to the calling queue, and hence, allows barging.) 1835 The alternative unblock is in the opposite order using @signal_block@, where the signaller is moved to urgent and the signallee continues (dashed line), and is implicitly unblocked from urgent when the signallee exits or waits. 1836 1837 For external scheduling, the condition queues are not used; 1838 instead threads are unblocked directly from the calling queue using @waitfor@ based on function names requesting mutual exclusion. 1839 (The linear search through the calling queue to locate a particular call can be reduced to $O(1)$.) 1840 The @waitfor@ has the same semantics as @signal_block@, where the signalled thread executes before the signallee, which waits on urgent. 1841 Executing multiple @waitfor@s from different signalled functions causes the calling threads to move to urgent. 1842 External scheduling requires urgent to be a stack, because the signaller expects to execute immediately after the specified monitor call has exited or waited. 1843 Internal scheduling behaves the same for an urgent stack or queue, except for multiple signalling, where the threads unblock from urgent in reverse order from signalling. 1844 If the restart order is important, multiple signalling by a signal thread can be transformed into daisy-chain signalling among threads, where each thread signals the next thread. 1845 We tried both a stack for @waitfor@ and queue for signalling, but that resulted in complex semantics about which thread enters next. 1846 Hence, \CFA uses a single urgent stack to correctly handle @waitfor@ and adequately support both forms of signalling. 1961 Signal is used when the signaller is providing the cooperation needed by the signallee (\eg creating an empty slot in a buffer for a producer) and the signaller immediately exits the monitor to run concurrently (consume the buffer element) and passes control of the monitor to the signalled thread, which can immediately take advantage of the state change. 1962 Specifically, the @wait@ function atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the function's parameter list. 1963 Signalling is unconditional because signalling an empty condition queue does nothing. 1964 It is common to declare condition queues as monitor fields to prevent shared access, hence no locking is required for access as the queues are protected by the monitor lock. 1965 In \CFA, a condition queue can be created/stored independently. 1847 1966 1848 1967 \begin{figure} … … 1862 1981 \end{figure} 1863 1982 1864 Figure~\ref{f:BBInt} shows a \CFA generic bounded-buffer with internal scheduling, where producers/consumers enter the monitor, detect the buffer is full/empty, and block on an appropriate condition variable, @full@/@empty@.1865 The @wait@ function atomically blocks the calling thread and implicitly releases the monitor lock(s) for all monitors in the function's parameter list.1866 The appropriate condition variable is signalled to unblock an opposite kind of thread after an element is inserted/removed from the buffer.1867 Signalling is unconditional, because signalling an empty condition variable does nothing.1868 It is common to declare condition variables as monitor fields to prevent shared access, hence no locking is required for access as the conditions are protected by the monitor lock.1869 In \CFA, a condition variable can be created/stored independently.1870 % To still prevent expensive locking on access, a condition variable is tied to a \emph{group} of monitors on first use, called \newterm{branding}, resulting in a low-cost boolean test to detect sharing from other monitors.1871 1872 % Signalling semantics cannot have the signaller and signalled thread in the monitor simultaneously, which means:1873 % \begin{enumerate}1874 % \item1875 % The signalling thread returns immediately and the signalled thread continues.1876 % \item1877 % The signalling thread continues and the signalled thread is marked for urgent unblocking at the next scheduling point (exit/wait).1878 % \item1879 % The signalling thread blocks but is marked for urgent unblocking at the next scheduling point and the signalled thread continues.1880 % \end{enumerate}1881 % The first approach is too restrictive, as it precludes solving a reasonable class of problems, \eg dating service (see Figure~\ref{f:DatingService}).1882 % \CFA supports the next two semantics as both are useful.1883 1884 1983 \begin{figure} 1885 1984 \centering … … 1893 1992 T elements[10]; 1894 1993 }; 1895 void ?{}( Buffer(T) & buf fer ) with(buffer) {1994 void ?{}( Buffer(T) & buf ) with(buf) { 1896 1995 front = back = count = 0; 1897 1996 } 1898 void insert( Buffer(T) & mutex buffer, T elem ) 1899 with(buffer){1900 if ( count == 10 ) `wait( empty )`; 1901 // insert el em into buffer1997 1998 void insert(Buffer(T) & mutex buf, T elm) with(buf){ 1999 if ( count == 10 ) `wait( empty )`; // full ? 2000 // insert elm into buf 1902 2001 `signal( full )`; 1903 2002 } 1904 T remove( Buffer(T) & mutex buf fer ) with(buffer) {1905 if ( count == 0 ) `wait( full )`; 1906 // remove el em from buffer2003 T remove( Buffer(T) & mutex buf ) with(buf) { 2004 if ( count == 0 ) `wait( full )`; // empty ? 2005 // remove elm from buf 1907 2006 `signal( empty )`; 1908 return el em;2007 return elm; 1909 2008 } 1910 2009 } 1911 2010 \end{cfa} 1912 2011 \end{lrbox} 1913 1914 % \newbox\myboxB1915 % \begin{lrbox}{\myboxB}1916 % \begin{cfa}[aboveskip=0pt,belowskip=0pt]1917 % forall( otype T ) { // distribute forall1918 % monitor Buffer {1919 %1920 % int front, back, count;1921 % T elements[10];1922 % };1923 % void ?{}( Buffer(T) & buffer ) with(buffer) {1924 % [front, back, count] = 0;1925 % }1926 % T remove( Buffer(T) & mutex buffer ); // forward1927 % void insert( Buffer(T) & mutex buffer, T elem )1928 % with(buffer) {1929 % if ( count == 10 ) `waitfor( remove, buffer )`;1930 % // insert elem into buffer1931 %1932 % }1933 % T remove( Buffer(T) & mutex buffer ) with(buffer) {1934 % if ( count == 0 ) `waitfor( insert, buffer )`;1935 % // remove elem from buffer1936 %1937 % return elem;1938 % }1939 % }1940 % \end{cfa}1941 % \end{lrbox}1942 2012 1943 2013 \newbox\myboxB 1944 2014 \begin{lrbox}{\myboxB} 1945 2015 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 2016 forall( otype T ) { // distribute forall 2017 monitor Buffer { 2018 2019 int front, back, count; 2020 T elements[10]; 2021 }; 2022 void ?{}( Buffer(T) & buf ) with(buf) { 2023 front = back = count = 0; 2024 } 2025 T remove( Buffer(T) & mutex buf ); // forward 2026 void insert(Buffer(T) & mutex buf, T elm) with(buf){ 2027 if ( count == 10 ) `waitfor( remove : buf )`; 2028 // insert elm into buf 2029 2030 } 2031 T remove( Buffer(T) & mutex buf ) with(buf) { 2032 if ( count == 0 ) `waitfor( insert : buf )`; 2033 // remove elm from buf 2034 2035 return elm; 2036 } 2037 } 2038 \end{cfa} 2039 \end{lrbox} 2040 2041 \subfloat[Internal scheduling]{\label{f:BBInt}\usebox\myboxA} 2042 \hspace{1pt} 2043 \vrule 2044 \hspace{3pt} 2045 \subfloat[External scheduling]{\label{f:BBExt}\usebox\myboxB} 2046 2047 \caption{Generic bounded buffer} 2048 \label{f:GenericBoundedBuffer} 2049 \end{figure} 2050 2051 The @signal_block@ provides the opposite unblocking order, where the signaller is moved to urgent and the signallee continues and a thread is implicitly unblocked from urgent when the signallee exits or waits (dashed line). 2052 Signal block is used when the signallee is providing the cooperation needed by the signaller (\eg if the buffer is removed and a producer hands off an item to a consumer, as in Figure~\ref{f:DatingSignalBlock}) so the signaller must wait until the signallee unblocks, provides the cooperation, exits the monitor to run concurrently, and passes control of the monitor to the signaller, which can immediately take advantage of the state change. 2053 Using @signal@ or @signal_block@ can be a dynamic decision based on whether the thread providing the cooperation arrives before or after the thread needing the cooperation. 2054 2055 External scheduling in Figure~\ref{f:BBExt} simplifies internal scheduling by eliminating condition queues and @signal@/@wait@ (cases where it cannot are discussed shortly), and has existed in the programming language Ada for almost 40 years with variants in other languages~\cite{SR,ConcurrentC++,uC++}. 2056 While prior languages use external scheduling solely for thread interaction, \CFA generalizes it to both monitors and threads. 2057 External scheduling allows waiting for events from other threads while restricting unrelated events, that would otherwise have to wait on condition queues in the monitor. 2058 Scheduling is controlled by the @waitfor@ statement, which atomically blocks the calling thread, releases the monitor lock, and restricts the function calls that can next acquire mutual exclusion. 2059 Specifically, a thread calling the monitor is unblocked directly from the calling queue based on function names that can fulfill the cooperation required by the signaller. 2060 (The linear search through the calling queue to locate a particular call can be reduced to $O(1)$.) 2061 Hence, the @waitfor@ has the same semantics as @signal_block@, where the signallee thread from the calling queue executes before the signaller, which waits on urgent. 2062 Now when a producer/consumer detects a full/empty buffer, the necessary cooperation for continuation is specified by indicating the next function call that can occur. 2063 For example, a producer detecting a full buffer must have cooperation from a consumer to remove an item so function @remove@ is accepted, which prevents producers from entering the monitor, and after a consumer calls @remove@, the producer waiting on urgent is \emph{implicitly} unblocked because it can now continue its insert operation. 2064 Hence, this mechanism is done in terms of control flow, next call, versus in terms of data, channels, as in Go/Rust @select@. 2065 While both mechanisms have strengths and weaknesses, \CFA uses the control-flow mechanism to be consistent with other language features. 2066 2067 Figure~\ref{f:ReadersWriterLock} shows internal/external scheduling for a readers/writer lock with no barging and threads are serviced in FIFO order to eliminate staleness/freshness among the reader/writer threads. 2068 For internal scheduling in Figure~\ref{f:RWInt}, the readers and writers wait on the same condition queue in FIFO order, making it impossible to tell if a waiting thread is a reader or writer. 2069 To clawback the kind of thread, a \CFA condition can store user data in the node for a blocking thread at the @wait@, \ie whether the thread is a @READER@ or @WRITER@. 2070 An unblocked reader thread checks if the thread at the front of the queue is a reader and unblock it, \ie the readers daisy-chain signal the next group of readers demarcated by the next writer or end of the queue. 2071 For external scheduling in Figure~\ref{f:RWExt}, a waiting reader checks if a writer is using the resource, and if so, restricts further calls until the writer exits by calling @EndWrite@. 2072 The writer does a similar action for each reader or writer using the resource. 2073 Note, no new calls to @StartRead@/@StartWrite@ may occur when waiting for the call to @EndRead@/@EndWrite@. 2074 2075 \begin{figure} 2076 \centering 2077 \newbox\myboxA 2078 \begin{lrbox}{\myboxA} 2079 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 2080 enum RW { READER, WRITER }; 1946 2081 monitor ReadersWriter { 1947 int rcnt, wcnt; // readers/writer using resource 2082 int rcnt, wcnt; // readers/writer using resource 2083 `condition RWers;` 1948 2084 }; 1949 2085 void ?{}( ReadersWriter & rw ) with(rw) { … … 1952 2088 void EndRead( ReadersWriter & mutex rw ) with(rw) { 1953 2089 rcnt -= 1; 2090 if ( rcnt == 0 ) `signal( RWers )`; 1954 2091 } 1955 2092 void EndWrite( ReadersWriter & mutex rw ) with(rw) { 1956 2093 wcnt = 0; 2094 `signal( RWers );` 1957 2095 } 1958 2096 void StartRead( ReadersWriter & mutex rw ) with(rw) { 1959 if ( wcnt > 0 ) `waitfor( EndWrite, rw );` 2097 if ( wcnt !=0 || ! empty( RWers ) ) 2098 `wait( RWers, READER )`; 1960 2099 rcnt += 1; 2100 if ( ! empty(RWers) && `front(RWers) == READER` ) 2101 `signal( RWers )`; // daisy-chain signalling 1961 2102 } 1962 2103 void StartWrite( ReadersWriter & mutex rw ) with(rw) { 1963 if ( wcnt > 0 ) `waitfor( EndWrite, rw );`1964 else while ( rcnt > 0 ) `waitfor( EndRead, rw );` 2104 if ( wcnt != 0 || rcnt != 0 ) `wait( RWers, WRITER )`; 2105 1965 2106 wcnt = 1; 1966 2107 } 1967 1968 2108 \end{cfa} 1969 2109 \end{lrbox} 1970 2110 1971 \subfloat[Generic bounded buffer, internal scheduling]{\label{f:BBInt}\usebox\myboxA} 1972 \hspace{3pt} 2111 \newbox\myboxB 2112 \begin{lrbox}{\myboxB} 2113 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 2114 2115 monitor ReadersWriter { 2116 int rcnt, wcnt; // readers/writer using resource 2117 2118 }; 2119 void ?{}( ReadersWriter & rw ) with(rw) { 2120 rcnt = wcnt = 0; 2121 } 2122 void EndRead( ReadersWriter & mutex rw ) with(rw) { 2123 rcnt -= 1; 2124 2125 } 2126 void EndWrite( ReadersWriter & mutex rw ) with(rw) { 2127 wcnt = 0; 2128 2129 } 2130 void StartRead( ReadersWriter & mutex rw ) with(rw) { 2131 if ( wcnt > 0 ) `waitfor( EndWrite : rw );` 2132 2133 rcnt += 1; 2134 2135 2136 } 2137 void StartWrite( ReadersWriter & mutex rw ) with(rw) { 2138 if ( wcnt > 0 ) `waitfor( EndWrite : rw );` 2139 else while ( rcnt > 0 ) `waitfor( EndRead : rw );` 2140 wcnt = 1; 2141 } 2142 \end{cfa} 2143 \end{lrbox} 2144 2145 \subfloat[Internal scheduling]{\label{f:RWInt}\usebox\myboxA} 2146 \hspace{1pt} 1973 2147 \vrule 1974 2148 \hspace{3pt} 1975 \subfloat[ Readers / writer lock, external scheduling]{\label{f:RWExt}\usebox\myboxB}1976 1977 \caption{ Internal / external scheduling}1978 \label{f: InternalExternalScheduling}2149 \subfloat[External scheduling]{\label{f:RWExt}\usebox\myboxB} 2150 2151 \caption{Readers / writer lock} 2152 \label{f:ReadersWriterLock} 1979 2153 \end{figure} 1980 2154 1981 Figure~\ref{f:BBInt} can be transformed into external scheduling by removing the condition variables and signals/waits, and adding the following lines at the locations of the current @wait@s in @insert@/@remove@, respectively. 1982 \begin{cfa}[aboveskip=2pt,belowskip=1pt] 1983 if ( count == 10 ) `waitfor( remove, buffer )`; | if ( count == 0 ) `waitfor( insert, buffer )`; 1984 \end{cfa} 1985 Here, the producers/consumers detects a full/\-empty buffer and prevents more producers/consumers from entering the monitor until there is a free/empty slot in the buffer. 1986 External scheduling is controlled by the @waitfor@ statement, which atomically blocks the calling thread, releases the monitor lock, and restricts the function calls that can next acquire mutual exclusion. 1987 If the buffer is full, only calls to @remove@ can acquire the buffer, and if the buffer is empty, only calls to @insert@ can acquire the buffer. 1988 Threads calling excluded functions block outside of (external to) the monitor on the calling queue, versus blocking on condition queues inside of (internal to) the monitor. 1989 Figure~\ref{f:RWExt} shows a readers/writer lock written using external scheduling, where a waiting reader detects a writer using the resource and restricts further calls until the writer exits by calling @EndWrite@. 1990 The writer does a similar action for each reader or writer using the resource. 1991 Note, no new calls to @StarRead@/@StartWrite@ may occur when waiting for the call to @EndRead@/@EndWrite@. 1992 External scheduling allows waiting for events from other threads while restricting unrelated events, that would otherwise have to wait on conditions in the monitor. 1993 The mechnaism can be done in terms of control flow, \eg Ada @accept@ or \uC @_Accept@, or in terms of data, \eg Go @select@ on channels. 1994 While both mechanisms have strengths and weaknesses, this project uses the control-flow mechanism to be consistent with other language features. 1995 % Two challenges specific to \CFA for external scheduling are loose object-definitions (see Section~\ref{s:LooseObjectDefinitions}) and multiple-monitor functions (see Section~\ref{s:Multi-MonitorScheduling}). 1996 1997 Figure~\ref{f:DatingService} shows a dating service demonstrating non-blocking and blocking signalling. 1998 The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers. 1999 A thread blocks until an appropriate partner arrives. 2000 The complexity is exchanging phone numbers in the monitor because of the mutual-exclusion property. 2001 For signal scheduling, the @exchange@ condition is necessary to block the thread finding the match, while the matcher unblocks to take the opposite number, post its phone number, and unblock the partner. 2002 For signal-block scheduling, the implicit urgent-queue replaces the explict @exchange@-condition and @signal_block@ puts the finding thread on the urgent condition and unblocks the matcher. 2003 The dating service is an example of a monitor that cannot be written using external scheduling because it requires knowledge of calling parameters to make scheduling decisions, and parameters of waiting threads are unavailable; 2004 as well, an arriving thread may not find a partner and must wait, which requires a condition variable, and condition variables imply internal scheduling. 2005 Furthermore, barging corrupts the dating service during an exchange because a barger may also match and change the phone numbers, invalidating the previous exchange phone number. 2006 Putting loops around the @wait@s does not correct the problem; 2007 the simple solution must be restructured to account for barging. 2155 Finally, external scheduling requires urgent to be a stack, because the signaller expects to execute immediately after the specified monitor call has exited or waited. 2156 Internal schedulling performing multiple signalling results in unblocking from urgent in the reverse order from signalling. 2157 It is rare for the unblocking order to be important as an unblocked thread can be time-sliced immediately after leaving the monitor. 2158 If the unblocking order is important, multiple signalling can be restructured into daisy-chain signalling, where each thread signals the next thread. 2159 Hence, \CFA uses a single urgent stack to correctly handle @waitfor@ and adequately support both forms of signalling. 2160 (Advanced @waitfor@ features are discussed in Section~\ref{s:ExtendedWaitfor}.) 2008 2161 2009 2162 \begin{figure} … … 2019 2172 }; 2020 2173 int girl( DS & mutex ds, int phNo, int ccode ) { 2021 if ( is_empty( Boys[ccode] ) ) {2174 if ( empty( Boys[ccode] ) ) { 2022 2175 wait( Girls[ccode] ); 2023 2176 GirlPhNo = phNo; … … 2046 2199 }; 2047 2200 int girl( DS & mutex ds, int phNo, int ccode ) { 2048 if ( is_empty( Boys[ccode] ) ) { // no compatible2201 if ( empty( Boys[ccode] ) ) { // no compatible 2049 2202 wait( Girls[ccode] ); // wait for boy 2050 2203 GirlPhNo = phNo; // make phone number available … … 2066 2219 \qquad 2067 2220 \subfloat[\lstinline@signal_block@]{\label{f:DatingSignalBlock}\usebox\myboxB} 2068 \caption{Dating service }2069 \label{f:DatingService }2221 \caption{Dating service Monitor} 2222 \label{f:DatingServiceMonitor} 2070 2223 \end{figure} 2071 2224 2072 In summation, for internal scheduling, non-blocking signalling (as in the producer/consumer example) is used when the signaller is providing the cooperation for a waiting thread; 2073 the signaller enters the monitor and changes state, detects a waiting threads that can use the state, performs a non-blocking signal on the condition queue for the waiting thread, and exits the monitor to run concurrently. 2074 The waiter unblocks next from the urgent queue, uses/takes the state, and exits the monitor. 2075 Blocking signal is the reverse, where the waiter is providing the cooperation for the signalling thread; 2076 the signaller enters the monitor, detects a waiting thread providing the necessary state, performs a blocking signal to place it on the urgent queue and unblock the waiter. 2077 The waiter changes state and exits the monitor, and the signaller unblocks next from the urgent queue to use/take the state. 2225 Figure~\ref{f:DatingServiceMonitor} shows a dating service demonstrating non-blocking and blocking signalling. 2226 The dating service matches girl and boy threads with matching compatibility codes so they can exchange phone numbers. 2227 A thread blocks until an appropriate partner arrives. 2228 The complexity is exchanging phone numbers in the monitor because of the mutual-exclusion property. 2229 For signal scheduling, the @exchange@ condition is necessary to block the thread finding the match, while the matcher unblocks to take the opposite number, post its phone number, and unblock the partner. 2230 For signal-block scheduling, the implicit urgent-queue replaces the explicit @exchange@-condition and @signal_block@ puts the finding thread on the urgent stack and unblocks the matcher. 2231 2232 The dating service is an important example of a monitor that cannot be written using external scheduling. 2233 First, because scheduling requires knowledge of calling parameters to make matching decisions, and parameters of calling threads are unavailable within the monitor. 2234 For example, a girl thread within the monitor cannot examine the @ccode@ of boy threads waiting on the calling queue to determine if there is a matching partner. 2235 Second, because a scheduling decision may be delayed when there is no immediate match, which requires a condition queue for waiting, and condition queues imply internal scheduling. 2236 For example, if a girl thread could determine there is no calling boy with the same @ccode@, it must wait until a matching boy arrives. 2237 Finally, barging corrupts the dating service during an exchange because a barger may also match and change the phone numbers, invalidating the previous exchange phone number. 2238 This situation shows rechecking the waiting condition and waiting again (signals-as-hints) fails, requiring significant restructured to account for barging. 2078 2239 2079 2240 Both internal and external scheduling extend to multiple monitors in a natural way. 2080 2241 \begin{cquote} 2081 \begin{tabular}{@{}l@{\hspace{ 3\parindentlnth}}l@{}}2242 \begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}} 2082 2243 \begin{cfa} 2083 2244 monitor M { `condition e`; ... }; … … 2090 2251 & 2091 2252 \begin{cfa} 2092 void rtn$\(_1\)$( M & mutex m1, M & mutex m2 ); 2253 void rtn$\(_1\)$( M & mutex m1, M & mutex m2 ); // overload rtn 2093 2254 void rtn$\(_2\)$( M & mutex m1 ); 2094 2255 void bar( M & mutex m1, M & mutex m2 ) { 2095 ... waitfor( `rtn` ); ... // $\LstCommentStyle{waitfor( rtn\(_1\),m1, m2 )}$2096 ... waitfor( `rtn , m1` ); ... // $\LstCommentStyle{waitfor( rtn\(_2\), m1 )}$2256 ... waitfor( `rtn`${\color{red}\(_1\)}$ ); ... // $\LstCommentStyle{waitfor( rtn\(_1\) : m1, m2 )}$ 2257 ... waitfor( `rtn${\color{red}\(_2\)}$ : m1` ); ... 2097 2258 } 2098 2259 \end{cfa} … … 2101 2262 For @wait( e )@, the default semantics is to atomically block the signaller and release all acquired mutex parameters, \ie @wait( e, m1, m2 )@. 2102 2263 To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @wait( e, m1 )@. 2103 Wait cannot statically verif iesthe released monitors are the acquired mutex-parameters without disallowing separately compiled helper functions calling @wait@.2104 While \CC supports bulk locking, @wait@ only accepts a single lock for a condition variable, so bulk locking with condition variables is asymmetric.2264 Wait cannot statically verify the released monitors are the acquired mutex-parameters without disallowing separately compiled helper functions calling @wait@. 2265 While \CC supports bulk locking, @wait@ only accepts a single lock for a condition queue, so bulk locking with condition queues is asymmetric. 2105 2266 Finally, a signaller, 2106 2267 \begin{cfa} … … 2111 2272 must have acquired at least the same locks as the waiting thread signalled from a condition queue to allow the locks to be passed, and hence, prevent barging. 2112 2273 2113 Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex parameters, \ie @waitfor( rtn ,m1, m2 )@.2114 To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn ,m1 )@.2274 Similarly, for @waitfor( rtn )@, the default semantics is to atomically block the acceptor and release all acquired mutex parameters, \ie @waitfor( rtn : m1, m2 )@. 2275 To override the implicit multi-monitor wait, specific mutex parameter(s) can be specified, \eg @waitfor( rtn : m1 )@. 2115 2276 @waitfor@ does statically verify the monitor types passed are the same as the acquired mutex-parameters of the given function or function pointer, hence the function (pointer) prototype must be accessible. 2116 2277 % When an overloaded function appears in an @waitfor@ statement, calls to any function with that name are accepted. … … 2120 2281 void rtn( M & mutex m ); 2121 2282 `int` rtn( M & mutex m ); 2122 waitfor( (`int` (*)( M & mutex ))rtn, m ); 2123 \end{cfa} 2124 2125 The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock. 2283 waitfor( (`int` (*)( M & mutex ))rtn : m ); 2284 \end{cfa} 2285 2286 The ability to release a subset of acquired monitors can result in a \newterm{nested monitor}~\cite{Lister77} deadlock (see Section~\ref{s:MutexAcquisition}). 2287 \newpage 2126 2288 \begin{cfa} 2127 2289 void foo( M & mutex m1, M & mutex m2 ) { 2128 ... wait( `e, m1` ); ... $\C{// release m1, keeping m2 acquired )}$2129 void bar( M & mutex m1, M & mutex m2 ) { $\C{// must acquire m1 and m2 )}$2290 ... wait( `e, m1` ); ... $\C{// release m1, keeping m2 acquired}$ 2291 void bar( M & mutex m1, M & mutex m2 ) { $\C{// must acquire m1 and m2}$ 2130 2292 ... signal( `e` ); ... 2131 2293 \end{cfa} 2132 2294 The @wait@ only releases @m1@ so the signalling thread cannot acquire @m1@ and @m2@ to enter @bar@ and @signal@ the condition. 2133 While deadlock can occur with multiple/nesting acquisition, this is a consequence of locks, and by extension monitors, not being perfectly composable. 2134 2295 While deadlock can occur with multiple/nesting acquisition, this is a consequence of locks, and by extension monitor locking is not perfectly composable. 2135 2296 2136 2297 2137 2298 \subsection{\texorpdfstring{Extended \protect\lstinline@waitfor@}{Extended waitfor}} 2299 \label{s:ExtendedWaitfor} 2138 2300 2139 2301 Figure~\ref{f:ExtendedWaitfor} shows the extended form of the @waitfor@ statement to conditionally accept one of a group of mutex functions, with an optional statement to be performed \emph{after} the mutex function finishes. … … 2146 2308 Hence, the terminating @else@ clause allows a conditional attempt to accept a call without blocking. 2147 2309 If both @timeout@ and @else@ clause are present, the @else@ must be conditional, or the @timeout@ is never triggered. 2148 There is also a traditional future wait queue (not shown) (\eg Microsoft (@WaitForMultipleObjects@)), to wait for a specified number of future elements in the queue. 2310 There is also a traditional future wait queue (not shown) (\eg Microsoft @WaitForMultipleObjects@), to wait for a specified number of future elements in the queue. 2311 Finally, there is a shorthand for specifying multiple functions using the same set of monitors: @waitfor( f, g, h : m1, m2, m3 )@. 2149 2312 2150 2313 \begin{figure} … … 2173 2336 The right example accepts either @mem1@ or @mem2@ if @C1@ and @C2@ are true. 2174 2337 2175 An interesting use of @waitfor@ is accepting the @mutex@ destructor to know when an object is deallocated, \eg assume the bounded buffer is restruct red from a monitor to a thread with the following @main@.2338 An interesting use of @waitfor@ is accepting the @mutex@ destructor to know when an object is deallocated, \eg assume the bounded buffer is restructured from a monitor to a thread with the following @main@. 2176 2339 \begin{cfa} 2177 2340 void main( Buffer(T) & buffer ) with(buffer) { 2178 2341 for () { 2179 `waitfor( ^?{} ,buffer )` break;2180 or when ( count != 20 ) waitfor( insert ,buffer ) { ... }2181 or when ( count != 0 ) waitfor( remove ,buffer ) { ... }2342 `waitfor( ^?{} : buffer )` break; 2343 or when ( count != 20 ) waitfor( insert : buffer ) { ... } 2344 or when ( count != 0 ) waitfor( remove : buffer ) { ... } 2182 2345 } 2183 2346 // clean up … … 2271 2434 To support this efficient semantics (and prevent barging), the implementation maintains a list of monitors acquired for each blocked thread. 2272 2435 When a signaller exits or waits in a monitor function/statement, the front waiter on urgent is unblocked if all its monitors are released. 2273 Implementing a fast subset check for the necessary released monitors is important .2436 Implementing a fast subset check for the necessary released monitors is important and discussed in the following sections. 2274 2437 % The benefit is encapsulating complexity into only two actions: passing monitors to the next owner when they should be released and conditionally waking threads if all conditions are met. 2275 2438 2276 2439 2277 \subsection{Loose Object Definitions} 2278 \label{s:LooseObjectDefinitions} 2279 2280 In an object-oriented programming language, a class includes an exhaustive list of operations. 2281 A new class can add members via static inheritance but the subclass still has an exhaustive list of operations. 2282 (Dynamic member adding, \eg JavaScript~\cite{JavaScript}, is not considered.) 2283 In the object-oriented scenario, the type and all its operators are always present at compilation (even separate compilation), so it is possible to number the operations in a bit mask and use an $O(1)$ compare with a similar bit mask created for the operations specified in a @waitfor@. 2284 2285 However, in \CFA, monitor functions can be statically added/removed in translation units, making a fast subset check difficult. 2286 \begin{cfa} 2287 monitor M { ... }; // common type, included in .h file 2288 translation unit 1 2289 void `f`( M & mutex m ); 2290 void g( M & mutex m ) { waitfor( `f`, m ); } 2291 translation unit 2 2292 void `f`( M & mutex m ); $\C{// replacing f and g for type M in this translation unit}$ 2293 void `g`( M & mutex m ); 2294 void h( M & mutex m ) { waitfor( `f`, m ) or waitfor( `g`, m ); } $\C{// extending type M in this translation unit}$ 2295 \end{cfa} 2296 The @waitfor@ statements in each translation unit cannot form a unique bit-mask because the monitor type does not carry that information. 2440 \subsection{\texorpdfstring{\protect\lstinline@waitfor@ Implementation}{waitfor Implementation}} 2441 \label{s:waitforImplementation} 2442 2443 In a statically-typed object-oriented programming language, a class has an exhaustive list of members, even when members are added via static inheritance (see Figure~\ref{f:uCinheritance}). 2444 Knowing all members at compilation (even separate compilation) allows uniquely numbered them so the accept-statement implementation can use a fast/compact bit mask with $O(1)$ compare. 2445 2446 \begin{figure} 2447 \centering 2448 \begin{lrbox}{\myboxA} 2449 \begin{uC++}[aboveskip=0pt,belowskip=0pt] 2450 $\emph{translation unit 1}$ 2451 _Monitor B { // common type in .h file 2452 _Mutex virtual void `f`( ... ); 2453 _Mutex virtual void `g`( ... ); 2454 _Mutex virtual void w1( ... ) { ... _Accept(`f`, `g`); ... } 2455 }; 2456 $\emph{translation unit 2}$ 2457 // include B 2458 _Monitor D : public B { // inherit 2459 _Mutex void `h`( ... ); // add 2460 _Mutex void w2( ... ) { ... _Accept(`f`, `h`); ... } 2461 }; 2462 \end{uC++} 2463 \end{lrbox} 2464 2465 \begin{lrbox}{\myboxB} 2466 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 2467 $\emph{translation unit 1}$ 2468 monitor M { ... }; // common type in .h file 2469 void `f`( M & mutex m, ... ); 2470 void `g`( M & mutex m, ... ); 2471 void w1( M & mutex m, ... ) { ... waitfor(`f`, `g` : m); ... } 2472 2473 $\emph{translation unit 2}$ 2474 // include M 2475 extern void `f`( M & mutex m, ... ); // import f but not g 2476 void `h`( M & mutex m ); // add 2477 void w2( M & mutex m, ... ) { ... waitfor(`f`, `h` : m); ... } 2478 2479 \end{cfa} 2480 \end{lrbox} 2481 2482 \subfloat[\uC]{\label{f:uCinheritance}\usebox\myboxA} 2483 \hspace{3pt} 2484 \vrule 2485 \hspace{3pt} 2486 \subfloat[\CFA]{\label{f:CFinheritance}\usebox\myboxB} 2487 \caption{Member / Function visibility} 2488 \label{f:MemberFunctionVisibility} 2489 \end{figure} 2490 2491 However, the @waitfor@ statement in translation unit 2 (see Figure~\ref{f:CFinheritance}) cannot see function @g@ in translation unit 1 precluding a unique numbering for a bit-mask because the monitor type only carries the protected shared-data. 2492 (A possible way to construct a dense mapping is at link or load-time.) 2297 2493 Hence, function pointers are used to identify the functions listed in the @waitfor@ statement, stored in a variable-sized array. 2298 Then, the same implementation approach used for the urgent stack is used for the calling queue. 2299 Each caller has a list of monitors acquired, and the @waitfor@ statement performs a (usually short) linear search matching functions in the @waitfor@ list with called functions, and then verifying the associated mutex locks can be transfers. 2300 (A possible way to construct a dense mapping is at link or load-time.) 2494 Then, the same implementation approach used for the urgent stack (see Section~\ref{s:Scheduling}) is used for the calling queue. 2495 Each caller has a list of monitors acquired, and the @waitfor@ statement performs a (short) linear search matching functions in the @waitfor@ list with called functions, and then verifying the associated mutex locks can be transfers. 2301 2496 2302 2497 … … 2313 2508 The solution is for the programmer to disambiguate: 2314 2509 \begin{cfa} 2315 waitfor( f ,`m2` ); $\C{// wait for call to f with argument m2}$2510 waitfor( f : `m2` ); $\C{// wait for call to f with argument m2}$ 2316 2511 \end{cfa} 2317 2512 Both locks are acquired by function @g@, so when function @f@ is called, the lock for monitor @m2@ is passed from @g@ to @f@, while @g@ still holds lock @m1@. … … 2320 2515 monitor M { ... }; 2321 2516 void f( M & mutex m1, M & mutex m2 ); 2322 void g( M & mutex m1, M & mutex m2 ) { waitfor( f ,`m1, m2` ); $\C{// wait for call to f with arguments m1 and m2}$2517 void g( M & mutex m1, M & mutex m2 ) { waitfor( f : `m1, m2` ); $\C{// wait for call to f with arguments m1 and m2}$ 2323 2518 \end{cfa} 2324 2519 Again, the set of monitors passed to the @waitfor@ statement must be entirely contained in the set of monitors already acquired by the accepting function. 2325 Also, the order of the monitors in a @waitfor@ statement is unimportant.2326 2327 Figure~\ref{f:UnmatchedMutexSets} shows an example where, for internal and external scheduling with multiple monitors, a signalling or accepting thread must match exactly, \ie partial matching results in waiting.2328 For both examples, the set of monitors is disjoint so unblocking is impossible.2520 % Also, the order of the monitors in a @waitfor@ statement must match the order of the mutex parameters. 2521 2522 Figure~\ref{f:UnmatchedMutexSets} shows internal and external scheduling with multiple monitors that must match exactly with a signalling or accepting thread, \ie partial matching results in waiting. 2523 In both cases, the set of monitors is disjoint so unblocking is impossible. 2329 2524 2330 2525 \begin{figure} … … 2355 2550 } 2356 2551 void g( M1 & mutex m1, M2 & mutex m2 ) { 2357 waitfor( f ,m1, m2 );2552 waitfor( f : m1, m2 ); 2358 2553 } 2359 2554 g( `m11`, m2 ); // block on accept … … 2370 2565 \end{figure} 2371 2566 2372 2373 \subsection{\texorpdfstring{\protect\lstinline@mutex@ Threads}{mutex Threads}}2374 2375 Threads in \CFA can also be monitors to allow \emph{direct communication} among threads, \ie threads can have mutex functions that are called by other threads.2376 Hence, all monitor features are available when using threads.2377 Figure~\ref{f:DirectCommunication} shows a comparison of direct call communication in \CFA with direct channel communication in Go.2378 (Ada provides a similar mechanism to the \CFA direct communication.)2379 The program main in both programs communicates directly with the other thread versus indirect communication where two threads interact through a passive monitor.2380 Both direct and indirection thread communication are valuable tools in structuring concurrent programs.2381 2382 2567 \begin{figure} 2383 2568 \centering … … 2386 2571 2387 2572 struct Msg { int i, j; }; 2388 thread GoRtn { int i; float f; Msg m; };2573 monitor thread GoRtn { int i; float f; Msg m; }; 2389 2574 void mem1( GoRtn & mutex gortn, int i ) { gortn.i = i; } 2390 2575 void mem2( GoRtn & mutex gortn, float f ) { gortn.f = f; } … … 2396 2581 for () { 2397 2582 2398 `waitfor( mem1 ,gortn )` sout | i; // wait for calls2399 or `waitfor( mem2 ,gortn )` sout | f;2400 or `waitfor( mem3 ,gortn )` sout | m.i | m.j;2401 or `waitfor( ^?{} , gortn )` break;2583 `waitfor( mem1 : gortn )` sout | i; // wait for calls 2584 or `waitfor( mem2 : gortn )` sout | f; 2585 or `waitfor( mem3 : gortn )` sout | m.i | m.j; 2586 or `waitfor( ^?{} : gortn )` break; // low priority 2402 2587 2403 2588 } … … 2453 2638 \hspace{3pt} 2454 2639 \subfloat[Go]{\label{f:Gochannel}\usebox\myboxB} 2455 \caption{Direct communication} 2456 \label{f:DirectCommunication} 2640 \caption{Direct versus indirect communication} 2641 \label{f:DirectCommunicationComparison} 2642 2643 \medskip 2644 2645 \begin{cfa} 2646 monitor thread DatingService { 2647 condition Girls[CompCodes], Boys[CompCodes]; 2648 int girlPhoneNo, boyPhoneNo, ccode; 2649 }; 2650 int girl( DatingService & mutex ds, int phoneno, int code ) with( ds ) { 2651 girlPhoneNo = phoneno; ccode = code; 2652 `wait( Girls[ccode] );` $\C{// wait for boy}$ 2653 girlPhoneNo = phoneno; return boyPhoneNo; 2654 } 2655 int boy( DatingService & mutex ds, int phoneno, int code ) with( ds ) { 2656 boyPhoneNo = phoneno; ccode = code; 2657 `wait( Boys[ccode] );` $\C{// wait for girl}$ 2658 boyPhoneNo = phoneno; return girlPhoneNo; 2659 } 2660 void main( DatingService & ds ) with( ds ) { $\C{// thread starts, ds defaults to mutex}$ 2661 for () { 2662 waitfor( ^?{} ) break; $\C{// high priority}$ 2663 or waitfor( girl ) $\C{// girl called, compatible boy ? restart boy then girl}$ 2664 if ( ! is_empty( Boys[ccode] ) ) { `signal_block( Boys[ccode] ); signal_block( Girls[ccode] );` } 2665 or waitfor( boy ) { $\C{// boy called, compatible girl ? restart girl then boy}$ 2666 if ( ! is_empty( Girls[ccode] ) ) { `signal_block( Girls[ccode] ); signal_block( Boys[ccode] );` } 2667 } 2668 } 2669 \end{cfa} 2670 \caption{Direct communication dating service} 2671 \label{f:DirectCommunicationDatingService} 2457 2672 \end{figure} 2458 2673 … … 2469 2684 void main( Ping & pi ) { 2470 2685 for ( 10 ) { 2471 `waitfor( ping ,pi );`2686 `waitfor( ping : pi );` 2472 2687 `pong( po );` 2473 2688 } … … 2482 2697 for ( 10 ) { 2483 2698 `ping( pi );` 2484 `waitfor( pong ,po );`2699 `waitfor( pong : po );` 2485 2700 } 2486 2701 } … … 2497 2712 2498 2713 2499 \subsection{Execution Properties} 2500 2501 Table~\ref{t:ObjectPropertyComposition} shows how the \CFA high-level constructs cover 3 fundamental execution properties: thread, stateful function, and mutual exclusion. 2502 Case 1 is a basic object, with none of the new execution properties. 2503 Case 2 allows @mutex@ calls to Case 1 to protect shared data. 2504 Case 3 allows stateful functions to suspend/resume but restricts operations because the state is stackless. 2505 Case 4 allows @mutex@ calls to Case 3 to protect shared data. 2506 Cases 5 and 6 are the same as 3 and 4 without restriction because the state is stackful. 2507 Cases 7 and 8 are rejected because a thread cannot execute without a stackful state in a preemptive environment when context switching from the signal handler. 2508 Cases 9 and 10 have a stackful thread without and with @mutex@ calls. 2509 For situations where threads do not require direct communication, case 9 provides faster creation/destruction by eliminating @mutex@ setup. 2510 2511 \begin{table} 2512 \caption{Object property composition} 2513 \centering 2514 \label{t:ObjectPropertyComposition} 2515 \renewcommand{\arraystretch}{1.25} 2516 %\setlength{\tabcolsep}{5pt} 2517 \begin{tabular}{c|c||l|l} 2518 \multicolumn{2}{c||}{object properties} & \multicolumn{2}{c}{mutual exclusion} \\ 2519 \hline 2520 thread & stateful & \multicolumn{1}{c|}{No} & \multicolumn{1}{c}{Yes} \\ 2521 \hline 2522 \hline 2523 No & No & \textbf{1}\ \ \ aggregate type & \textbf{2}\ \ \ @monitor@ aggregate type \\ 2524 \hline 2525 No & Yes (stackless) & \textbf{3}\ \ \ @generator@ & \textbf{4}\ \ \ @monitor@ @generator@ \\ 2526 \hline 2527 No & Yes (stackful) & \textbf{5}\ \ \ @coroutine@ & \textbf{6}\ \ \ @monitor@ @coroutine@ \\ 2528 \hline 2529 Yes & No / Yes (stackless) & \textbf{7}\ \ \ {\color{red}rejected} & \textbf{8}\ \ \ {\color{red}rejected} \\ 2530 \hline 2531 Yes & Yes (stackful) & \textbf{9}\ \ \ @thread@ & \textbf{10}\ \ @monitor@ @thread@ \\ 2532 \end{tabular} 2533 \end{table} 2714 \subsection{\texorpdfstring{\protect\lstinline@monitor@ Generators / Coroutines / Threads}{monitor Generators / Coroutines / Threads}} 2715 2716 \CFA generators, coroutines, and threads can also be monitors (Table~\ref{t:ExecutionPropertyComposition} cases 4, 6, 12) allowing safe \emph{direct communication} with threads, \ie the custom types can have mutex functions that are called by other threads. 2717 All monitor features are available within these mutex functions. 2718 For example, if the formatter generator (or coroutine equivalent) in Figure~\ref{f:CFAFormatGen} is extended with the monitor property and this interface function is used to communicate with the formatter: 2719 \begin{cfa} 2720 void fmt( Fmt & mutex fmt, char ch ) { fmt.ch = ch; resume( fmt ) } 2721 \end{cfa} 2722 multiple threads can safely pass characters for formatting. 2723 2724 Figure~\ref{f:DirectCommunicationComparison} shows a comparison of direct call-communication in \CFA versus indirect channel-communication in Go. 2725 (Ada has a similar mechanism to \CFA direct communication.) 2726 The program thread in \CFA @main@ uses the call/return paradigm to directly communicate with the @GoRtn main@, whereas Go switches to the channel paradigm to indirectly communicate with the goroutine. 2727 Communication by multiple threads is safe for the @gortn@ thread via mutex calls in \CFA or channel assignment in Go. 2728 2729 Figure~\ref{f:DirectCommunicationDatingService} shows the dating-service problem in Figure~\ref{f:DatingServiceMonitor} extended from indirect monitor communication to direct thread communication. 2730 When converting a monitor to a thread (server), the coding pattern is to move as much code as possible from the accepted members into the thread main so it does an much work as possible. 2731 Notice, the dating server is postponing requests for an unspecified time while continuing to accept new requests. 2732 For complex servers (web-servers), there can be hundreds of lines of code in the thread main and safe interaction with clients can be complex. 2534 2733 2535 2734 … … 2537 2736 2538 2737 For completeness and efficiency, \CFA provides a standard set of low-level locks: recursive mutex, condition, semaphore, barrier, \etc, and atomic instructions: @fetchAssign@, @fetchAdd@, @testSet@, @compareSet@, \etc. 2539 Some of these low-level mechanism are used in the \CFA runtime, but we stronglyadvocate using high-level mechanisms whenever possible.2738 Some of these low-level mechanism are used to build the \CFA runtime, but we always advocate using high-level mechanisms whenever possible. 2540 2739 2541 2740 … … 2580 2779 \begin{cfa} 2581 2780 struct Adder { 2582 2781 int * row, cols; 2583 2782 }; 2584 2783 int operator()() { … … 2639 2838 \label{s:RuntimeStructureCluster} 2640 2839 2641 A \newterm{cluster} is a collection of threads and virtual processors (abstract kernel-thread) that execute the (user) threads from its own ready queue (like an OS executing kernel threads). 2840 A \newterm{cluster} is a collection of user and kernel threads, where the kernel threads run the user threads from the cluster's ready queue, and the operating system runs the kernel threads on the processors from its ready queue. 2841 The term \newterm{virtual processor} is introduced as a synonym for kernel thread to disambiguate between user and kernel thread. 2842 From the language perspective, a virtual processor is an actual processor (core). 2843 2642 2844 The purpose of a cluster is to control the amount of parallelism that is possible among threads, plus scheduling and other execution defaults. 2643 2845 The default cluster-scheduler is single-queue multi-server, which provides automatic load-balancing of threads on processors. … … 2658 2860 Programs may use more virtual processors than hardware processors. 2659 2861 On a multiprocessor, kernel threads are distributed across the hardware processors resulting in virtual processors executing in parallel. 2660 (It is possible to use affinity to lock a virtual processor onto a particular hardware processor~\cite{affinityLinux, affinityWindows, affinityFreebsd, affinityNetbsd, affinityMacosx}, which is used when caching issues occur or for heterogeneous hardware processors.)2862 (It is possible to use affinity to lock a virtual processor onto a particular hardware processor~\cite{affinityLinux,affinityWindows}, which is used when caching issues occur or for heterogeneous hardware processors.) %, affinityFreebsd, affinityNetbsd, affinityMacosx 2661 2863 The \CFA runtime attempts to block unused processors and unblock processors as the system load increases; 2662 balancing the workload with processors is difficult because it requires future knowledge, \ie what will the applicat on workload do next.2864 balancing the workload with processors is difficult because it requires future knowledge, \ie what will the application workload do next. 2663 2865 Preemption occurs on virtual processors rather than user threads, via operating-system interrupts. 2664 2866 Thus virtual processors execute user threads, where preemption frequency applies to a virtual processor, so preemption occurs randomly across the executed user threads. … … 2695 2897 Nondeterministic preemption provides fairness from long-running threads, and forces concurrent programmers to write more robust programs, rather than relying on code between cooperative scheduling to be atomic. 2696 2898 This atomic reliance can fail on multi-core machines, because execution across cores is nondeterministic. 2697 A different reason for not supporting preemption is that it significantly complicates the runtime system, \eg Microsoftruntime does not support interrupts and on Linux systems, interrupts are complex (see below).2899 A different reason for not supporting preemption is that it significantly complicates the runtime system, \eg Windows runtime does not support interrupts and on Linux systems, interrupts are complex (see below). 2698 2900 Preemption is normally handled by setting a countdown timer on each virtual processor. 2699 When the timer expires, an interrupt is delivered, and the interrupthandler resets the countdown timer, and if the virtual processor is executing in user code, the signal handler performs a user-level context-switch, or if executing in the language runtime kernel, the preemption is ignored or rolled forward to the point where the runtime kernel context switches back to user code.2901 When the timer expires, an interrupt is delivered, and its signal handler resets the countdown timer, and if the virtual processor is executing in user code, the signal handler performs a user-level context-switch, or if executing in the language runtime kernel, the preemption is ignored or rolled forward to the point where the runtime kernel context switches back to user code. 2700 2902 Multiple signal handlers may be pending. 2701 2903 When control eventually switches back to the signal handler, it returns normally, and execution continues in the interrupted user thread, even though the return from the signal handler may be on a different kernel thread than the one where the signal is delivered. 2702 2904 The only issue with this approach is that signal masks from one kernel thread may be restored on another as part of returning from the signal handler; 2703 2905 therefore, the same signal mask is required for all virtual processors in a cluster. 2704 Because preemption frequency is usually long (1 millisecond) performance cost is negligible. 2705 2706 Linux switched a decade ago from specific to arbitrary process signal-delivery for applications with multiple kernel threads. 2707 \begin{cquote} 2708 A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked. 2709 If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which it will deliver the signal. 2710 SIGNAL(7) - Linux Programmer's Manual 2711 \end{cquote} 2906 Because preemption interval is usually long (1 millisecond) performance cost is negligible. 2907 2908 Linux switched a decade ago from specific to arbitrary virtual-processor signal-delivery for applications with multiple kernel threads. 2909 In the new semantics, a virtual-processor directed signal may be delivered to any virtual processor created by the application that does not have the signal blocked. 2712 2910 Hence, the timer-expiry signal, which is generated \emph{externally} by the Linux kernel to an application, is delivered to any of its Linux subprocesses (kernel threads). 2713 2911 To ensure each virtual processor receives a preemption signal, a discrete-event simulation is run on a special virtual processor, and only it sets and receives timer events. … … 2727 2925 \label{s:Performance} 2728 2926 2729 To verify the implementation of the \CFA runtime, a series of microbenchmarks are performed comparing \CFA with pthreads, Java OpenJDK-9, Go 1.12.6and \uC 7.0.0.2927 To test the performance of the \CFA runtime, a series of microbenchmarks are used to compare \CFA with pthreads, Java 11.0.6, Go 1.12.6, Rust 1.37.0, Python 3.7.6, Node.js 12.14.1, and \uC 7.0.0. 2730 2928 For comparison, the package must be multi-processor (M:N), which excludes libdill/libmil~\cite{libdill} (M:1)), and use a shared-memory programming model, \eg not message passing. 2731 The benchmark computer is an AMD Opteron\texttrademark\ 6380 NUMA 64-core, 8 socket, 2.5 GHz processor, running Ubuntu 16.04.6 LTS, and \CFA/\uC are compiled with gcc 6.5.2929 The benchmark computer is an AMD Opteron\texttrademark\ 6380 NUMA 64-core, 8 socket, 2.5 GHz processor, running Ubuntu 16.04.6 LTS, and pthreads/\CFA/\uC are compiled with gcc 9.2.1. 2732 2930 2733 2931 All benchmarks are run using the following harness. (The Java harness is augmented to circumvent JIT issues.) 2734 2932 \begin{cfa} 2735 unsigned int N = 10_000_000; 2736 #define BENCH( `run` ) Time before = getTimeNsec(); `run;` Duration result = (getTimeNsec() - before) / N; 2737 \end{cfa} 2738 The method used to get time is @clock_gettime( CLOCK_REALTIME )@. 2739 Each benchmark is performed @N@ times, where @N@ varies depending on the benchmark; 2740 the total time is divided by @N@ to obtain the average time for a benchmark. 2741 Each benchmark experiment is run 31 times. 2933 #define BENCH( `run` ) uint64_t start = cputime_ns(); `run;` double result = (double)(cputime_ns() - start) / N; 2934 \end{cfa} 2935 where CPU time in nanoseconds is from the appropriate language clock. 2936 Each benchmark is performed @N@ times, where @N@ is selected so the benchmark runs in the range of 2--20 seconds for the specific programming language. 2937 The total time is divided by @N@ to obtain the average time for a benchmark. 2938 Each benchmark experiment is run 13 times and the average appears in the table. 2742 2939 All omitted tests for other languages are functionally identical to the \CFA tests and available online~\cite{CforallBenchMarks}. 2743 % tar --exclude=.deps --exclude=Makefile --exclude=Makefile.in --exclude=c.c --exclude=cxx.cpp --exclude=fetch_add.c -cvhf benchmark.tar benchmark 2744 2745 \paragraph{Object Creation} 2746 2747 Object creation is measured by creating/deleting the specific kind of concurrent object. 2748 Figure~\ref{f:creation} shows the code for \CFA, with results in Table~\ref{tab:creation}. 2749 The only note here is that the call stacks of \CFA coroutines are lazily created, therefore without priming the coroutine to force stack creation, the creation cost is artificially low. 2750 2751 \begin{multicols}{2} 2752 \lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}} 2753 \begin{cfa} 2754 @thread@ MyThread {}; 2755 void @main@( MyThread & ) {} 2756 int main() { 2757 BENCH( for ( N ) { @MyThread m;@ } ) 2758 sout | result`ns; 2759 } 2760 \end{cfa} 2761 \captionof{figure}{\CFA object-creation benchmark} 2762 \label{f:creation} 2763 2764 \columnbreak 2765 2766 \vspace*{-16pt} 2767 \captionof{table}{Object creation comparison (nanoseconds)} 2768 \label{tab:creation} 2769 2770 \begin{tabular}[t]{@{}r*{3}{D{.}{.}{5.2}}@{}} 2771 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\ 2772 \CFA Coroutine Lazy & 13.2 & 13.1 & 0.44 \\ 2773 \CFA Coroutine Eager & 531.3 & 536.0 & 26.54 \\ 2774 \CFA Thread & 2074.9 & 2066.5 & 170.76 \\ 2775 \uC Coroutine & 89.6 & 90.5 & 1.83 \\ 2776 \uC Thread & 528.2 & 528.5 & 4.94 \\ 2777 Goroutine & 4068.0 & 4113.1 & 414.55 \\ 2778 Java Thread & 103848.5 & 104295.4 & 2637.57 \\ 2779 Pthreads & 33112.6 & 33127.1 & 165.90 2780 \end{tabular} 2781 \end{multicols} 2782 2783 2784 \paragraph{Context-Switching} 2940 % tar --exclude-ignore=exclude -cvhf benchmark.tar benchmark 2941 2942 \paragraph{Context Switching} 2785 2943 2786 2944 In procedural programming, the cost of a function call is important as modularization (refactoring) increases. 2787 (In many cases, a compiler inlines function calls to eliminate this cost.)2788 Similarly, when modularization extends to coroutines/t asks, the time for a context switch becomes a relevant factor.2945 (In many cases, a compiler inlines function calls to increase the size and number of basic blocks for optimizing.) 2946 Similarly, when modularization extends to coroutines/threads, the time for a context switch becomes a relevant factor. 2789 2947 The coroutine test is from resumer to suspender and from suspender to resumer, which is two context switches. 2948 %For async-await systems, the test is scheduling and fulfilling @N@ empty promises, where all promises are allocated before versus interleaved with fulfillment to avoid garbage collection. 2949 For async-await systems, the test measures the cost of the @await@ expression entering the event engine by awaiting @N@ promises, where each created promise is resolved by an immediate event in the engine (using Node.js @setImmediate@). 2790 2950 The thread test is using yield to enter and return from the runtime kernel, which is two context switches. 2791 2951 The difference in performance between coroutine and thread context-switch is the cost of scheduling for threads, whereas coroutines are self-scheduling. 2792 Figure~\ref{f:ctx-switch} only shows the \CFA code for coroutines/threads (other systems are similar) with all results in Table~\ref{tab:ctx-switch}. 2952 Figure~\ref{f:ctx-switch} shows the \CFA code for a coroutine/thread with results in Table~\ref{t:ctx-switch}. 2953 2954 % From: Gregor Richards <gregor.richards@uwaterloo.ca> 2955 % To: "Peter A. Buhr" <pabuhr@plg2.cs.uwaterloo.ca> 2956 % Date: Fri, 24 Jan 2020 13:49:18 -0500 2957 % 2958 % I can also verify that the previous version, which just tied a bunch of promises together, *does not* go back to the 2959 % event loop at all in the current version of Node. Presumably they're taking advantage of the fact that the ordering of 2960 % events is intentionally undefined to just jump right to the next 'then' in the chain, bypassing event queueing 2961 % entirely. That's perfectly correct behavior insofar as its difference from the specified behavior isn't observable, but 2962 % it isn't typical or representative of much anything useful, because most programs wouldn't have whole chains of eager 2963 % promises. Also, it's not representative of *anything* you can do with async/await, as there's no way to encode such an 2964 % eager chain that way. 2793 2965 2794 2966 \begin{multicols}{2} … … 2796 2968 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 2797 2969 @coroutine@ C {} c; 2798 void main( C & ) { for ( ;;) { @suspend;@ } }2970 void main( C & ) { while () { @suspend;@ } } 2799 2971 int main() { // coroutine test 2800 2972 BENCH( for ( N ) { @resume( c );@ } ) 2801 sout | result `ns;2802 } 2803 int main() { // t asktest2973 sout | result; 2974 } 2975 int main() { // thread test 2804 2976 BENCH( for ( N ) { @yield();@ } ) 2805 sout | result `ns;2977 sout | result; 2806 2978 } 2807 2979 \end{cfa} … … 2813 2985 \vspace*{-16pt} 2814 2986 \captionof{table}{Context switch comparison (nanoseconds)} 2815 \label{t ab:ctx-switch}2987 \label{t:ctx-switch} 2816 2988 \begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}} 2817 2989 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\ 2818 C function & 1.8 & 1.8 & 0.01 \\ 2819 \CFA generator & 2.4 & 2.2 & 0.25 \\ 2820 \CFA Coroutine & 36.2 & 36.2 & 0.25 \\ 2821 \CFA Thread & 93.2 & 93.5 & 2.09 \\ 2822 \uC Coroutine & 52.0 & 52.1 & 0.51 \\ 2823 \uC Thread & 96.2 & 96.3 & 0.58 \\ 2824 Goroutine & 141.0 & 141.3 & 3.39 \\ 2825 Java Thread & 374.0 & 375.8 & 10.38 \\ 2826 Pthreads Thread & 361.0 & 365.3 & 13.19 2990 C function & 1.8 & 1.8 & 0.0 \\ 2991 \CFA generator & 1.8 & 1.8 & 0.1 \\ 2992 \CFA coroutine & 32.5 & 32.9 & 0.8 \\ 2993 \CFA thread & 93.8 & 93.6 & 2.2 \\ 2994 \uC coroutine & 50.3 & 50.3 & 0.2 \\ 2995 \uC thread & 97.3 & 97.4 & 1.0 \\ 2996 Python generator & 40.9 & 41.3 & 1.5 \\ 2997 Node.js generator & 32.6 & 32.2 & 1.0 \\ 2998 Node.js await & 1852.2 & 1854.7 & 16.4 \\ 2999 Goroutine thread & 143.0 & 143.3 & 1.1 \\ 3000 Rust thread & 332.0 & 331.4 & 2.4 \\ 3001 Java thread & 405.0 & 415.0 & 17.6 \\ 3002 Pthreads thread & 334.3 & 335.2 & 3.9 2827 3003 \end{tabular} 2828 3004 \end{multicols} 2829 3005 2830 2831 \paragraph{Mutual-Exclusion} 2832 2833 Uncontented mutual exclusion, which frequently occurs, is measured by entering/leaving a critical section. 2834 For monitors, entering and leaving a monitor function is measured. 2835 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. 2836 Figure~\ref{f:mutex} shows the code for \CFA with all results in Table~\ref{tab:mutex}. 3006 \paragraph{Internal Scheduling} 3007 3008 Internal scheduling is measured using a cycle of two threads signalling and waiting. 3009 Figure~\ref{f:schedint} shows the code for \CFA, with results in Table~\ref{t:schedint}. 2837 3010 Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects. 3011 Java scheduling is significantly greater because the benchmark explicitly creates multiple thread in order to prevent the JIT from making the program sequential, \ie removing all locking. 2838 3012 2839 3013 \begin{multicols}{2} 2840 3014 \lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}} 2841 3015 \begin{cfa} 3016 volatile int go = 0; 3017 @condition c;@ 2842 3018 @monitor@ M {} m1/*, m2, m3, m4*/; 2843 void __attribute__((noinline)) 2844 do_call( M & @mutex m/*, m2, m3, m4*/@ ) {} 3019 void call( M & @mutex p1/*, p2, p3, p4*/@ ) { 3020 @signal( c );@ 3021 } 3022 void wait( M & @mutex p1/*, p2, p3, p4*/@ ) { 3023 go = 1; // continue other thread 3024 for ( N ) { @wait( c );@ } ); 3025 } 3026 thread T {}; 3027 void main( T & ) { 3028 while ( go == 0 ) { yield(); } // waiter must start first 3029 BENCH( for ( N ) { call( m1/*, m2, m3, m4*/ ); } ) 3030 sout | result; 3031 } 2845 3032 int main() { 2846 BENCH( 2847 for( N ) do_call( m1/*, m2, m3, m4*/ ); 2848 ) 2849 sout | result`ns; 2850 } 2851 \end{cfa} 2852 \captionof{figure}{\CFA acquire/release mutex benchmark} 2853 \label{f:mutex} 3033 T t; 3034 wait( m1/*, m2, m3, m4*/ ); 3035 } 3036 \end{cfa} 3037 \captionof{figure}{\CFA Internal-scheduling benchmark} 3038 \label{f:schedint} 2854 3039 2855 3040 \columnbreak 2856 3041 2857 3042 \vspace*{-16pt} 2858 \captionof{table}{Mutex comparison (nanoseconds)} 2859 \label{tab:mutex} 2860 \begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}} 2861 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\ 2862 test and test-and-test lock & 19.1 & 18.9 & 0.40 \\ 2863 \CFA @mutex@ function, 1 arg. & 45.9 & 46.6 & 1.45 \\ 2864 \CFA @mutex@ function, 2 arg. & 105.0 & 104.7 & 3.08 \\ 2865 \CFA @mutex@ function, 4 arg. & 165.0 & 167.6 & 5.65 \\ 2866 \uC @monitor@ member rtn. & 54.0 & 53.7 & 0.82 \\ 2867 Java synchronized method & 31.0 & 31.1 & 0.50 \\ 2868 Pthreads Mutex Lock & 33.6 & 32.6 & 1.14 3043 \captionof{table}{Internal-scheduling comparison (nanoseconds)} 3044 \label{t:schedint} 3045 \bigskip 3046 3047 \begin{tabular}{@{}r*{3}{D{.}{.}{5.2}}@{}} 3048 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\ 3049 \CFA @signal@, 1 monitor & 364.4 & 364.2 & 4.4 \\ 3050 \CFA @signal@, 2 monitor & 484.4 & 483.9 & 8.8 \\ 3051 \CFA @signal@, 4 monitor & 709.1 & 707.7 & 15.0 \\ 3052 \uC @signal@ monitor & 328.3 & 327.4 & 2.4 \\ 3053 Rust cond. variable & 7514.0 & 7437.4 & 397.2 \\ 3054 Java @notify@ monitor & 9623.0 & 9654.6 & 236.2 \\ 3055 Pthreads cond. variable & 5553.7 & 5576.1 & 345.6 2869 3056 \end{tabular} 2870 3057 \end{multicols} … … 2874 3061 2875 3062 External scheduling is measured using a cycle of two threads calling and accepting the call using the @waitfor@ statement. 2876 Figure~\ref{f: ext-sched} shows the code for \CFA, with results in Table~\ref{tab:ext-sched}.3063 Figure~\ref{f:schedext} shows the code for \CFA with results in Table~\ref{t:schedext}. 2877 3064 Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects. 2878 3065 … … 2881 3068 \vspace*{-16pt} 2882 3069 \begin{cfa} 2883 volatile int go = 0; 2884 @monitor@ M {} m; 3070 @monitor@ M {} m1/*, m2, m3, m4*/; 3071 void call( M & @mutex p1/*, p2, p3, p4*/@ ) {} 3072 void wait( M & @mutex p1/*, p2, p3, p4*/@ ) { 3073 for ( N ) { @waitfor( call : p1/*, p2, p3, p4*/ );@ } 3074 } 2885 3075 thread T {}; 2886 void __attribute__((noinline))2887 do_call( M & @mutex@ ) {}2888 3076 void main( T & ) { 2889 while ( go == 0 ) { yield(); } 2890 while ( go == 1 ) { do_call( m ); } 2891 } 2892 int __attribute__((noinline)) 2893 do_wait( M & @mutex@ m ) { 2894 go = 1; // continue other thread 2895 BENCH( for ( N ) { @waitfor( do_call, m );@ } ) 2896 go = 0; // stop other thread 2897 sout | result`ns; 3077 BENCH( for ( N ) { call( m1/*, m2, m3, m4*/ ); } ) 3078 sout | result; 2898 3079 } 2899 3080 int main() { 2900 3081 T t; 2901 do_wait( m);3082 wait( m1/*, m2, m3, m4*/ ); 2902 3083 } 2903 3084 \end{cfa} 2904 3085 \captionof{figure}{\CFA external-scheduling benchmark} 2905 \label{f: ext-sched}3086 \label{f:schedext} 2906 3087 2907 3088 \columnbreak … … 2909 3090 \vspace*{-16pt} 2910 3091 \captionof{table}{External-scheduling comparison (nanoseconds)} 2911 \label{t ab:ext-sched}3092 \label{t:schedext} 2912 3093 \begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}} 2913 3094 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\ 2914 \CFA @waitfor@, 1 @monitor@ & 376.4 & 376.8 & 7.63 \\ 2915 \CFA @waitfor@, 2 @monitor@ & 491.4 & 492.0 & 13.31 \\ 2916 \CFA @waitfor@, 4 @monitor@ & 681.0 & 681.7 & 19.10 \\ 2917 \uC @_Accept@ & 331.1 & 331.4 & 2.66 3095 \CFA @waitfor@, 1 monitor & 367.1 & 365.3 & 5.0 \\ 3096 \CFA @waitfor@, 2 monitor & 463.0 & 464.6 & 7.1 \\ 3097 \CFA @waitfor@, 4 monitor & 689.6 & 696.2 & 21.5 \\ 3098 \uC \lstinline[language=uC++]|_Accept| monitor & 328.2 & 329.1 & 3.4 \\ 3099 Go \lstinline[language=Golang]|select| channel & 365.0 & 365.5 & 1.2 2918 3100 \end{tabular} 2919 3101 \end{multicols} 2920 3102 2921 2922 \paragraph{Internal Scheduling} 2923 2924 Internal scheduling is measured using a cycle of two threads signalling and waiting.2925 F igure~\ref{f:int-sched} shows the code for \CFA, with results in Table~\ref{tab:int-sched}.2926 Note, the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects.2927 Java scheduling is significantly greater because the benchmark explicitly creates multiple thread in order to prevent the JIT from making the program sequential, \ie removing all locking.3103 \paragraph{Mutual-Exclusion} 3104 3105 Uncontented mutual exclusion, which frequently occurs, is measured by entering/leaving a critical section. 3106 For monitors, entering and leaving a monitor function is measured, otherwise the language-appropriate mutex-lock is measured. 3107 For comparison, a spinning (versus blocking) test-and-test-set lock is presented. 3108 Figure~\ref{f:mutex} shows the code for \CFA with results in Table~\ref{t:mutex}. 3109 Note the incremental cost of bulk acquire for \CFA, which is largely a fixed cost for small numbers of mutex objects. 2928 3110 2929 3111 \begin{multicols}{2} 2930 3112 \lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}} 2931 3113 \begin{cfa} 2932 volatile int go = 0; 2933 @monitor@ M { @condition c;@ } m; 2934 void __attribute__((noinline)) 2935 do_call( M & @mutex@ a1 ) { @signal( c );@ } 2936 thread T {}; 2937 void main( T & this ) { 2938 while ( go == 0 ) { yield(); } 2939 while ( go == 1 ) { do_call( m ); } 2940 } 2941 int __attribute__((noinline)) 2942 do_wait( M & mutex m ) with(m) { 2943 go = 1; // continue other thread 2944 BENCH( for ( N ) { @wait( c );@ } ); 2945 go = 0; // stop other thread 2946 sout | result`ns; 2947 } 3114 @monitor@ M {} m1/*, m2, m3, m4*/; 3115 call( M & @mutex p1/*, p2, p3, p4*/@ ) {} 2948 3116 int main() { 2949 T t;2950 do_wait( m );2951 } 2952 \end{cfa} 2953 \captionof{figure}{\CFA Internal-schedulingbenchmark}2954 \label{f: int-sched}3117 BENCH( for( N ) call( m1/*, m2, m3, m4*/ ); ) 3118 sout | result; 3119 } 3120 \end{cfa} 3121 \captionof{figure}{\CFA acquire/release mutex benchmark} 3122 \label{f:mutex} 2955 3123 2956 3124 \columnbreak 2957 3125 2958 3126 \vspace*{-16pt} 2959 \captionof{table}{Internal-scheduling comparison (nanoseconds)} 2960 \label{tab:int-sched} 2961 \bigskip 2962 2963 \begin{tabular}{@{}r*{3}{D{.}{.}{5.2}}@{}} 2964 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\ 2965 \CFA @signal@, 1 @monitor@ & 372.6 & 374.3 & 14.17 \\ 2966 \CFA @signal@, 2 @monitor@ & 492.7 & 494.1 & 12.99 \\ 2967 \CFA @signal@, 4 @monitor@ & 749.4 & 750.4 & 24.74 \\ 2968 \uC @signal@ & 320.5 & 321.0 & 3.36 \\ 2969 Java @notify@ & 10160.5 & 10169.4 & 267.71 \\ 2970 Pthreads Cond. Variable & 4949.6 & 5065.2 & 363 3127 \captionof{table}{Mutex comparison (nanoseconds)} 3128 \label{t:mutex} 3129 \begin{tabular}{@{}r*{3}{D{.}{.}{3.2}}@{}} 3130 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} &\multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\ 3131 test-and-test-set lock & 19.1 & 18.9 & 0.4 \\ 3132 \CFA @mutex@ function, 1 arg. & 48.3 & 47.8 & 0.9 \\ 3133 \CFA @mutex@ function, 2 arg. & 86.7 & 87.6 & 1.9 \\ 3134 \CFA @mutex@ function, 4 arg. & 173.4 & 169.4 & 5.9 \\ 3135 \uC @monitor@ member rtn. & 54.8 & 54.8 & 0.1 \\ 3136 Goroutine mutex lock & 34.0 & 34.0 & 0.0 \\ 3137 Rust mutex lock & 33.0 & 33.2 & 0.8 \\ 3138 Java synchronized method & 31.0 & 31.0 & 0.0 \\ 3139 Pthreads mutex Lock & 31.0 & 31.1 & 0.4 2971 3140 \end{tabular} 2972 3141 \end{multicols} 2973 3142 3143 \paragraph{Creation} 3144 3145 Creation is measured by creating/deleting a specific kind of control-flow object. 3146 Figure~\ref{f:creation} shows the code for \CFA with results in Table~\ref{t:creation}. 3147 Note, the call stacks of \CFA coroutines are lazily created on the first resume, therefore the cost of creation with and without a stack are presented. 3148 3149 \begin{multicols}{2} 3150 \lstset{language=CFA,moredelim=**[is][\color{red}]{@}{@},deletedelim=**[is][]{`}{`}} 3151 \begin{cfa} 3152 @coroutine@ MyCoroutine {}; 3153 void ?{}( MyCoroutine & this ) { 3154 #ifdef EAGER 3155 resume( this ); 3156 #endif 3157 } 3158 void main( MyCoroutine & ) {} 3159 int main() { 3160 BENCH( for ( N ) { @MyCoroutine c;@ } ) 3161 sout | result; 3162 } 3163 \end{cfa} 3164 \captionof{figure}{\CFA creation benchmark} 3165 \label{f:creation} 3166 3167 \columnbreak 3168 3169 \vspace*{-16pt} 3170 \captionof{table}{Creation comparison (nanoseconds)} 3171 \label{t:creation} 3172 3173 \begin{tabular}[t]{@{}r*{3}{D{.}{.}{5.2}}@{}} 3174 \multicolumn{1}{@{}c}{} & \multicolumn{1}{c}{Median} & \multicolumn{1}{c}{Average} & \multicolumn{1}{c@{}}{Std Dev} \\ 3175 \CFA generator & 0.6 & 0.6 & 0.0 \\ 3176 \CFA coroutine lazy & 13.4 & 13.1 & 0.5 \\ 3177 \CFA coroutine eager & 144.7 & 143.9 & 1.5 \\ 3178 \CFA thread & 466.4 & 468.0 & 11.3 \\ 3179 \uC coroutine & 155.6 & 155.7 & 1.7 \\ 3180 \uC thread & 523.4 & 523.9 & 7.7 \\ 3181 Python generator & 123.2 & 124.3 & 4.1 \\ 3182 Node.js generator & 32.3 & 32.2 & 0.3 \\ 3183 Goroutine thread & 751.0 & 750.5 & 3.1 \\ 3184 Rust thread & 53801.0 & 53896.8 & 274.9 \\ 3185 Java thread & 120274.0 & 120722.9 & 2356.7 \\ 3186 Pthreads thread & 31465.5 & 31419.5 & 140.4 3187 \end{tabular} 3188 \end{multicols} 3189 3190 3191 \subsection{Discussion} 3192 3193 Languages using 1:1 threading based on pthreads can at best meet or exceed (due to language overhead) the pthread results. 3194 Note, pthreads has a fast zero-contention mutex lock checked in user space. 3195 Languages with M:N threading have better performance than 1:1 because there is no operating-system interactions. 3196 Languages with stackful coroutines have higher cost than stackless coroutines because of stack allocation and context switching; 3197 however, stackful \uC and \CFA coroutines have approximately the same performance as stackless Python and Node.js generators. 3198 The \CFA stackless generator is approximately 25 times faster for suspend/resume and 200 times faster for creation than stackless Python and Node.js generators. 3199 2974 3200 2975 3201 \section{Conclusion} … … 2977 3203 Advanced control-flow will always be difficult, especially when there is temporal ordering and nondeterminism. 2978 3204 However, many systems exacerbate the difficulty through their presentation mechanisms. 2979 This paper shows it is possible to present a hierarchy of control-flow features, generator, coroutine, thread, and monitor, providing an integrated set of high-level, efficient, and maintainable control-flow features. 2980 Eliminated from \CFA are spurious wakeup and barging, which are nonintuitive and lead to errors, and having to work with a bewildering set of low-level locks and acquisition techniques. 2981 \CFA high-level race-free monitors and tasks provide the core mechanisms for mutual exclusion and synchronization, without having to resort to magic qualifiers like @volatile@/@atomic@. 3205 This paper shows it is possible to understand high-level control-flow using three properties: statefulness, thread, mutual-exclusion/synchronization. 3206 Combining these properties creates a number of high-level, efficient, and maintainable control-flow types: generator, coroutine, thread, each of which can be a monitor. 3207 Eliminated from \CFA are barging and spurious wakeup, which are nonintuitive and lead to errors, and having to work with a bewildering set of low-level locks and acquisition techniques. 3208 \CFA high-level race-free monitors and threads provide the core mechanisms for mutual exclusion and synchronization, without having to resort to magic qualifiers like @volatile@/@atomic@. 2982 3209 Extending these mechanisms to handle high-level deadlock-free bulk acquire across both mutual exclusion and synchronization is a unique contribution. 2983 3210 The \CFA runtime provides concurrency based on a preemptive M:N user-level threading-system, executing in clusters, which encapsulate scheduling of work on multiple kernel threads providing parallelism. 2984 3211 The M:N model is judged to be efficient and provide greater flexibility than a 1:1 threading model. 2985 3212 These concepts and the \CFA runtime-system are written in the \CFA language, extensively leveraging the \CFA type-system, which demonstrates the expressiveness of the \CFA language. 2986 Performance comparisons with other concurrent systems/languages show the \CFA approach is competitive across all low-level operations, which translates directly into good performance in well-written concurrent applications.2987 C programmers should feel comfortable using these mechanisms for developing complex control-flow in applications, with the ability to obtain maximum available performance by selecting mechanisms at the appropriate level of need .3213 Performance comparisons with other concurrent systems/languages show the \CFA approach is competitive across all basic operations, which translates directly into good performance in well-written applications with advanced control-flow. 3214 C programmers should feel comfortable using these mechanisms for developing complex control-flow in applications, with the ability to obtain maximum available performance by selecting mechanisms at the appropriate level of need using only calling communication. 2988 3215 2989 3216 … … 3005 3232 \label{futur:nbio} 3006 3233 3007 Many modern workloads are not bound by computation but IO operations, a common casebeing web servers and XaaS~\cite{XaaS} (anything as a service).3234 Many modern workloads are not bound by computation but IO operations, common cases being web servers and XaaS~\cite{XaaS} (anything as a service). 3008 3235 These types of workloads require significant engineering to amortizing costs of blocking IO-operations. 3009 3236 At its core, non-blocking I/O is an operating-system level feature queuing IO operations, \eg network operations, and registering for notifications instead of waiting for requests to complete. … … 3033 3260 \section{Acknowledgements} 3034 3261 3035 The authors would like to recognize the design assistance of Aaron Moss, Rob Schluntz, Andrew Beach and Michael Brooks on the features described in this paper.3036 Funding for this project has been provided by Huawei Ltd.\ (\url{http://www.huawei.com}). %, and Peter Buhr is partially funded by the Natural Sciences and Engineering Research Council of Canada.3262 The authors recognize the design assistance of Aaron Moss, Rob Schluntz, Andrew Beach, and Michael Brooks; David Dice for commenting and helping with the Java benchmarks; and Gregor Richards for helping with the Node.js benchmarks. 3263 This research is funded by a grant from Waterloo-Huawei (\url{http://www.huawei.com}) Joint Innovation Lab. %, and Peter Buhr is partially funded by the Natural Sciences and Engineering Research Council of Canada. 3037 3264 3038 3265 {% 3039 \fontsize{9bp}{1 2bp}\selectfont%3266 \fontsize{9bp}{11.5bp}\selectfont% 3040 3267 \bibliography{pl,local} 3041 3268 }% -
doc/papers/concurrency/examples/Fib.py
r41efd33 r04e6f93 4 4 while True: 5 5 fn = fn1 + fn2; fn2 = fn1; fn1 = fn; yield fn 6 7 8 6 9 7 f1 = Fib() … … 14 12 # Local Variables: # 15 13 # tab-width: 4 # 16 # compile-command: "python3. 5Fib.py" #14 # compile-command: "python3.7 Fib.py" # 17 15 # End: # -
doc/papers/concurrency/examples/Fib2.c
r41efd33 r04e6f93 1 1 #include <stdio.h> 2 2 3 void mary() {4 printf( "MARY\n" );5 }6 7 3 #define FIB_INIT { 0 } 8 typedef struct { int next; int fn1, fn2; } Fib;4 typedef struct { int restart; int fn1, fn2; } Fib; 9 5 int fib( Fib * f ) { 10 static void * states[] = { &&s1, &&s2, &&s3 }; 11 goto *states[f->next]; 6 static void * states[] = { &&s0, &&s1, &&s2 }; 7 goto *states[f->restart]; 8 s0: 9 f->fn1 = 0; 10 f->restart = 1; 11 return f->fn1; 12 12 s1: 13 mary();14 f->fn1 = 0;15 f->next = 1;16 return f->fn1;17 s2:18 mary();19 13 f->fn2 = f->fn1; 20 14 f->fn1 = 1; 21 f-> next = 2;15 f->restart = 2; 22 16 return f->fn1; 23 s3:; 24 mary(); 17 s2:; 25 18 int fn = f->fn1 + f->fn2; 26 19 f->fn2 = f->fn1; -
doc/papers/concurrency/examples/Fib2.py
r41efd33 r04e6f93 1 1 def Fib(): 2 fn1, fn = 0, 12 fn1, fn = 1, 0 3 3 while True: 4 yield fn 14 yield fn 5 5 fn1, fn = fn, fn1 + fn 6 6 … … 12 12 # Local Variables: # 13 13 # tab-width: 4 # 14 # compile-command: "python3. 5Fib2.py" #14 # compile-command: "python3.7 Fib2.py" # 15 15 # End: # -
doc/papers/concurrency/examples/Fib3.c
r41efd33 r04e6f93 2 2 3 3 typedef struct { 4 int fn1, fn; 5 void * next; 4 int restart, fn1, fn; 6 5 } Fib; 7 #define FibCtor { 1, 0, NULL}6 #define FibCtor { 0, 1, 0 } 8 7 9 8 Fib * comain( Fib * f ) { 10 if ( __builtin_expect(f->next != 0, 1) ) goto *f->next; 11 f->next = &&s1; 9 static void * states[] = {&&s0, &&s1}; 10 goto *states[f->restart]; 11 s0: f->restart = 1; 12 12 for ( ;; ) { 13 13 return f; -
doc/papers/concurrency/examples/FibRefactor.py
r41efd33 r04e6f93 22 22 # Local Variables: # 23 23 # tab-width: 4 # 24 # compile-command: "python3. 5FibRefactor.py" #24 # compile-command: "python3.7 FibRefactor.py" # 25 25 # End: # -
doc/papers/concurrency/examples/Format.c
r41efd33 r04e6f93 2 2 3 3 typedef struct { 4 void * next;4 int restart, g, b; 5 5 char ch; 6 int g, b;7 6 } Fmt; 8 7 9 8 void comain( Fmt * f ) { 10 if ( __builtin_expect(f->next != 0, 1) ) goto *f->next; 11 f->next = &&s1; 9 static void * states[] = {&&s0, &&s1}; 10 goto *states[f->restart]; 11 s0: f->restart = 1; 12 12 for ( ;; ) { 13 13 for ( f->g = 0; f->g < 5; f->g += 1 ) { // groups 14 14 for ( f->b = 0; f->b < 4; f->b += 1 ) { // blocks 15 return; 16 s1:; while ( f->ch == '\n' ) return; // ignore 15 do { 16 return; s1: ; 17 } while ( f->ch == '\n' ); // ignore 17 18 printf( "%c", f->ch ); // print character 18 19 } … … 24 25 25 26 int main() { 26 Fmt fmt = { NULL};27 Fmt fmt = { 0 }; 27 28 comain( &fmt ); // prime 28 29 for ( ;; ) { -
doc/papers/concurrency/examples/Format.cc
r41efd33 r04e6f93 6 6 for ( g = 0; g < 5; g += 1 ) { // groups of 5 blocks 7 7 for ( b = 0; b < 4; b += 1 ) { // blocks of 4 characters 8 //for ( ;; ) { // for newline characters8 for ( ;; ) { // for newline characters 9 9 suspend(); 10 //if ( ch != '\n' ) break; // ignore newline11 //}10 if ( ch != '\n' ) break; // ignore newline 11 } 12 12 // cout << ch; // print character 13 13 } … … 31 31 // Local Variables: // 32 32 // tab-width: 4 // 33 // compile-command: "u++-work -O2 -nodebu bg Format.cc" //33 // compile-command: "u++-work -O2 -nodebug Format.cc" // 34 34 // End: // -
doc/papers/concurrency/examples/Format.cfa
r41efd33 r04e6f93 11 11 for ( g = 0; g < 5; g += 1 ) { // groups of 5 blocks 12 12 for ( b = 0; b < 4; b += 1 ) { // blocks of 4 characters 13 //do {13 do { 14 14 suspend(); 15 //} while ( ch == '\n' || ch == '\t' );15 } while ( ch == '\n' || ch == '\t' ); 16 16 sout | ch; // print character 17 17 } -
doc/papers/concurrency/examples/Format.data
r41efd33 r04e6f93 1 abcdefghijklmnopqrstuvwxyzxxxxxxxxxxxxxx 1 abcdefghijklmnop 2 qrstuvwxyzx 3 xxxxxxxxxxxxx -
doc/papers/concurrency/examples/Format.py
r41efd33 r04e6f93 4 4 for g in range( 5 ): # groups of 5 blocks 5 5 for b in range( 4 ): # blocks of 4 characters 6 print( (yield), end='' ) # receive from send 6 while True: 7 ch = (yield) # receive from send 8 if '\n' not in ch: 9 break 10 print( ch, end='' ) # receive from send 7 11 print( ' ', end='' ) # block separator 8 12 print() # group separator … … 11 15 print() 12 16 17 input = "abcdefghijklmnop\nqrstuvwx\nyzxxxxxxxxxxxxxx\n" 18 13 19 fmt = Format() 14 20 next( fmt ) # prime generator 15 for i in range( 41 ):16 fmt.send( 'a'); # send to yield21 for i in input: 22 fmt.send( i ); # send to yield 17 23 18 24 # Local Variables: # 19 25 # tab-width: 4 # 20 # compile-command: "python3. 5Format.py" #26 # compile-command: "python3.7 Format.py" # 21 27 # End: # -
doc/papers/concurrency/examples/Format1.c
r41efd33 r04e6f93 2 2 3 3 typedef struct { 4 void * next;4 int restart, g, b; 5 5 char ch; 6 int g, b;7 6 } Fmt; 8 7 9 8 void format( Fmt * f ) { 10 if ( __builtin_expect(f->next != 0, 1) ) goto *f->next; 11 f->next = &&s1; 9 static void * states[] = {&&s0, &&s1}; 10 goto *states[f->restart]; 11 s0: f->restart = 1; 12 12 for ( ;; ) { 13 13 for ( f->g = 0; f->g < 5; f->g += 1 ) { // groups 14 14 for ( f->b = 0; f->b < 4; f->b += 1 ) { // blocks 15 15 return; 16 s1: ; 17 if ( f->ch == '\0' ) goto fini; // EOF ? 16 s1: if ( f->ch == '\0' ) goto fini; // EOF ? 18 17 while ( f->ch == '\n' ) return; // ignore 19 printf( "%c", f->ch ); // print character18 // printf( "%c", f->ch ); // print character 20 19 } 21 printf( " " ); // block separator20 // printf( " " ); // block separator 22 21 } 23 printf( "\n" ); // group separator22 // printf( "\n" ); // group separator 24 23 } 25 fini: 26 if ( f->g != 0 || f->b != 0 ) printf( "\n" );24 fini:; 25 // if ( f->g != 0 || f->b != 0 ) printf( "\n" ); 27 26 } 28 27 29 28 int main() { 30 Fmt fmt = { NULL};29 Fmt fmt = { 0 }; 31 30 format( &fmt ); // prime 32 for ( ;; ) { 33 scanf( "%c", &fmt.ch ); // direct read into communication variable 34 if ( feof( stdin ) ) break; 31 fmt.ch = 'a'; 32 for ( long int i = 0; i < 1000000000; i += 1 ) { 33 // scanf( "%c", &fmt.ch ); // direct read into communication variable 34 // if ( feof( stdin ) ) break; 35 35 format( &fmt ); 36 36 } 37 fmt.ch = '\0'; 37 fmt.ch = '\0'; // sentential (EOF) 38 38 format( &fmt ); 39 39 } -
doc/papers/concurrency/examples/PingPong.c
r41efd33 r04e6f93 2 2 3 3 typedef struct PingPong { 4 int restart; // style 1 5 int N, i; 4 6 const char * name; 5 int N, i;6 7 struct PingPong * partner; 7 void * next; 8 void * next; // style 2 8 9 } PingPong; 9 #define PPCtor( name, N ) { name, N, 0, NULL, NULL } 10 #define PPCtor( name, N ) { 0, N, 0, name, NULL, NULL } 11 10 12 void comain( PingPong * pp ) __attribute__(( noinline )); 11 13 void comain( PingPong * pp ) { 14 #if 0 12 15 if ( __builtin_expect(pp->next != 0, 1) ) goto *pp->next; 13 #if 014 pp->next = &&here;15 asm( "mov %0,%%rdi" : "=m" (pp) );16 asm( "mov %rdi,%rax" );17 #ifndef OPT18 #ifdef PRINT19 asm( "add $16, %rsp" );20 #endif // PRINT21 asm( "popq %rbp" );22 #endif // ! OPT23 24 #ifdef OPT25 #ifdef PRINT26 asm( "popq %rbx" );27 #endif // PRINT28 #endif // OPT29 asm( "jmp comain" );30 here: ;31 #endif // 032 33 16 pp->next = &&cycle; 34 17 for ( ; pp->i < pp->N; pp->i += 1 ) { … … 53 36 cycle: ; 54 37 } // for 38 #endif // 0 39 40 #if 1 41 static void * states[] = {&&s0, &&s1}; 42 goto *states[pp->restart]; 43 s0: pp->restart = 1; 44 for ( ; pp->i < pp->N; pp->i += 1 ) { 45 #ifdef PRINT 46 printf( "%s %d\n", pp->name, pp->i ); 47 #endif // PRINT 48 asm( "mov %0,%%rdi" : "=m" (pp->partner) ); 49 asm( "mov %rdi,%rax" ); 50 #ifndef OPT 51 #ifdef PRINT 52 asm( "add $16, %rsp" ); 53 #endif // PRINT 54 asm( "popq %rbp" ); 55 #endif // ! OPT 56 57 #ifdef OPT 58 #ifdef PRINT 59 asm( "popq %rbx" ); 60 #endif // PRINT 61 #endif // OPT 62 asm( "jmp comain" ); 63 s1: ; 64 } // for 65 #endif // 0 55 66 } 56 67 … … 70 81 // Local Variables: // 71 82 // tab-width: 4 // 72 // compile-command: "gcc- 8-g -DPRINT PingPong.c" //83 // compile-command: "gcc-9 -g -DPRINT PingPong.c" // 73 84 // End: // -
doc/papers/concurrency/examples/Pingpong.py
r41efd33 r04e6f93 1 1 def PingPong( name, N ): 2 partner = (yield)# get partner3 yield 2 partner = yield # get partner 3 yield # resume scheduler 4 4 for i in range( N ): 5 5 print( name ) 6 yield partner 6 yield partner # execute next 7 7 print( "end", name ) 8 8 9 9 def Scheduler(): 10 n = (yield) # starting coroutine 11 while True: 12 n = next( n ) # schedule coroutine 10 n = yield # starting coroutine 11 try: 12 while True: 13 n = next( n ) # schedule coroutine 14 except StopIteration: 15 pass 13 16 14 17 pi = PingPong( "ping", 5 ) 15 18 po = PingPong( "pong", 5 ) 16 next( pi ) 17 pi.send( po ) 18 next( po ) 19 po.send( pi ) 19 next( pi ) # prime 20 pi.send( po ) # send partner 21 next( po ) # prime 22 po.send( pi ) # send partner 20 23 21 24 s = Scheduler(); 22 next( s ) 25 next( s ) # prime 23 26 try: 24 27 s.send( pi ) # start cycle 25 except StopIteration: 26 p rint( "scheduler stop" )28 except StopIteration: # scheduler stopped 29 pass 27 30 print( "stop" ) 28 31 29 32 # Local Variables: # 30 33 # tab-width: 4 # 31 # compile-command: "python3. 5Pingpong.py" #34 # compile-command: "python3.7 Pingpong.py" # 32 35 # End: # -
doc/papers/concurrency/examples/ProdCons.py
r41efd33 r04e6f93 1 1 def Prod( N ): 2 cons = (yield)# get cons3 yield 2 cons = yield # get cons 3 yield # resume scheduler 4 4 for i in range( N ): 5 5 print( "prod" ) 6 yield cons 6 yield cons # execute next 7 7 print( "end", "prod" ) 8 8 9 9 def Cons( N ): 10 prod = (yield)# get prod11 yield 10 prod = yield # get prod 11 yield # resume scheduler 12 12 for i in range( N ): 13 13 print( "cons" ) 14 yield prod 14 yield prod # execute next 15 15 print( "end", "cons" ) 16 16 17 17 def Scheduler(): 18 n = (yield) # starting coroutine 19 while True: 20 n = next( n ) # schedule coroutine 18 n = yield # starting coroutine 19 try: 20 while True: 21 n = next( n ) # schedule coroutine 22 except StopIteration: 23 pass 21 24 22 25 prod = Prod( 5 ) 23 26 cons = Cons( 5 ) 24 next( prod ) 25 prod.send( cons ) 26 next( cons ) 27 cons.send( prod ) 27 next( prod ) # prime 28 prod.send( cons ) # send cons 29 next( cons ) # prime 30 cons.send( prod ) # send prod 28 31 29 32 s = Scheduler(); 30 next( s ) 33 next( s ) # prime 31 34 try: 32 35 s.send( prod ) # start cycle 33 except StopIteration: 34 p rint( "scheduler stop" )36 except StopIteration: # scheduler stopped 37 pass 35 38 print( "stop" ) 36 39 37 40 # Local Variables: # 38 41 # tab-width: 4 # 39 # compile-command: "python3. 5ProdCons.py" #42 # compile-command: "python3.7 ProdCons.py" # 40 43 # End: # -
doc/papers/concurrency/examples/RWMonitorEXT.cfa
r41efd33 r04e6f93 7 7 int rcnt, wcnt; // number of readers/writer using resource 8 8 }; 9 10 void ?{}( ReadersWriter & rw ) with(rw) { rcnt = wcnt = 0; } 9 11 void EndRead( ReadersWriter & mutex rw ) with(rw) { rcnt -= 1; } 10 12 void EndWrite( ReadersWriter & mutex rw ) with(rw) { wcnt = 0; } 11 13 void StartRead( ReadersWriter & mutex rw ) with(rw) { 12 if ( wcnt > 0 ) waitfor( EndWrite ,rw );14 if ( wcnt > 0 ) waitfor( EndWrite : rw ); 13 15 rcnt += 1; 14 16 } 15 17 void StartWrite( ReadersWriter & mutex rw ) with(rw) { 16 if ( wcnt > 0 ) waitfor( EndWrite ,rw );17 else while ( rcnt > 0 ) waitfor( EndRead ,rw );18 if ( wcnt > 0 ) waitfor( EndWrite : rw ); 19 else while ( rcnt > 0 ) waitfor( EndRead : rw ); 18 20 wcnt = 1; 19 21 } 20 void ?{}( ReadersWriter & rw ) with(rw) { rcnt = wcnt = 0; }21 22 int readers( ReadersWriter & rw ) { return rw.rcnt; } 23 22 24 void Read( ReadersWriter & rw ) { 23 25 StartRead( rw ); … … 34 36 EndWrite( rw ); 35 37 } 38 36 39 thread Worker { 37 40 ReadersWriter &rw; … … 47 50 } // for 48 51 } 52 49 53 int main() { 50 54 enum { MaxTask = 5 }; … … 57 61 } // main 58 62 59 60 63 // Local Variables: // 61 64 // tab-width: 4 // 62 // compile-command: "cfa -O2 RWMonitor .cfa" //65 // compile-command: "cfa -O2 RWMonitorEXT.cfa" // 63 66 // End: // -
doc/papers/concurrency/examples/Refactor.py
r41efd33 r04e6f93 26 26 # Local Variables: # 27 27 # tab-width: 4 # 28 # compile-command: "python3. 5Refactor.py" #28 # compile-command: "python3.7 Refactor.py" # 29 29 # End: # -
doc/papers/concurrency/figures/FullCoroutinePhases.fig
r41efd33 r04e6f93 8 8 -2 9 9 1200 2 10 5 1 0 1 0 7 100 0 -1 0.000 0 0 1 0 4575.000 2437.500 4275 1875 4575 1800 4875 187510 5 1 0 1 0 7 100 0 -1 0.000 0 0 1 0 5175.000 2437.500 4875 1875 5175 1800 5475 1875 11 11 1 1 1.00 45.00 90.00 12 5 1 0 1 0 7 100 0 -1 0.000 0 0 1 0 4575.000 1537.500 4875 2100 4575 2175 4275 210012 5 1 0 1 0 7 100 0 -1 0.000 0 0 1 0 5175.000 1537.500 5475 2100 5175 2175 4875 2100 13 13 1 1 1.00 45.00 90.00 14 5 1 0 1 0 7 50 -1 -1 0.000 0 1 1 0 4 207.500 1642.500 4125 1425 3975 1650 4200 187514 5 1 0 1 0 7 50 -1 -1 0.000 0 1 1 0 4807.500 1642.500 4725 1425 4575 1650 4800 1875 15 15 1 1 1.00 45.00 90.00 16 6 1575 1575 2700 2025 16 17 2 1 0 1 0 7 100 0 -1 0.000 0 0 -1 1 0 2 17 18 1 1 1.00 45.00 90.00 … … 20 21 1 1 1.00 45.00 90.00 21 22 2175 1575 2400 1800 23 4 1 0 100 0 4 10 0.0000 2 165 300 1725 1950 ping\001 24 4 1 0 100 0 4 10 0.0000 2 135 360 2475 1950 pong\001 25 -6 26 6 3075 1575 4200 2025 27 6 3075 1575 4200 2025 22 28 2 1 0 1 0 7 100 0 -1 0.000 0 0 -1 1 0 2 23 29 1 1 1.00 45.00 90.00 24 3 3001575 3300 180030 3525 1575 3300 1800 25 31 2 1 0 1 0 7 100 0 -1 0.000 0 0 -1 1 0 2 26 32 1 1 1.00 45.00 90.00 27 3300 2025 3300 2250 28 4 1 0 100 0 0 10 0.0000 2 105 555 2100 1200 creation\001 29 4 1 0 100 0 4 10 0.0000 2 165 300 1725 1950 ping\001 30 4 1 0 100 0 4 10 0.0000 2 135 360 2475 1950 pong\001 31 4 1 0 100 0 4 10 0.0000 2 165 300 3300 1950 ping\001 32 4 1 0 100 0 4 10 0.0000 2 135 360 3300 2400 pong\001 33 4 1 0 100 0 0 10 0.0000 2 105 675 4575 1200 execution\001 34 4 1 0 100 0 4 10 0.0000 2 165 300 4275 2025 ping\001 35 4 1 0 100 0 4 10 0.0000 2 135 360 4875 2025 pong\001 36 4 1 0 100 0 0 10 0.0000 2 90 420 3300 1200 starter\001 33 3675 1575 3900 1800 34 4 1 0 100 0 4 10 0.0000 2 165 300 3225 1950 ping\001 35 4 1 0 100 0 4 10 0.0000 2 135 360 3975 1950 pong\001 36 -6 37 -6 37 38 4 1 0 100 0 4 10 0.0000 2 165 705 2100 1500 pgm main\001 38 4 1 0 100 0 4 10 0.0000 2 165 705 3300 1500 pgm main\001 39 4 1 0 100 0 4 10 0.0000 2 165 705 4500 1500 pgm main\001 39 4 1 0 100 0 4 10 0.0000 2 165 705 3600 1500 pgm main\001 40 4 1 0 100 0 4 10 0.0000 2 165 300 4875 2025 ping\001 41 4 1 0 100 0 4 10 0.0000 2 135 360 5475 2025 pong\001 42 4 1 0 100 0 4 10 0.0000 2 165 705 5100 1500 pgm main\001 43 4 1 0 100 0 2 10 0.0000 2 105 540 2100 1275 creator\001 44 4 1 0 100 0 2 10 0.0000 2 105 495 3600 1275 starter\001 45 4 1 0 100 0 2 10 0.0000 2 105 690 5175 1275 execution\001 -
doc/papers/concurrency/figures/RunTimeStructure.fig
r41efd33 r04e6f93 36 36 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 4500 3600 15 15 4500 3600 4515 3615 37 37 -6 38 6 2175 4650 7050 4950 39 1 3 0 1 0 0 0 0 0 0.000 1 0.0000 2250 4830 30 30 2250 4830 2280 4860 40 1 1 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4200 4800 150 75 4200 4800 4350 4875 41 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 3275 4800 100 100 3275 4800 3375 4800 38 6 3225 4125 4650 4425 39 6 4350 4200 4650 4350 40 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 4425 4275 15 15 4425 4275 4440 4290 41 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 4500 4275 15 15 4500 4275 4515 4290 42 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 4575 4275 15 15 4575 4275 4590 4290 43 -6 44 1 1 0 1 -1 -1 0 0 -1 0.000 1 0.0000 3450 4275 225 150 3450 4275 3675 4425 45 1 1 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4050 4275 225 150 4050 4275 4275 4425 46 -6 47 6 6675 4125 7500 4425 48 6 7200 4200 7500 4350 49 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 7275 4275 15 15 7275 4275 7290 4290 50 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 7350 4275 15 15 7350 4275 7365 4290 51 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 7425 4275 15 15 7425 4275 7440 4290 52 -6 53 1 1 0 1 -1 -1 0 0 -1 0.000 1 0.0000 6900 4275 225 150 6900 4275 7125 4425 54 -6 55 6 6675 3525 8025 3975 56 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 1 0 2 57 1 1 1.00 45.00 90.00 58 6675 3750 6975 3750 59 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 1 0 2 60 1 1 1.00 45.00 90.00 61 7125 3750 7350 3750 42 62 2 2 0 1 -1 -1 0 0 -1 0.000 0 0 0 0 0 5 43 5400 4950 5400 4725 5175 4725 5175 4950 5400 4950 44 2 2 1 1 -1 -1 0 0 -1 3.000 0 0 0 0 0 5 45 6525 4950 6300 4950 6300 4725 6525 4725 6525 4950 46 4 0 -1 0 0 0 10 0.0000 2 105 450 6600 4875 cluster\001 47 4 0 -1 0 0 0 10 0.0000 2 105 660 5475 4875 processor\001 48 4 0 -1 0 0 0 10 0.0000 2 105 555 4425 4875 monitor\001 49 4 0 -1 0 0 0 10 0.0000 2 120 270 3450 4875 task\001 50 4 0 -1 0 0 0 10 0.0000 2 105 660 2325 4875 coroutine\001 51 -6 52 6 3450 1275 3750 1425 53 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 3525 1350 15 15 3525 1350 3540 1365 54 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 3600 1350 15 15 3600 1350 3615 1365 55 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 3675 1350 15 15 3675 1350 3690 1365 56 -6 57 6 5550 1275 5850 1425 58 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 5625 1350 15 15 5625 1350 5640 1365 59 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 5700 1350 15 15 5700 1350 5715 1365 60 1 3 0 1 -1 -1 0 0 20 0.000 1 0.0000 5775 1350 15 15 5775 1350 5790 1365 63 7800 3975 7800 3525 7350 3525 7350 3975 7800 3975 64 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 1 0 2 65 1 1 1.00 45.00 90.00 66 7800 3750 8025 3750 61 67 -6 62 68 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 5550 2625 150 150 5550 2625 5700 2625 … … 67 73 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4425 2850 150 150 4425 2850 4575 2850 68 74 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4650 2475 150 150 4650 2475 4800 2475 69 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 3525 3600 150 150 3525 3600 3675 360070 75 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 3975 3600 150 150 3975 3600 4125 3600 71 76 1 3 0 1 0 0 0 0 0 0.000 1 0.0000 3525 3600 30 30 3525 3600 3555 3630 … … 74 79 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 3975 2850 150 150 3975 2850 4125 2850 75 80 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 7200 2775 150 150 7200 2775 7350 2775 76 1 1 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4650 1350 225 150 4650 1350 4875 1500 77 1 1 0 1 -1 -1 0 0 -1 0.000 1 0.0000 5250 1350 225 150 5250 1350 5475 1500 78 1 1 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4050 1350 225 150 4050 1350 4275 1500 81 1 3 0 1 0 0 0 0 0 0.000 1 0.0000 2250 4830 30 30 2250 4830 2280 4860 82 1 3 0 1 0 0 0 0 0 0.000 1 0.0000 7200 2775 30 30 7200 2775 7230 2805 83 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 3525 3600 150 150 3525 3600 3675 3600 84 1 3 0 1 -1 -1 0 0 -1 0.000 1 0.0000 3875 4800 100 100 3875 4800 3975 4800 85 1 1 0 1 -1 -1 0 0 -1 0.000 1 0.0000 4650 4800 150 75 4650 4800 4800 4875 79 86 2 2 0 1 -1 -1 0 0 -1 0.000 0 0 0 0 0 5 80 87 2400 4200 2400 3750 1950 3750 1950 4200 2400 4200 … … 140 147 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 1 0 2 141 148 1 1 1.00 45.00 90.00 142 6675 3975 6975 3975143 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 1 0 2144 1 1 1.00 45.00 90.00145 149 7050 2775 6825 2775 146 150 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 0 0 2 147 6825 2775 6825 3975 148 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 1 0 2 149 1 1 1.00 45.00 90.00 150 7125 3975 7350 3975 151 2 2 0 1 -1 -1 0 0 -1 0.000 0 0 0 0 0 5 152 7800 4200 7800 3750 7350 3750 7350 4200 7800 4200 153 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 1 0 2 154 1 1 1.00 45.00 90.00 155 7800 3975 8025 3975 151 6825 2775 6825 3750 156 152 2 1 0 1 -1 -1 0 0 -1 0.000 0 0 -1 1 0 4 157 153 1 1 1.00 45.00 90.00 158 7875 3975 7875 2325 7200 2325 7200 2550 154 7875 3750 7875 2325 7200 2325 7200 2550 155 2 2 0 1 -1 -1 0 0 -1 0.000 0 0 0 0 0 5 156 5850 4950 5850 4725 5625 4725 5625 4950 5850 4950 157 2 2 1 1 -1 -1 0 0 -1 3.000 0 0 0 0 0 5 158 6975 4950 6750 4950 6750 4725 6975 4725 6975 4950 159 159 4 1 -1 0 0 0 10 0.0000 2 105 720 5550 4425 Processors\001 160 160 4 1 -1 0 0 0 10 0.0000 2 120 1005 4200 3225 Blocked Tasks\001 … … 165 165 4 1 -1 0 0 0 10 0.0000 2 105 990 2175 3525 Discrete-event\001 166 166 4 1 -1 0 0 0 10 0.0000 2 135 795 2175 4350 preemption\001 167 4 0 -1 0 0 0 10 0.0000 2 150 1290 2325 4875 genrator/coroutine\001 168 4 0 -1 0 0 0 10 0.0000 2 120 270 4050 4875 task\001 169 4 0 -1 0 0 0 10 0.0000 2 105 450 7050 4875 cluster\001 170 4 0 -1 0 0 0 10 0.0000 2 105 660 5925 4875 processor\001 171 4 0 -1 0 0 0 10 0.0000 2 105 555 4875 4875 monitor\001 -
doc/papers/concurrency/mail2
r41efd33 r04e6f93 22 22 Software: Practice and Experience Editorial Office 23 23 24 25 26 Date: Tue, 12 Nov 2019 22:25:17 +0000 27 From: Richard Jones <onbehalfof@manuscriptcentral.com> 28 Reply-To: R.E.Jones@kent.ac.uk 29 To: tdelisle@uwaterloo.ca, pabuhr@uwaterloo.ca 30 Subject: Software: Practice and Experience - Decision on Manuscript ID 31 SPE-19-0219 32 33 12-Nov-2019 34 35 Dear Dr Buhr, 36 37 Many thanks for submitting SPE-19-0219 entitled "Advanced Control-flow and Concurrency in Cforall" to Software: Practice and Experience. The paper has now been reviewed and the comments of the referees are included at the bottom of this letter. 38 39 The decision on this paper is that it requires substantial further work is required. The referees have a number of substantial concerns. All the reviewers found the submission very hard to read; two of the reviewers state that it needs very substantial restructuring. These concerns must be addressed before your submission can be considered further. 40 41 A revised version of your manuscript that takes into account the comments of the referees will be reconsidered for publication. 42 43 Please note that submitting a revision of your manuscript does not guarantee eventual acceptance, and that your revision will be subject to re-review by the referees before a decision is rendered. 44 45 You have 90 days from the date of this email to submit your revision. If you are unable to complete the revision within this time, please contact me to request an extension. 46 47 You can upload your revised manuscript and submit it through your Author Center. Log into https://mc.manuscriptcentral.com/spe and enter your Author Center, where you will find your manuscript title listed under "Manuscripts with Decisions". 48 49 When submitting your revised manuscript, you will be able to respond to the comments made by the referee(s) in the space provided. You can use this space to document any changes you make to the original manuscript. 50 51 If you feel that your paper could benefit from English language polishing, you may wish to consider having your paper professionally edited for English language by a service such as Wiley's at http://wileyeditingservices.com. Please note that while this service will greatly improve the readability of your paper, it does not guarantee acceptance of your paper by the journal. 52 53 Once again, thank you for submitting your manuscript to Software: Practice and Experience and I look forward to receiving your revision. 54 55 56 Sincerely, 57 58 Prof. Richard Jones 59 Software: Practice and Experience 60 R.E.Jones@kent.ac.uk 61 62 63 Referee(s)' Comments to Author: 64 65 Reviewing: 1 66 67 Comments to the Author 68 This article presents the design and rationale behind the various 69 threading and synchronization mechanisms of C-forall, a new low-level 70 programming language. This paper is very similar to a companion paper 71 which I have also received: as the papers are similar, so will these 72 reviews be --- in particular any general comments from the other 73 review apply to this paper also. 74 75 As far as I can tell, the article contains three main ideas: an 76 asynchronous execution / threading model; a model for monitors to 77 provide mutual exclusion; and an implementation. The first two ideas 78 are drawn together in Table 1: unfortunately this is on page 25 of 30 79 pages of text. Implementation choices and descriptions are scattered 80 throughout the paper - and the sectioning of the paper seems almost 81 arbitrary. 82 83 The article is about its contributions. Simply adding feature X to 84 language Y isn't by itself a contribution, (when feature X isn't 85 already a contribution). The contribution can be in the design: the 86 motivation, the space of potential design options, the particular 87 design chosen and the rationale for that choice, or the resulting 88 performance. For example: why support two kinds of generators as well 89 as user-level threads? Why support both low and high level 90 synchronization constructs? Similarly I would have found the article 91 easier to follow if it was written top down, presenting the design 92 principles, present the space of language features, justify chosen 93 language features (and rationale) and those excluded, and then present 94 implementation, and performance. 95 96 Then the writing of the article is often hard to follow, to say the 97 least. Two examples: section 3 "stateful functions" - I've some idea 98 what that is (a function with Algol's "own" or C's "static" variables? 99 but in fact the paper has a rather more specific idea than that. The 100 top of page 3 throws a whole lot of defintions at the reader 101 "generator" "coroutine" "stackful" "stackless" "symmetric" 102 "asymmetric" without every stopping to define each one --- but then in 103 footnote "C" takes the time to explain what C's "main" function is? I 104 cannot imagine a reader of this paper who doesn't know what "main" is 105 in C; especially if they understand the other concepts already 106 presented in the paper. The start of section 3 then does the same 107 thing: putting up a whole lot of definitions, making distinctions and 108 comparisons, even talking about some runtime details, but the critical 109 definition of a monitor doesn't appear until three pages later, at the 110 start of section 5 on p15, lines 29-34 are a good, clear, description 111 of what a monitor actually is. That needs to come first, rather than 112 being buried again after two sections of comparisons, discussions, 113 implementations, and options that are ungrounded because they haven't 114 told the reader what they are actually talking about. First tell the 115 reader what something is, then how they might use it (as programmers: 116 what are the rules and restrictions) and only then start comparison 117 with other things, other approaches, other languages, or 118 implementations. 119 120 The description of the implementation is similarly lost in the trees 121 without ever really seeing the wood. Figure 19 is crucial here, but 122 it's pretty much at the end of the paper, and comments about 123 implementations are threaded throughout the paper without the context 124 (fig 19) to understand what's going on. The protocol for performance 125 testing may just about suffice for C (although is N constantly ten 126 million, or does it vary for each benchmark) but such evaluation isn't 127 appropriate for garbage-collected or JITTed languages like Java or Go. 128 129 other comments working through the paper - these are mostly low level 130 and are certainly not comprehensive. 131 132 p1 only a subset of C-forall extensions? 133 134 p1 "has features often associated with object-oriented programming 135 languages, such as constructors, destructors, virtuals and simple 136 inheritance." There's no need to quibble about this. Once a language 137 has inheritance, it's hard to claim it's not object-oriented. 138 139 140 p2 barging? signals-as-hints? 141 142 p3 start your discussion of generations with a simple example of a 143 C-forall generator. Fig 1(b) might do: but put it inline instead of 144 the python example - and explain the key rules and restrictions on the 145 construct. Then don't even start to compare with coroutines until 146 you've presented, described and explained your coroutines... 147 p3 I'd probably leave out the various "C" versions unless there are 148 key points to make you can't make in C-forall. All the alternatives 149 are just confusing. 150 151 152 p4 but what's that "with" in Fig 1(B) 153 154 p5 start with the high level features of C-forall generators... 155 156 p5 why is the paper explaining networking protocols? 157 158 p7 lines 1-9 (transforming generator to coroutine - why would I do any 159 of this? Why would I want one instead of the other (do not use "stack" 160 in your answer!) 161 162 p10 last para "A coroutine must retain its last resumer to suspend 163 back because the resumer is on a different stack. These reverse 164 pointers allow suspend to cycle backwards, " I've no idea what is 165 going on here? why should I care? Shouldn't I just be using threads 166 instead? why not? 167 168 p16 for the same reasons - what reasons? 169 170 p17 if the multiple-monitor entry procedure really is novel, write a 171 paper about that, and only about that. 172 173 p23 "Loose Object Definitions" - no idea what that means. in that 174 section: you can't leave out JS-style dynamic properties. Even in 175 OOLs that (one way or another) allow separate definitions of methods 176 (like Objective-C, Swift, Ruby, C#) at any time a runtime class has a 177 fixed definition. Quite why the detail about bit mask implementation 178 is here anyway, I've no idea. 179 180 p25 this cluster isn't a CLU cluster then? 181 182 * conclusion should conclude the paper, not the related. 183 184 185 Reviewing: 2 186 187 Comments to the Author 188 This paper describes the concurrency features of an extension of C (whose name I will write as "C\/" here, for convenience), including much design-level discussion of the coroutine- and monitor-based features and some microbenchmarks exploring the current implementation's performance. The key message of the latter is that the system's concurrency abstractions are much lighter-weight than the threading found in mainstream C or Java implementations. 189 190 There is much description of the system and its details, but nothing about (non-artificial) uses of it. Although the microbenchmark data is encouraging, arguably not enough practical experience with the system has been reported here to say much about either its usability advantages or its performance. 191 192 As such, the main contribution of the paper seem to be to document the existence of the described system and to provide a detailed design rationale and (partial) tutorial. I believe that could be of interest to some readers, so an acceptable manuscript is lurking in here somewhere. 193 194 Unfortunately, at present the writing style is somewhere between unclear and infuriating. It omits to define terms; it uses needlessly many terms for what are apparently (but not clearly) the same things; it interrupts itself rather than deliver the natural consequent of whatever it has just said; and so on. Section 5 is particularly bad in these regards -- see my detailed comments below. Fairly major additional efforts will be needed to turn the present text into a digestible design-and-tutorial document. I suspect that a shorter paper could do this job better than the present manuscript, which is overwrought in parts. 195 196 p2: lines 4--9 are a little sloppy. It is not the languages but their popular implementations which "adopt" the 1:1 kernel threading model. 197 198 line 10: "medium work" -- "medium-sized work"? 199 200 line 18: "is all sequential to the compiler" -- not true in modern compilers, and in 2004 H-J Boehm wrote a tech report describing exactly why ("Threads cannot be implemented as a library", HP Labs). 201 202 line 20: "knows the optimization boundaries" -- I found this vague. What's an example? 203 204 line 31: this paragraph has made a lot of claims. Perhaps forward-reference to the parts of the paper that discuss each one. 205 206 line 33: "so the reader can judge if" -- this reads rather passive-aggressively. Perhaps better: "... to support our argument that..." 207 208 line 41: "a dynamic partitioning mechanism" -- I couldn't tell what this meant 209 210 p3. Presenting concept of a "stateful function" as a new language feature seems odd. In C, functions often have local state thanks to static local variables (or globals, indeed). Of course, that has several limitations. Can you perhaps present your contributions by enumerating these limitations? See also my suggestion below about a possible framing centred on a strawman. 211 212 line 2: "an old idea that is new again" -- this is too oblique 213 214 lines 2--15: I found this to be a word/concept soup. Stacks, closures, generators, stackless stackful, coroutine, symmetric, asymmetric, resume/suspend versus resume/resume... there needs to be a more gradual and structured way to introduce all this, and ideally one that minimises redundancy. Maybe present it as a series of "definitions" each with its own heading, e.g. "A closure is stackless if its local state has statically known fixed size"; "A generator simply means a stackless closure." And so on. Perhaps also strongly introduce the word "activate" as a direct contrast with resume and suspend. These are just a flavour of the sort of changes that might make this paragraph into something readable. 215 216 Continuing the thought: I found it confusing that by these definitinos, a stackful closure is not a stack, even though logically the stack *is* a kind of closure (it is a representation of the current thread's continuation). 217 218 lines 24--27: without explaining what the boost functor types mean, I don't think the point here comes across. 219 220 line 34: "semantically coupled" -- I wasn't surew hat this meant 221 222 p4: the point of Figure 1 (C) was not immediately clear. It seem to be showing how one might "compile down" Figure 1 (B). Or is that Figure 1 (A)? 223 224 It's right that the incidental language features of the system are not front-and-centre, but I'd appreciate some brief glossing of non-C languages features as they appear. Examples are the square bracket notation, the pipe notation and the constructor syntax. These explanations could go in the caption of the figure which first uses them, perhaps. Overall I found the figure captions to be terse, and a missed opportunity to explain clearly what was going on. 225 226 p5 line 23: "This restriction is removed..." -- give us some up-front summary of your contributions and the elements of the language design that will be talked about, so that this isn't an aside. This will reduce the "twisty passages" feeling that characterises much of the paper. 227 228 line 40: "a killer asymmetric generator" -- this is stylistically odd, and the sentence about failures doesn't convincigly argue that C\/ will help with them. Have you any experience writing device drivers using C\/? Or any argument that the kinds of failures can be traced to the "stack-ripping" style that one is forced to use without coroutines? Also, a typo on line 41: "device drives". And saying "Windows/Linux" is sloppy... what does the cited paper actually say? 229 230 p6 lines 13--23: this paragraph is difficult to understand. It seems to be talking about a control-flow pattern roughly equivalent to tail recursion. What is the high-level point, other than that this is possible? 231 232 line 34: "which they call coroutines" -- a better way to make this point is presumably that the C++20 proposal only provides a specialised kind of coroutine, namely generators, despite its use of the more general word. 233 234 line 47: "... due to dynamic stack allocation, execution..." -- this sentence doesn't scan. I suggest adding "and for" in the relevant places where currently there are only commas. 235 236 p8 / Figure 5 (B) -- the GNU C extension of unary "&&" needs to be explained. The whole figure needs a better explanation, in fact. 237 238 p9, lines 1--10: I wasn't sure this stepping-through really added much value. What are the truly important points to note about this code? 239 240 p10: similarly, lines 3--27 again are somewhere between tedious and confusing. I'm sure the motivation and details of "starter semantics" can both be stated much more pithily. 241 242 line 32: "a self-resume does not overwrite the last resumer" -- is this a hack or a defensible principled decision? 243 244 p11: "a common source of errors" -- among beginners or among production code? Presumably the former. 245 246 line 23: "with builtin and library" -- not sure what this means 247 248 lines 31--36: these can be much briefer. The only important point here seems to be that coroutines cannot be copied. 249 250 p12: line 1: what is a "task"? Does it matter? 251 252 line 7: calling it "heap stack" seems to be a recipe for confusion. "Stack-and-heap" might be better, and contrast with "stack-and-VLS" perhaps. When "VLS" is glossed, suggest actually expanding its initials: say "length" not "size". 253 254 line 21: are you saying "cooperative threading" is the same as "non-preemptive scheduling", or that one is a special case (kind) of the other? Both are defensible, but be clear. 255 256 line 27: "mutual exclusion and synchronization" -- the former is a kind of the latter, so I suggest "and other forms of synchronization". 257 258 line 30: "can either be a stackless or stackful" -- stray "a", but also, this seems to be switching from generic/background terminology to C\/-specific terminology. 259 260 An expositional idea occurs: start the paper with a strawman naive/limited realisation of coroutines -- say, Simon Tatham's popular "Coroutines in C" web page -- and identify point by point what the limitations are and how C\/ overcomes them. Currently the presentation is often flat (lacking motivating contrasts) and backwards (stating solutions before problems). The foregoing approach might fix both of these. 261 262 page 13: line 23: it seems a distraction to mention the Python feature here. 263 264 p14 line 5: it seems odd to describe these as "stateless" just because they lack shared mutable state. It means the code itself is even more stateful. Maybe the "stack ripping" argument could usefully be given here. 265 266 line 16: "too restrictive" -- would be good to have a reference to justify this, or at least give a sense of what the state-of-the-art performance in transactional memory systems is (both software and hardware) 267 268 line 22: "simulate monitors" -- what about just *implementing* monitors? isn't that what these systems do? or is the point more about refining them somehow into something more specialised? 269 270 p15: sections 4.1 and 4.2 seem adrift and misplaced. Split them into basic parts (which go earlier) and more advanced parts (e.g. barging, which can be explained later). 271 272 line 31: "acquire/release" -- misses an opportunity to contrast the monitor's "enter/exit" abstraction with the less structured acquire/release of locks. 273 274 p16 line 12: the "implicit" versus "explicit" point is unclear. Is it perhaps about the contract between an opt-in *discipline* and a language-enforced *guarantee*? 275 276 line 28: no need to spend ages dithering about which one is default and which one is the explicit qualifier. Tell us what you decided, briefly justify it, and move on. 277 278 p17: Figure 11: since the main point seems to be to highlight bulk acquire, include a comment which identifies the line where this is happening. 279 280 line 2: "impossible to statically..." -- or dynamically. Doing it dynamically would be perfectly acceptable (locking is a dynamic operation after all) 281 282 "guarantees acquisition order is consistent" -- assuming it's done in a single bulk acquire. 283 284 p18: section 5.3: the text here is a mess. The explanations of "internal" versus "external" scheduling are unclear, and "signals as hints" is not explained. "... can cause thread starvation" -- means including a while loop, or not doing so? "There are three signalling mechanisms.." but the text does not follow that by telling us what they are. My own scribbled attempt at unpicking the internal/external thing: "threads already in the monitor, albeit waiting, have priority over those trying to enter". 285 286 p19: line 3: "empty condition" -- explain that condition variables don't store anything. So being "empty" means that the queue of waiting threads (threads waiting to be signalled that the condition has become true) is empty. 287 288 line 6: "... can be transformed into external scheduling..." -- OK, but give some motivation. 289 290 p20: line 6: "mechnaism" 291 292 lines 16--20: this is dense and can probably only be made clear with an example 293 294 p21 line 21: clarify that nested monitor deadlock was describe earlier (in 5.2). (Is the repetition necessary?) 295 296 line 27: "locks, and by extension monitors" -- this is true but the "by extension" argument is faulty. It is perfectly possible to use locks as a primitive and build a compositional mechanism out of them, e.g. transactions. 297 298 p22 line 2: should say "restructured" 299 300 line 33: "Implementing a fast subset check..." -- make clear that the following section explains how to do this. Restructuring the sections themselves could do this, or noting in the text. 301 302 p23: line 3: "dynamic member adding, eg, JavaScript" -- needs to say "as permitted in JavaScript", and "dynamically adding members" is stylistically better 303 304 p23: line 18: "urgent stack" -- back-reference to where this was explained before 305 306 p24 line 7: I did not understand what was more "direct" about "direct communication". Also, what is a "passive monitor" -- just a monitor, given that monitors are passive by design? 307 308 line 14 / section 5.9: this table was useful and it (or something like it) could be used much earlier on to set the structure of the rest of the paper. The explanation at present is too brief, e.g. I did not really understand the point about cases 7 and 8. 309 310 p25 line 2: instead of casually dropping in a terse explanation for the newly intrdouced term "virtual processor", introduce it properly. Presumably the point is to give a less ambiguous meaning to "thread" by reserving it only for C\/'s green threads. 311 312 Table 1: what does "No / Yes" mean? 313 314 p26 line 15: "transforms user threads into fibres" -- a reference is needed to explain what "fibres" means... guessing it's in the sense of Adya et al. 315 316 line 20: "Microsoft runtime" -- means Windows? 317 318 lines 21--26: don't say "interrupt" to mean "signal", especially not without clear introduction. You can use "POSIX signal" to disambiguate from condition variables' "signal". 319 320 p27 line 3: "frequency is usually long" -- that's a "time period" or "interval", not a frequency 321 322 line 5: the lengthy quotation is not really necessary; just paraphrase the first sentence and move on. 323 324 line 20: "to verify the implementation" -- I don't think that means what is intended 325 326 Tables in section 7 -- too many significant figures. How many overall runs are described? What is N in each case? 327 328 p29 line 2: "to eliminate this cost" -- arguably confusing since nowadays on commodity CPUs most of the benefits of inlining are not to do with call overheads, but from later optimizations enabled as a consequence of the inlining 329 330 line 41: "a hierarchy" -- are they a hierarchy? If so, this could be explained earlier. Also, to say these make up "an integrated set... of control-flow features" verges on the tautologous. 331 332 p30 line 15: "a common case being web servers and XaaS" -- that's two cases 333 334 335 Reviewing: 3 336 337 Comments to the Author 338 # Cforall review 339 340 Overall, I quite enjoyed reading the paper. Cforall has some very interesting ideas. I did have some suggestions that I think would be helpful before final publication. I also left notes on various parts of the paper that I find confusing when reading, in hopes that it may be useful to you. 341 342 ## Summary 343 344 * Expand on the motivations for including both generator and coroutines, vs trying to build one atop the other 345 * Expand on the motivations for having Why both symmetric and asymettric coroutines? 346 * Comparison to async-await model adopted by other languages 347 * C#, JS 348 * Rust and its async/await model 349 * Consider performance comparisons against node.js and Rust frameworks 350 * Discuss performance of monitors vs finer-grained memory models and atomic operations found in other languages 351 * Why both internal/external scheduling for synchronization? 352 353 ## Generator/coroutines 354 355 In general, this section was clear, but I thought it would be useful to provide a somewhat deeper look into why Cforall opted for the particular combination of features that it offers. I see three main differences from other languages: 356 357 * Generators are not exposed as a "function" that returns a generator object, but rather as a kind of struct, with communication happening via mutable state instead of "return values". That is, the generator must be manually resumed and (if I understood) it is expected to store values that can then later be read (perhaps via methods), instead of having a `yield <Expr>` statement that yields up a value explicitly. 358 * Both "symmetric" and "asymmetric" generators are supported, instead of only asymmetric. 359 * Coroutines (multi-frame generators) are an explicit mechanism. 360 361 In most other languages, coroutines are rather built by layering single-frame generators atop one another (e.g., using a mechanism like async-await), and symmetric coroutines are basically not supported. I'd like to see a bit more justification for Cforall including all the above mechanisms -- it seemed like symmetric coroutines were a useful building block for some of the user-space threading and custom scheduler mechanisms that were briefly mentioned later in the paper. 362 363 In the discussion of coroutines, I would have expected a bit more of a comparison to the async-await mechanism offered in other languages. Certainly the semantics of async-await in JavaScript implies significantly more overhead (because each async fn is a distinct heap object). [Rust's approach avoids this overhead][zc], however, and might be worthy of a comparison (see the Performance section). 364 365 ## Locks and threading 366 367 ### Comparison to atomics overlooks performance 368 369 There are several sections in the paper that compare against atomics -- for example, on page 15, the paper shows a simple monitor that encapsulates an integer and compares that to C++ atomics. Later, the paper compares the simplicity of monitors against the `volatile` quantifier from Java. The conclusion in section 8 also revisits this point. 370 371 While I agree that monitors are simpler, they are obviously also significantly different from a performance perspective -- the paper doesn't seem to address this at all. It's plausible that (e.g.) the `Aint` monitor type described in the paper can be compiled and mapped to the specialized instructions offered by hardware, but I didn't see any mention of how this would be done. There is also no mention of the more nuanced memory ordering relations offered by C++11 and how one might achieve similar performance characteristics in Cforall (perhaps the answer is that one simply doesn't need to; I think that's defensible, but worth stating explicitly). 372 373 ### Justification for external scheduling feels lacking 374 375 Cforall includes both internal and external scheduling; I found the explanation for the external scheduling mechanism to be lacking in justification. Why include both mechanisms when most languages seem to make do with only internal scheduling? It would be useful to show some scenarios where external scheduling is truly more powerful. 376 377 I would have liked to see some more discussion of external scheduling and how it interacts with software engineering best practices. It seems somewhat similar to AOP in certain regards. It seems to add a bit of "extra semantics" to monitor methods, in that any method may now also become a kind of synchronization point. The "open-ended" nature of this feels like it could easily lead to subtle bugs, particularly when code refactoring occurs (which may e.g. split an existing method into two). This seems particularly true if external scheduling can occur across compilation units -- the paper suggested that this is true, but I wasn't entirely clear. 378 379 I would have also appreciated a few more details on how external scheduling is implemented. It seems to me that there must be some sort of "hooks" on mutex methods so that they can detect whether some other function is waiting on them and awaken those blocked threads. I'm not sure how such hooks are inserted, particularly across compilation units. The material in Section 5.6 didn't quite clarify the matter for me. For example, it left me somewhat confused about whether the `f` and `g` functions declared were meant to be local to a translation unit, or shared with other unit. 380 381 ### Presentation of monitors is somewhat confusing 382 383 I found myself confused fairly often in the section on monitors. I'm just going to leave some notes here on places that I got confused in how that it could be useful to you as feedback on writing that might want to be clarified. 384 385 To start, I did not realize that the `mutex_opt` notation was a keyword, I thought it was a type annotation. I think this could be called out more explicitly. 386 387 Later, in section 5.2, the paper discusses `nomutex` annotations, which initially threw me, as they had not been introduced (now I realize that this paragraph is there to justify why there is no such keyword). The paragraph might be rearranged to make that clearer, perhaps by leading with the choice that Cforall made. 388 389 On page 17, the paper states that "acquiring multiple monitors is safe from deadlock", but this could be stated a bit more precisely: acquiring multiple monitors in a bulk-acquire is safe from deadlock (deadlock can still result from nested acquires). 390 391 On page 18, the paper states that wait states do not have to be enclosed in loops, as there is no concern of barging. This seems true but there are also other reasons to use loops (e.g., if there are multiple reasons to notify on the same condition). Thus the statement initially surprised me, as barging is only one of many reasons that I typically employ loops around waits. 392 393 I did not understand the diagram in Figure 12 for some time. Initially, I thought that it was generic to all monitors, and I could not understand the state space. It was only later that I realized it was specific to your example. Updating the caption from "Monitor scheduling to "Monitor scheduling in the example from Fig 13" might have helped me quite a bit. 394 395 I spent quite some time reading the boy/girl dating example (\*) and I admit I found it somewhat confusing. For example, I couldn't tell whether there were supposed to be many "girl" threads executing at once, or if there was only supposed to be one girl and one boy thread executing in a loop. Are the girl/boy threads supposed to invoke the girl/boy methods or vice versa? Surely there is some easier way to set this up? I believe that when reading the paper I convinced myself of how it was supposed to be working, but I'm writing this review some days later, and I find myself confused all over again and not able to easily figure it out. 396 397 (\*) as an aside, I would consider modifying the example to some other form of matching, like customers and support personnel. 398 399 ## Related work 400 401 The paper offered a number of comparisons to Go, C#, Scala, and so forth, but seems to have overlooked another recent language, Rust. In many ways, Rust seems to be closest in philosophy to Cforall, so it seems like an odd omission. I already mentioned above that Rust is in the process of shipping [async-await syntax][aa], which is definitely an alternative to the generator/coroutine approach in Cforall (though one with clear pros/cons). 402 403 ## Performance 404 405 In the performance section in particular, you might consider comparing against some of the Rust web servers and threading systems. For example, actix is top of the [single query TechEmpower Framework benchmarks], and tokio is near the top of the [plainthreading benchmarks][pt] (hyper, the top, is more of an HTTP framework, though it is also written in Rust). It would seem worth trying to compare their "context switching" costs as well -- I believe both actix and tokio have a notion of threads that could be readily compared. 406 407 Another addition that might be worth considering is to compare against node.js promises, although I think the comparison to process creation is not as clean. 408 409 That said, I think that the performance comparison is not a big focus of the paper, so it may not be necessary to add anything to it. 410 411 ## Authorship of this review 412 413 I'm going to sign this review. This review was authored by Nicholas D. Matsakis. In the intrerest of full disclosure, I'm heavily involved in the Rust project, although I dont' think that influenced this review in particular. Feel free to reach out to me for clarifying questions. 414 415 ## Links 416 417 [aa]: https://blog.rust-lang.org/2019/09/30/Async-await-hits-beta.html 418 [zc]: https://aturon.github.io/blog/2016/08/11/futures/ 419 [sq]: https://www.techempower.com/benchmarks/#section=data-r18&hw=ph&test=db 420 [pt]: https://www.techempower.com/benchmarks/#section=data-r18&hw=ph&test=plaintext 421 422 423 424 Subject: Re: manuscript SPE-19-0219 425 To: "Peter A. Buhr" <pabuhr@uwaterloo.ca> 426 From: Richard Jones <R.E.Jones@kent.ac.uk> 427 Date: Tue, 12 Nov 2019 22:43:55 +0000 428 429 Dear Dr Buhr 430 431 Your should have received a decision letter on this today. I am sorry that this 432 has taken so long. Unfortunately SP&E receives a lot of submissions and getting 433 reviewers is a perennial problem. 434 435 Regards 436 Richard 437 438 Peter A. Buhr wrote on 11/11/2019 13:10: 439 > 26-Jun-2019 440 > Your manuscript entitled "Advanced Control-flow and Concurrency in Cforall" 441 > has been received by Software: Practice and Experience. It will be given 442 > full consideration for publication in the journal. 443 > 444 > Hi, it has been over 4 months since submission of our manuscript SPE-19-0219 445 > with no response. 446 > 447 > Currently, I am refereeing a paper for IEEE that already cites our prior SP&E 448 > paper and the Master's thesis forming the bases of the SP&E paper under 449 > review. Hence our work is apropos and we want to get it disseminates as soon as 450 > possible. 451 > 452 > [3] A. Moss, R. Schluntz, and P. A. Buhr, "Cforall: Adding modern programming 453 > language features to C," Software - Practice and Experience, vol. 48, 454 > no. 12, pp. 2111-2146, 2018. 455 > 456 > [4] T. Delisle, "Concurrency in C for all," Master's thesis, University of 457 > Waterloo, 2018. [Online]. Available: 458 > https://uwspace.uwaterloo.ca/bitstream/handle/10012/12888 459 460 461 462 Date: Mon, 13 Jan 2020 05:33:15 +0000 463 From: Richard Jones <onbehalfof@manuscriptcentral.com> 464 Reply-To: R.E.Jones@kent.ac.uk 465 To: pabuhr@uwaterloo.ca 466 Subject: Revision reminder - SPE-19-0219 467 468 13-Jan-2020 469 Dear Dr Buhr 470 SPE-19-0219 471 472 This is a reminder that your opportunity to revise and re-submit your 473 manuscript will expire 28 days from now. If you require more time please 474 contact me directly and I may grant an extension to this deadline, otherwise 475 the option to submit a revision online, will not be available. 476 477 I look forward to receiving your revision. 478 479 Sincerely, 480 481 Prof. Richard Jones 482 Editor, Software: Practice and Experience 483 https://mc.manuscriptcentral.com/spe 484 485 486 487 Date: Wed, 5 Feb 2020 04:22:18 +0000 488 From: Aaron Thomas <onbehalfof@manuscriptcentral.com> 489 Reply-To: speoffice@wiley.com 490 To: tdelisle@uwaterloo.ca, pabuhr@uwaterloo.ca 491 Subject: SPE-19-0219.R1 successfully submitted 492 493 04-Feb-2020 494 495 Dear Dr Buhr, 496 497 Your manuscript entitled "Advanced Control-flow and Concurrency in Cforall" has 498 been successfully submitted online and is presently being given full 499 consideration for publication in Software: Practice and Experience. 500 501 Your manuscript number is SPE-19-0219.R1. Please mention this number in all 502 future correspondence regarding this submission. 503 504 You can view the status of your manuscript at any time by checking your Author 505 Center after logging into https://mc.manuscriptcentral.com/spe. If you have 506 difficulty using this site, please click the 'Get Help Now' link at the top 507 right corner of the site. 508 509 Thank you for submitting your manuscript to Software: Practice and Experience. 510 511 Sincerely, 512 Software: Practice and Experience Editorial Office 513 -
driver/cfa.cc
r41efd33 r04e6f93 411 411 args[nargs++] = "-lcfathread"; 412 412 args[nargs++] = "-Wl,--pop-state"; 413 args[nargs++] = "-Wl,--push-state,--no-as-needed"; 413 414 args[nargs++] = "-lcfa"; 415 args[nargs++] = "-Wl,--pop-state"; 414 416 args[nargs++] = "-pthread"; 415 417 args[nargs++] = "-ldl"; -
libcfa/src/bits/containers.hfa
r41efd33 r04e6f93 146 146 static inline forall( dtype T | is_node(T) ) { 147 147 void ?{}( __queue(T) & this ) with( this ) { 148 head{ 0p };148 head{ 1p }; 149 149 tail{ &head }; 150 verify(*tail == 1p); 150 151 } 151 152 152 153 void append( __queue(T) & this, T * val ) with( this ) { 153 154 verify(tail != 0p); 155 verify(*tail == 1p); 154 156 *tail = val; 155 157 tail = &get_next( *val ); 158 *tail = 1p; 156 159 } 157 160 158 161 T * pop_head( __queue(T) & this ) { 162 verify(*this.tail == 1p); 159 163 T * head = this.head; 160 if( head ) {164 if( head != 1p ) { 161 165 this.head = get_next( *head ); 162 if( !get_next( *head )) {166 if( get_next( *head ) == 1p ) { 163 167 this.tail = &this.head; 164 168 } 165 169 get_next( *head ) = 0p; 166 } 167 return head; 170 verify(*this.tail == 1p); 171 return head; 172 } 173 verify(*this.tail == 1p); 174 return 0p; 168 175 } 169 176 … … 180 187 get_next( *val ) = 0p; 181 188 182 verify( (head == 0p) == (&head == tail) );183 verify( *tail == 0p );189 verify( (head == 1p) == (&head == tail) ); 190 verify( *tail == 1p ); 184 191 return val; 185 192 } -
libcfa/src/bits/locks.hfa
r41efd33 r04e6f93 60 60 } 61 61 62 extern void yield( unsigned int );63 64 62 static inline void ?{}( __spinlock_t & this ) { 65 63 this.lock = 0; … … 68 66 // Lock the spinlock, return false if already acquired 69 67 static inline bool try_lock ( __spinlock_t & this __cfaabi_dbg_ctx_param2 ) { 68 disable_interrupts(); 70 69 bool result = (this.lock == 0) && (__atomic_test_and_set( &this.lock, __ATOMIC_ACQUIRE ) == 0); 71 70 if( result ) { 72 disable_interrupts();73 71 __cfaabi_dbg_record( this, caller ); 72 } else { 73 enable_interrupts_noPoll(); 74 74 } 75 75 return result; … … 83 83 #endif 84 84 85 disable_interrupts(); 85 86 for ( unsigned int i = 1;; i += 1 ) { 86 87 if ( (this.lock == 0) && (__atomic_test_and_set( &this.lock, __ATOMIC_ACQUIRE ) == 0) ) break; … … 98 99 #endif 99 100 } 100 disable_interrupts();101 101 __cfaabi_dbg_record( this, caller ); 102 102 } 103 103 104 104 static inline void unlock( __spinlock_t & this ) { 105 __atomic_clear( &this.lock, __ATOMIC_RELEASE ); 105 106 enable_interrupts_noPoll(); 106 __atomic_clear( &this.lock, __ATOMIC_RELEASE );107 107 } 108 108 -
libcfa/src/concurrency/CtxSwitch-arm.S
r41efd33 r04e6f93 13 13 .text 14 14 .align 2 15 .global CtxSwitch16 .type CtxSwitch, %function15 .global __cfactx_switch 16 .type __cfactx_switch, %function 17 17 18 CtxSwitch:18 __cfactx_switch: 19 19 @ save callee-saved registers: r4-r8, r10, r11, r13(sp) (plus r9 depending on platform specification) 20 20 @ I've seen reference to 31 registers on 64-bit, if this is the case, more need to be saved … … 52 52 mov r15, r14 53 53 #endif // R9_SPECIAL 54 54 55 55 .text 56 56 .align 2 57 .global CtxInvokeStub58 .type CtxInvokeStub, %function57 .global __cfactx_invoke_stub 58 .type __cfactx_invoke_stub, %function 59 59 60 CtxInvokeStub:60 __cfactx_invoke_stub: 61 61 ldmfd r13!, {r0-r1} 62 62 mov r15, r1 -
libcfa/src/concurrency/CtxSwitch-i386.S
r41efd33 r04e6f93 43 43 .text 44 44 .align 2 45 .globl CtxSwitch46 .type CtxSwitch, @function47 CtxSwitch:45 .globl __cfactx_switch 46 .type __cfactx_switch, @function 47 __cfactx_switch: 48 48 49 49 // Copy the "from" context argument from the stack to register eax … … 83 83 84 84 ret 85 .size CtxSwitch, .-CtxSwitch85 .size __cfactx_switch, .-__cfactx_switch 86 86 87 87 // Local Variables: // -
libcfa/src/concurrency/CtxSwitch-x86_64.S
r41efd33 r04e6f93 44 44 .text 45 45 .align 2 46 .globl CtxSwitch47 .type CtxSwitch, @function48 CtxSwitch:46 .globl __cfactx_switch 47 .type __cfactx_switch, @function 48 __cfactx_switch: 49 49 50 50 // Save volatile registers on the stack. … … 77 77 78 78 ret 79 .size CtxSwitch, .-CtxSwitch79 .size __cfactx_switch, .-__cfactx_switch 80 80 81 81 //----------------------------------------------------------------------------- … … 83 83 .text 84 84 .align 2 85 .globl CtxInvokeStub86 .type CtxInvokeStub, @function87 CtxInvokeStub:85 .globl __cfactx_invoke_stub 86 .type __cfactx_invoke_stub, @function 87 __cfactx_invoke_stub: 88 88 movq %rbx, %rdi 89 89 movq %r12, %rsi 90 90 jmp *%r13 91 .size CtxInvokeStub, .-CtxInvokeStub91 .size __cfactx_invoke_stub, .-__cfactx_invoke_stub 92 92 93 93 // Local Variables: // -
libcfa/src/concurrency/alarm.cfa
r41efd33 r04e6f93 47 47 //============================================================================================= 48 48 49 void ?{}( alarm_node_t & this, thread_desc* thrd, Time alarm, Duration period ) with( this ) {49 void ?{}( alarm_node_t & this, $thread * thrd, Time alarm, Duration period ) with( this ) { 50 50 this.thrd = thrd; 51 51 this.alarm = alarm; -
libcfa/src/concurrency/alarm.hfa
r41efd33 r04e6f93 23 23 #include "time.hfa" 24 24 25 struct thread_desc;25 struct $thread; 26 26 struct processor; 27 27 … … 43 43 44 44 union { 45 thread_desc* thrd; // thrd who created event45 $thread * thrd; // thrd who created event 46 46 processor * proc; // proc who created event 47 47 }; … … 53 53 typedef alarm_node_t ** __alarm_it_t; 54 54 55 void ?{}( alarm_node_t & this, thread_desc* thrd, Time alarm, Duration period );55 void ?{}( alarm_node_t & this, $thread * thrd, Time alarm, Duration period ); 56 56 void ?{}( alarm_node_t & this, processor * proc, Time alarm, Duration period ); 57 57 void ^?{}( alarm_node_t & this ); -
libcfa/src/concurrency/coroutine.cfa
r41efd33 r04e6f93 37 37 38 38 extern "C" { 39 void _CtxCoroutine_Unwind(struct _Unwind_Exception * storage, struct coroutine_desc*) __attribute__ ((__noreturn__));39 void _CtxCoroutine_Unwind(struct _Unwind_Exception * storage, struct $coroutine *) __attribute__ ((__noreturn__)); 40 40 static void _CtxCoroutine_UnwindCleanup(_Unwind_Reason_Code, struct _Unwind_Exception *) __attribute__ ((__noreturn__)); 41 41 static void _CtxCoroutine_UnwindCleanup(_Unwind_Reason_Code, struct _Unwind_Exception *) { … … 89 89 } 90 90 91 void ?{}( coroutine_desc& this, const char name[], void * storage, size_t storageSize ) with( this ) {91 void ?{}( $coroutine & this, const char name[], void * storage, size_t storageSize ) with( this ) { 92 92 (this.context){0p, 0p}; 93 93 (this.stack){storage, storageSize}; … … 99 99 } 100 100 101 void ^?{}( coroutine_desc& this) {101 void ^?{}($coroutine& this) { 102 102 if(this.state != Halted && this.state != Start && this.state != Primed) { 103 coroutine_desc* src = TL_GET( this_thread )->curr_cor;104 coroutine_desc* dst = &this;103 $coroutine * src = TL_GET( this_thread )->curr_cor; 104 $coroutine * dst = &this; 105 105 106 106 struct _Unwind_Exception storage; … … 115 115 } 116 116 117 CoroutineCtxSwitch( src, dst );117 $ctx_switch( src, dst ); 118 118 } 119 119 } … … 123 123 forall(dtype T | is_coroutine(T)) 124 124 void prime(T& cor) { 125 coroutine_desc* this = get_coroutine(cor);125 $coroutine* this = get_coroutine(cor); 126 126 assert(this->state == Start); 127 127 … … 187 187 // is not inline (We can't inline Cforall in C) 188 188 extern "C" { 189 void __ leave_coroutine( struct coroutine_desc* src ) {190 coroutine_desc* starter = src->cancellation != 0 ? src->last : src->starter;189 void __cfactx_cor_leave( struct $coroutine * src ) { 190 $coroutine * starter = src->cancellation != 0 ? src->last : src->starter; 191 191 192 192 src->state = Halted; … … 201 201 src->name, src, starter->name, starter ); 202 202 203 CoroutineCtxSwitch( src, starter );204 } 205 206 struct coroutine_desc * __finish_coroutine(void) {207 struct coroutine_desc* cor = kernelTLS.this_thread->curr_cor;203 $ctx_switch( src, starter ); 204 } 205 206 struct $coroutine * __cfactx_cor_finish(void) { 207 struct $coroutine * cor = kernelTLS.this_thread->curr_cor; 208 208 209 209 if(cor->state == Primed) { -
libcfa/src/concurrency/coroutine.hfa
r41efd33 r04e6f93 25 25 trait is_coroutine(dtype T) { 26 26 void main(T & this); 27 coroutine_desc* get_coroutine(T & this);27 $coroutine * get_coroutine(T & this); 28 28 }; 29 29 30 #define DECL_COROUTINE(X) static inline coroutine_desc* get_coroutine(X& this) { return &this.__cor; } void main(X& this)30 #define DECL_COROUTINE(X) static inline $coroutine* get_coroutine(X& this) { return &this.__cor; } void main(X& this) 31 31 32 32 //----------------------------------------------------------------------------- … … 35 35 // void ^?{}( coStack_t & this ); 36 36 37 void ?{}( coroutine_desc& this, const char name[], void * storage, size_t storageSize );38 void ^?{}( coroutine_desc& this );37 void ?{}( $coroutine & this, const char name[], void * storage, size_t storageSize ); 38 void ^?{}( $coroutine & this ); 39 39 40 static inline void ?{}( coroutine_desc& this) { this{ "Anonymous Coroutine", 0p, 0 }; }41 static inline void ?{}( coroutine_desc& this, size_t stackSize) { this{ "Anonymous Coroutine", 0p, stackSize }; }42 static inline void ?{}( coroutine_desc& this, void * storage, size_t storageSize ) { this{ "Anonymous Coroutine", storage, storageSize }; }43 static inline void ?{}( coroutine_desc& this, const char name[]) { this{ name, 0p, 0 }; }44 static inline void ?{}( coroutine_desc& this, const char name[], size_t stackSize ) { this{ name, 0p, stackSize }; }40 static inline void ?{}( $coroutine & this) { this{ "Anonymous Coroutine", 0p, 0 }; } 41 static inline void ?{}( $coroutine & this, size_t stackSize) { this{ "Anonymous Coroutine", 0p, stackSize }; } 42 static inline void ?{}( $coroutine & this, void * storage, size_t storageSize ) { this{ "Anonymous Coroutine", storage, storageSize }; } 43 static inline void ?{}( $coroutine & this, const char name[]) { this{ name, 0p, 0 }; } 44 static inline void ?{}( $coroutine & this, const char name[], size_t stackSize ) { this{ name, 0p, stackSize }; } 45 45 46 46 //----------------------------------------------------------------------------- … … 54 54 void prime(T & cor); 55 55 56 static inline struct coroutine_desc* active_coroutine() { return TL_GET( this_thread )->curr_cor; }56 static inline struct $coroutine * active_coroutine() { return TL_GET( this_thread )->curr_cor; } 57 57 58 58 //----------------------------------------------------------------------------- … … 61 61 // Start coroutine routines 62 62 extern "C" { 63 void CtxInvokeCoroutine(void (*main)(void *), void * this);63 void __cfactx_invoke_coroutine(void (*main)(void *), void * this); 64 64 65 65 forall(dtype T) 66 void CtxStart(void (*main)(T &), struct coroutine_desc* cor, T & this, void (*invoke)(void (*main)(void *), void *));66 void __cfactx_start(void (*main)(T &), struct $coroutine * cor, T & this, void (*invoke)(void (*main)(void *), void *)); 67 67 68 extern void _ CtxCoroutine_Unwind(struct _Unwind_Exception * storage, struct coroutine_desc*) __attribute__ ((__noreturn__));68 extern void __cfactx_coroutine_unwind(struct _Unwind_Exception * storage, struct $coroutine *) __attribute__ ((__noreturn__)); 69 69 70 extern void CtxSwitch( struct __stack_context_t * from, struct __stack_context_t * to ) asm ("CtxSwitch");70 extern void __cfactx_switch( struct __stack_context_t * from, struct __stack_context_t * to ) asm ("__cfactx_switch"); 71 71 } 72 72 73 73 // Private wrappers for context switch and stack creation 74 74 // Wrapper for co 75 static inline void CoroutineCtxSwitch(coroutine_desc* src, coroutine_desc* dst) {75 static inline void $ctx_switch( $coroutine * src, $coroutine * dst ) __attribute__((nonnull (1, 2))) { 76 76 // set state of current coroutine to inactive 77 77 src->state = src->state == Halted ? Halted : Inactive; … … 82 82 // context switch to specified coroutine 83 83 verify( dst->context.SP ); 84 CtxSwitch( &src->context, &dst->context );85 // when CtxSwitch returns we are back in the src coroutine84 __cfactx_switch( &src->context, &dst->context ); 85 // when __cfactx_switch returns we are back in the src coroutine 86 86 87 87 // set state of new coroutine to active … … 89 89 90 90 if( unlikely(src->cancellation != 0p) ) { 91 _ CtxCoroutine_Unwind(src->cancellation, src);91 __cfactx_coroutine_unwind(src->cancellation, src); 92 92 } 93 93 } … … 102 102 // will also migrate which means this value will 103 103 // stay in syn with the TLS 104 coroutine_desc* src = TL_GET( this_thread )->curr_cor;104 $coroutine * src = TL_GET( this_thread )->curr_cor; 105 105 106 106 assertf( src->last != 0, … … 113 113 src->name, src, src->last->name, src->last ); 114 114 115 CoroutineCtxSwitch( src, src->last );115 $ctx_switch( src, src->last ); 116 116 } 117 117 … … 124 124 // will also migrate which means this value will 125 125 // stay in syn with the TLS 126 coroutine_desc* src = TL_GET( this_thread )->curr_cor;127 coroutine_desc* dst = get_coroutine(cor);126 $coroutine * src = TL_GET( this_thread )->curr_cor; 127 $coroutine * dst = get_coroutine(cor); 128 128 129 129 if( unlikely(dst->context.SP == 0p) ) { 130 130 TL_GET( this_thread )->curr_cor = dst; 131 131 __stack_prepare(&dst->stack, 65000); 132 CtxStart(main, dst, cor, CtxInvokeCoroutine);132 __cfactx_start(main, dst, cor, __cfactx_invoke_coroutine); 133 133 TL_GET( this_thread )->curr_cor = src; 134 134 } … … 147 147 148 148 // always done for performance testing 149 CoroutineCtxSwitch( src, dst );149 $ctx_switch( src, dst ); 150 150 151 151 return cor; 152 152 } 153 153 154 static inline void resume( coroutine_desc * dst) {154 static inline void resume( $coroutine * dst ) __attribute__((nonnull (1))) { 155 155 // optimization : read TLS once and reuse it 156 156 // Safety note: this is preemption safe since if … … 158 158 // will also migrate which means this value will 159 159 // stay in syn with the TLS 160 coroutine_desc* src = TL_GET( this_thread )->curr_cor;160 $coroutine * src = TL_GET( this_thread )->curr_cor; 161 161 162 162 // not resuming self ? … … 172 172 173 173 // always done for performance testing 174 CoroutineCtxSwitch( src, dst );174 $ctx_switch( src, dst ); 175 175 } 176 176 -
libcfa/src/concurrency/invoke.c
r41efd33 r04e6f93 29 29 // Called from the kernel when starting a coroutine or task so must switch back to user mode. 30 30 31 extern void __leave_coroutine ( struct coroutine_desc * ); 32 extern struct coroutine_desc * __finish_coroutine(void); 33 extern void __leave_thread_monitor(); 31 extern struct $coroutine * __cfactx_cor_finish(void); 32 extern void __cfactx_cor_leave ( struct $coroutine * ); 33 extern void __cfactx_thrd_leave(); 34 34 35 extern void disable_interrupts() OPTIONAL_THREAD; 35 36 extern void enable_interrupts( __cfaabi_dbg_ctx_param ); 36 37 37 void CtxInvokeCoroutine(38 void __cfactx_invoke_coroutine( 38 39 void (*main)(void *), 39 40 void *this 40 41 ) { 41 42 // Finish setting up the coroutine by setting its state 42 struct coroutine_desc * cor = __finish_coroutine();43 struct $coroutine * cor = __cfactx_cor_finish(); 43 44 44 45 // Call the main of the coroutine … … 46 47 47 48 //Final suspend, should never return 48 __ leave_coroutine( cor );49 __cfactx_cor_leave( cor ); 49 50 __cabi_abort( "Resumed dead coroutine" ); 50 51 } 51 52 52 static _Unwind_Reason_Code _ CtxCoroutine_UnwindStop(53 static _Unwind_Reason_Code __cfactx_coroutine_unwindstop( 53 54 __attribute((__unused__)) int version, 54 55 _Unwind_Action actions, … … 61 62 // We finished unwinding the coroutine, 62 63 // leave it 63 __ leave_coroutine( param );64 __cfactx_cor_leave( param ); 64 65 __cabi_abort( "Resumed dead coroutine" ); 65 66 } … … 69 70 } 70 71 71 void _ CtxCoroutine_Unwind(struct _Unwind_Exception * storage, struct coroutine_desc* cor) __attribute__ ((__noreturn__));72 void _ CtxCoroutine_Unwind(struct _Unwind_Exception * storage, struct coroutine_desc* cor) {73 _Unwind_Reason_Code ret = _Unwind_ForcedUnwind( storage, _ CtxCoroutine_UnwindStop, cor );72 void __cfactx_coroutine_unwind(struct _Unwind_Exception * storage, struct $coroutine * cor) __attribute__ ((__noreturn__)); 73 void __cfactx_coroutine_unwind(struct _Unwind_Exception * storage, struct $coroutine * cor) { 74 _Unwind_Reason_Code ret = _Unwind_ForcedUnwind( storage, __cfactx_coroutine_unwindstop, cor ); 74 75 printf("UNWIND ERROR %d after force unwind\n", ret); 75 76 abort(); 76 77 } 77 78 78 void CtxInvokeThread(79 void __cfactx_invoke_thread( 79 80 void (*main)(void *), 80 81 void *this … … 93 94 // The order of these 4 operations is very important 94 95 //Final suspend, should never return 95 __ leave_thread_monitor();96 __cfactx_thrd_leave(); 96 97 __cabi_abort( "Resumed dead thread" ); 97 98 } 98 99 99 void CtxStart(100 void __cfactx_start( 100 101 void (*main)(void *), 101 struct coroutine_desc* cor,102 struct $coroutine * cor, 102 103 void *this, 103 104 void (*invoke)(void *) … … 139 140 140 141 fs->dummyReturn = NULL; 141 fs->rturn = CtxInvokeStub;142 fs->rturn = __cfactx_invoke_stub; 142 143 fs->fixedRegisters[0] = main; 143 144 fs->fixedRegisters[1] = this; … … 157 158 struct FakeStack *fs = (struct FakeStack *)cor->context.SP; 158 159 159 fs->intRegs[8] = CtxInvokeStub;160 fs->intRegs[8] = __cfactx_invoke_stub; 160 161 fs->arg[0] = this; 161 162 fs->arg[1] = invoke; -
libcfa/src/concurrency/invoke.h
r41efd33 r04e6f93 47 47 extern "Cforall" { 48 48 extern __attribute__((aligned(128))) thread_local struct KernelThreadData { 49 struct thread_desc* volatile this_thread;49 struct $thread * volatile this_thread; 50 50 struct processor * volatile this_processor; 51 51 … … 92 92 }; 93 93 94 enum coroutine_state { Halted, Start, Inactive, Active, Primed }; 95 96 struct coroutine_desc { 97 // context that is switch during a CtxSwitch 94 enum coroutine_state { Halted, Start, Primed, Inactive, Active, Rerun }; 95 enum __Preemption_Reason { __NO_PREEMPTION, __ALARM_PREEMPTION, __POLL_PREEMPTION, __MANUAL_PREEMPTION }; 96 97 struct $coroutine { 98 // context that is switch during a __cfactx_switch 98 99 struct __stack_context_t context; 99 100 … … 108 109 109 110 // first coroutine to resume this one 110 struct coroutine_desc* starter;111 struct $coroutine * starter; 111 112 112 113 // last coroutine to resume this one 113 struct coroutine_desc* last;114 struct $coroutine * last; 114 115 115 116 // If non-null stack must be unwound with this exception … … 127 128 }; 128 129 129 struct monitor_desc{130 struct $monitor { 130 131 // spinlock to protect internal data 131 132 struct __spinlock_t lock; 132 133 133 134 // current owner of the monitor 134 struct thread_desc* owner;135 struct $thread * owner; 135 136 136 137 // queue of threads that are blocked waiting for the monitor 137 __queue_t(struct thread_desc) entry_queue;138 __queue_t(struct $thread) entry_queue; 138 139 139 140 // stack of conditions to run next once we exit the monitor … … 152 153 struct __monitor_group_t { 153 154 // currently held monitors 154 __cfa_anonymous_object( __small_array_t( monitor_desc*) );155 __cfa_anonymous_object( __small_array_t($monitor*) ); 155 156 156 157 // last function that acquired monitors … … 158 159 }; 159 160 160 struct thread_desc{161 struct $thread { 161 162 // Core threading fields 162 // context that is switch during a CtxSwitch163 // context that is switch during a __cfactx_switch 163 164 struct __stack_context_t context; 164 165 165 166 // current execution status for coroutine 166 enum coroutine_state state; 167 volatile int state; 168 enum __Preemption_Reason preempted; 167 169 168 170 //SKULLDUGGERY errno is not save in the thread data structure because returnToKernel appears to be the only function to require saving and restoring it 169 171 170 172 // coroutine body used to store context 171 struct coroutine_descself_cor;173 struct $coroutine self_cor; 172 174 173 175 // current active context 174 struct coroutine_desc* curr_cor;176 struct $coroutine * curr_cor; 175 177 176 178 // monitor body used for mutual exclusion 177 struct monitor_descself_mon;179 struct $monitor self_mon; 178 180 179 181 // pointer to monitor with sufficient lifetime for current monitors 180 struct monitor_desc* self_mon_p;182 struct $monitor * self_mon_p; 181 183 182 184 // pointer to the cluster on which the thread is running … … 188 190 // Link lists fields 189 191 // instrusive link field for threads 190 struct thread_desc* next;192 struct $thread * next; 191 193 192 194 struct { 193 struct thread_desc* next;194 struct thread_desc* prev;195 struct $thread * next; 196 struct $thread * prev; 195 197 } node; 196 198 }; … … 198 200 #ifdef __cforall 199 201 extern "Cforall" { 200 static inline thread_desc *& get_next( thread_desc & this) {202 static inline $thread *& get_next( $thread & this ) __attribute__((const)) { 201 203 return this.next; 202 204 } 203 205 204 static inline [ thread_desc *&, thread_desc *& ] __get( thread_desc & this) {206 static inline [$thread *&, $thread *& ] __get( $thread & this ) __attribute__((const)) { 205 207 return this.node.[next, prev]; 206 208 } … … 212 214 } 213 215 214 static inline void ?{}(__monitor_group_t & this, struct monitor_desc** data, __lock_size_t size, fptr_t func) {216 static inline void ?{}(__monitor_group_t & this, struct $monitor ** data, __lock_size_t size, fptr_t func) { 215 217 (this.data){data}; 216 218 (this.size){size}; … … 218 220 } 219 221 220 static inline bool ?==?( const __monitor_group_t & lhs, const __monitor_group_t & rhs ) {222 static inline bool ?==?( const __monitor_group_t & lhs, const __monitor_group_t & rhs ) __attribute__((const)) { 221 223 if( (lhs.data != 0) != (rhs.data != 0) ) return false; 222 224 if( lhs.size != rhs.size ) return false; … … 252 254 253 255 // assembler routines that performs the context switch 254 extern void CtxInvokeStub( void );255 extern void CtxSwitch( struct __stack_context_t * from, struct __stack_context_t * to ) asm ("CtxSwitch");256 extern void __cfactx_invoke_stub( void ); 257 extern void __cfactx_switch( struct __stack_context_t * from, struct __stack_context_t * to ) asm ("__cfactx_switch"); 256 258 // void CtxStore ( void * this ) asm ("CtxStore"); 257 259 // void CtxRet ( void * dst ) asm ("CtxRet"); -
libcfa/src/concurrency/kernel.cfa
r41efd33 r04e6f93 110 110 //----------------------------------------------------------------------------- 111 111 //Start and stop routine for the kernel, declared first to make sure they run first 112 static void kernel_startup(void)__attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) ));113 static void kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) ));112 static void __kernel_startup (void) __attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) )); 113 static void __kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) )); 114 114 115 115 //----------------------------------------------------------------------------- … … 117 117 KERNEL_STORAGE(cluster, mainCluster); 118 118 KERNEL_STORAGE(processor, mainProcessor); 119 KERNEL_STORAGE( thread_desc, mainThread);119 KERNEL_STORAGE($thread, mainThread); 120 120 KERNEL_STORAGE(__stack_t, mainThreadCtx); 121 121 122 122 cluster * mainCluster; 123 123 processor * mainProcessor; 124 thread_desc* mainThread;124 $thread * mainThread; 125 125 126 126 extern "C" { … … 164 164 // Main thread construction 165 165 166 void ?{}( coroutine_desc& this, current_stack_info_t * info) with( this ) {166 void ?{}( $coroutine & this, current_stack_info_t * info) with( this ) { 167 167 stack.storage = info->storage; 168 168 with(*stack.storage) { … … 179 179 } 180 180 181 void ?{}( thread_desc& this, current_stack_info_t * info) with( this ) {181 void ?{}( $thread & this, current_stack_info_t * info) with( this ) { 182 182 state = Start; 183 183 self_cor{ info }; … … 208 208 } 209 209 210 static void start(processor * this); 210 static void * __invoke_processor(void * arg); 211 211 212 void ?{}(processor & this, const char name[], cluster & cltr) with( this ) { 212 213 this.name = name; 213 214 this.cltr = &cltr; 214 215 terminated{ 0 }; 216 destroyer = 0p; 215 217 do_terminate = false; 216 218 preemption_alarm = 0p; … … 220 222 idleLock{}; 221 223 222 start( &this ); 224 __cfaabi_dbg_print_safe("Kernel : Starting core %p\n", &this); 225 226 this.stack = __create_pthread( &this.kernel_thread, __invoke_processor, (void *)&this ); 227 228 __cfaabi_dbg_print_safe("Kernel : core %p started\n", &this); 223 229 } 224 230 … … 258 264 // Kernel Scheduling logic 259 265 //============================================================================================= 260 static void runThread(processor * this, thread_desc * dst);261 static void finishRunning(processor * this);262 static void halt(processor * this);266 static $thread * __next_thread(cluster * this); 267 static void __run_thread(processor * this, $thread * dst); 268 static void __halt(processor * this); 263 269 264 270 //Main of the processor contexts … … 281 287 __cfaabi_dbg_print_safe("Kernel : core %p started\n", this); 282 288 283 thread_desc* readyThread = 0p;289 $thread * readyThread = 0p; 284 290 for( unsigned int spin_count = 0; ! __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST); spin_count++ ) { 285 readyThread = nextThread( this->cltr );291 readyThread = __next_thread( this->cltr ); 286 292 287 293 if(readyThread) { 288 verify( ! kernelTLS.preemption_state.enabled ); 289 290 runThread(this, readyThread); 291 292 verify( ! kernelTLS.preemption_state.enabled ); 293 294 //Some actions need to be taken from the kernel 295 finishRunning(this); 294 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 295 /* paranoid */ verifyf( readyThread->state == Inactive || readyThread->state == Start || readyThread->preempted != __NO_PREEMPTION, "state : %d, preempted %d\n", readyThread->state, readyThread->preempted); 296 /* paranoid */ verifyf( readyThread->next == 0p, "Expected null got %p", readyThread->next ); 297 298 __run_thread(this, readyThread); 299 300 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 296 301 297 302 spin_count = 0; 298 303 } else { 299 304 // spin(this, &spin_count); 300 halt(this);305 __halt(this); 301 306 } 302 307 } … … 318 323 // runThread runs a thread by context switching 319 324 // from the processor coroutine to the target thread 320 static void runThread(processor * this, thread_desc * thrd_dst) { 321 coroutine_desc * proc_cor = get_coroutine(this->runner); 322 323 // Reset the terminating actions here 324 this->finish.action_code = No_Action; 325 static void __run_thread(processor * this, $thread * thrd_dst) { 326 $coroutine * proc_cor = get_coroutine(this->runner); 325 327 326 328 // Update global state 327 329 kernelTLS.this_thread = thrd_dst; 328 330 329 // set state of processor coroutine to inactive and the thread to active 330 proc_cor->state = proc_cor->state == Halted ? Halted : Inactive; 331 thrd_dst->state = Active; 332 333 // set context switch to the thread that the processor is executing 334 verify( thrd_dst->context.SP ); 335 CtxSwitch( &proc_cor->context, &thrd_dst->context ); 336 // when CtxSwitch returns we are back in the processor coroutine 337 338 // set state of processor coroutine to active and the thread to inactive 339 thrd_dst->state = thrd_dst->state == Halted ? Halted : Inactive; 331 // set state of processor coroutine to inactive 332 verify(proc_cor->state == Active); 333 proc_cor->state = Inactive; 334 335 // Actually run the thread 336 RUNNING: while(true) { 337 if(unlikely(thrd_dst->preempted)) { 338 thrd_dst->preempted = __NO_PREEMPTION; 339 verify(thrd_dst->state == Active || thrd_dst->state == Rerun); 340 } else { 341 verify(thrd_dst->state == Start || thrd_dst->state == Primed || thrd_dst->state == Inactive); 342 thrd_dst->state = Active; 343 } 344 345 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 346 347 // set context switch to the thread that the processor is executing 348 verify( thrd_dst->context.SP ); 349 __cfactx_switch( &proc_cor->context, &thrd_dst->context ); 350 // when __cfactx_switch returns we are back in the processor coroutine 351 352 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 353 354 355 // We just finished running a thread, there are a few things that could have happened. 356 // 1 - Regular case : the thread has blocked and now one has scheduled it yet. 357 // 2 - Racy case : the thread has blocked but someone has already tried to schedule it. 358 // 3 - Polite Racy case : the thread has blocked, someone has already tried to schedule it, but the thread is nice and wants to go through the ready-queue any way 359 // 4 - Preempted 360 // In case 1, we may have won a race so we can't write to the state again. 361 // In case 2, we lost the race so we now own the thread. 362 // In case 3, we lost the race but can just reschedule the thread. 363 364 if(unlikely(thrd_dst->preempted != __NO_PREEMPTION)) { 365 // The thread was preempted, reschedule it and reset the flag 366 __schedule_thread( thrd_dst ); 367 break RUNNING; 368 } 369 370 // set state of processor coroutine to active and the thread to inactive 371 static_assert(sizeof(thrd_dst->state) == sizeof(int)); 372 enum coroutine_state old_state = __atomic_exchange_n(&thrd_dst->state, Inactive, __ATOMIC_SEQ_CST); 373 switch(old_state) { 374 case Halted: 375 // The thread has halted, it should never be scheduled/run again, leave it back to Halted and move on 376 thrd_dst->state = Halted; 377 378 // We may need to wake someone up here since 379 unpark( this->destroyer ); 380 this->destroyer = 0p; 381 break RUNNING; 382 case Active: 383 // This is case 1, the regular case, nothing more is needed 384 break RUNNING; 385 case Rerun: 386 // This is case 2, the racy case, someone tried to run this thread before it finished blocking 387 // In this case, just run it again. 388 continue RUNNING; 389 default: 390 // This makes no sense, something is wrong abort 391 abort("Finished running a thread that was Inactive/Start/Primed %d\n", old_state); 392 } 393 } 394 395 // Just before returning to the processor, set the processor coroutine to active 340 396 proc_cor->state = Active; 341 397 } 342 398 343 399 // KERNEL_ONLY 344 static void returnToKernel() { 345 coroutine_desc * proc_cor = get_coroutine(kernelTLS.this_processor->runner); 346 thread_desc * thrd_src = kernelTLS.this_thread; 347 348 // set state of current coroutine to inactive 349 thrd_src->state = thrd_src->state == Halted ? Halted : Inactive; 350 proc_cor->state = Active; 351 int local_errno = *__volatile_errno(); 352 #if defined( __i386 ) || defined( __x86_64 ) 353 __x87_store; 354 #endif 355 356 // set new coroutine that the processor is executing 357 // and context switch to it 358 verify( proc_cor->context.SP ); 359 CtxSwitch( &thrd_src->context, &proc_cor->context ); 360 361 // set state of new coroutine to active 362 proc_cor->state = proc_cor->state == Halted ? Halted : Inactive; 363 thrd_src->state = Active; 364 365 #if defined( __i386 ) || defined( __x86_64 ) 366 __x87_load; 367 #endif 368 *__volatile_errno() = local_errno; 369 } 370 371 // KERNEL_ONLY 372 // Once a thread has finished running, some of 373 // its final actions must be executed from the kernel 374 static void finishRunning(processor * this) with( this->finish ) { 375 verify( ! kernelTLS.preemption_state.enabled ); 376 choose( action_code ) { 377 case No_Action: 378 break; 379 case Release: 380 unlock( *lock ); 381 case Schedule: 382 ScheduleThread( thrd ); 383 case Release_Schedule: 384 unlock( *lock ); 385 ScheduleThread( thrd ); 386 case Release_Multi: 387 for(int i = 0; i < lock_count; i++) { 388 unlock( *locks[i] ); 389 } 390 case Release_Multi_Schedule: 391 for(int i = 0; i < lock_count; i++) { 392 unlock( *locks[i] ); 393 } 394 for(int i = 0; i < thrd_count; i++) { 395 ScheduleThread( thrds[i] ); 396 } 397 case Callback: 398 callback(); 399 default: 400 abort("KERNEL ERROR: Unexpected action to run after thread"); 401 } 400 void returnToKernel() { 401 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 402 $coroutine * proc_cor = get_coroutine(kernelTLS.this_processor->runner); 403 $thread * thrd_src = kernelTLS.this_thread; 404 405 // Run the thread on this processor 406 { 407 int local_errno = *__volatile_errno(); 408 #if defined( __i386 ) || defined( __x86_64 ) 409 __x87_store; 410 #endif 411 verify( proc_cor->context.SP ); 412 __cfactx_switch( &thrd_src->context, &proc_cor->context ); 413 #if defined( __i386 ) || defined( __x86_64 ) 414 __x87_load; 415 #endif 416 *__volatile_errno() = local_errno; 417 } 418 419 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 402 420 } 403 421 … … 406 424 // This is the entry point for processors (kernel threads) 407 425 // It effectively constructs a coroutine by stealing the pthread stack 408 static void * CtxInvokeProcessor(void * arg) {426 static void * __invoke_processor(void * arg) { 409 427 processor * proc = (processor *) arg; 410 428 kernelTLS.this_processor = proc; … … 447 465 } // Abort 448 466 449 void * create_pthread( pthread_t * pthread, void * (*start)(void *), void * arg ) {467 void * __create_pthread( pthread_t * pthread, void * (*start)(void *), void * arg ) { 450 468 pthread_attr_t attr; 451 469 … … 475 493 } 476 494 477 static void start(processor * this) {478 __cfaabi_dbg_print_safe("Kernel : Starting core %p\n", this);479 480 this->stack = create_pthread( &this->kernel_thread, CtxInvokeProcessor, (void *)this );481 482 __cfaabi_dbg_print_safe("Kernel : core %p started\n", this);483 }484 485 495 // KERNEL_ONLY 486 voidkernel_first_resume( processor * this ) {487 thread_desc* src = mainThread;488 coroutine_desc* dst = get_coroutine(this->runner);496 static void __kernel_first_resume( processor * this ) { 497 $thread * src = mainThread; 498 $coroutine * dst = get_coroutine(this->runner); 489 499 490 500 verify( ! kernelTLS.preemption_state.enabled ); … … 492 502 kernelTLS.this_thread->curr_cor = dst; 493 503 __stack_prepare( &dst->stack, 65000 ); 494 CtxStart(main, dst, this->runner, CtxInvokeCoroutine);504 __cfactx_start(main, dst, this->runner, __cfactx_invoke_coroutine); 495 505 496 506 verify( ! kernelTLS.preemption_state.enabled ); … … 504 514 // context switch to specified coroutine 505 515 verify( dst->context.SP ); 506 CtxSwitch( &src->context, &dst->context );507 // when CtxSwitch returns we are back in the src coroutine516 __cfactx_switch( &src->context, &dst->context ); 517 // when __cfactx_switch returns we are back in the src coroutine 508 518 509 519 mainThread->curr_cor = &mainThread->self_cor; … … 516 526 517 527 // KERNEL_ONLY 518 voidkernel_last_resume( processor * this ) {519 coroutine_desc* src = &mainThread->self_cor;520 coroutine_desc* dst = get_coroutine(this->runner);528 static void __kernel_last_resume( processor * this ) { 529 $coroutine * src = &mainThread->self_cor; 530 $coroutine * dst = get_coroutine(this->runner); 521 531 522 532 verify( ! kernelTLS.preemption_state.enabled ); … … 525 535 526 536 // context switch to the processor 527 CtxSwitch( &src->context, &dst->context );537 __cfactx_switch( &src->context, &dst->context ); 528 538 } 529 539 530 540 //----------------------------------------------------------------------------- 531 541 // Scheduler routines 532 533 542 // KERNEL ONLY 534 void ScheduleThread( thread_desc * thrd ) { 535 verify( thrd ); 536 verify( thrd->state != Halted ); 537 538 verify( ! kernelTLS.preemption_state.enabled ); 539 540 verifyf( thrd->next == 0p, "Expected null got %p", thrd->next ); 541 542 with( *thrd->curr_cluster ) { 543 lock ( ready_queue_lock __cfaabi_dbg_ctx2 ); 544 bool was_empty = !(ready_queue != 0); 545 append( ready_queue, thrd ); 546 unlock( ready_queue_lock ); 547 548 if(was_empty) { 549 lock (proc_list_lock __cfaabi_dbg_ctx2); 550 if(idles) { 551 wake_fast(idles.head); 552 } 553 unlock (proc_list_lock); 543 void __schedule_thread( $thread * thrd ) with( *thrd->curr_cluster ) { 544 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 545 /* paranoid */ #if defined( __CFA_WITH_VERIFY__ ) 546 /* paranoid */ if( thrd->state == Inactive || thrd->state == Start ) assertf( thrd->preempted == __NO_PREEMPTION, 547 "Error inactive thread marked as preempted, state %d, preemption %d\n", thrd->state, thrd->preempted ); 548 /* paranoid */ if( thrd->preempted != __NO_PREEMPTION ) assertf(thrd->state == Active || thrd->state == Rerun, 549 "Error preempted thread marked as not currently running, state %d, preemption %d\n", thrd->state, thrd->preempted ); 550 /* paranoid */ #endif 551 /* paranoid */ verifyf( thrd->next == 0p, "Expected null got %p", thrd->next ); 552 553 lock ( ready_queue_lock __cfaabi_dbg_ctx2 ); 554 bool was_empty = !(ready_queue != 0); 555 append( ready_queue, thrd ); 556 unlock( ready_queue_lock ); 557 558 if(was_empty) { 559 lock (proc_list_lock __cfaabi_dbg_ctx2); 560 if(idles) { 561 wake_fast(idles.head); 554 562 } 555 else if( struct processor * idle = idles.head ) {556 wake_fast(idle);557 }558 559 } 560 561 verify( ! kernelTLS.preemption_state.enabled );563 unlock (proc_list_lock); 564 } 565 else if( struct processor * idle = idles.head ) { 566 wake_fast(idle); 567 } 568 569 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 562 570 } 563 571 564 572 // KERNEL ONLY 565 thread_desc * nextThread(cluster * this) with( *this ) { 566 verify( ! kernelTLS.preemption_state.enabled ); 573 static $thread * __next_thread(cluster * this) with( *this ) { 574 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 575 567 576 lock( ready_queue_lock __cfaabi_dbg_ctx2 ); 568 thread_desc* head = pop_head( ready_queue );577 $thread * head = pop_head( ready_queue ); 569 578 unlock( ready_queue_lock ); 570 verify( ! kernelTLS.preemption_state.enabled ); 579 580 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 571 581 return head; 572 582 } 573 583 574 void BlockInternal() { 584 void unpark( $thread * thrd ) { 585 if( !thrd ) return; 586 575 587 disable_interrupts(); 576 verify( ! kernelTLS.preemption_state.enabled ); 588 static_assert(sizeof(thrd->state) == sizeof(int)); 589 enum coroutine_state old_state = __atomic_exchange_n(&thrd->state, Rerun, __ATOMIC_SEQ_CST); 590 switch(old_state) { 591 case Active: 592 // Wake won the race, the thread will reschedule/rerun itself 593 break; 594 case Inactive: 595 /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION ); 596 597 // Wake lost the race, 598 thrd->state = Inactive; 599 __schedule_thread( thrd ); 600 break; 601 case Rerun: 602 abort("More than one thread attempted to schedule thread %p\n", thrd); 603 break; 604 case Halted: 605 case Start: 606 case Primed: 607 default: 608 // This makes no sense, something is wrong abort 609 abort(); 610 } 611 enable_interrupts( __cfaabi_dbg_ctx ); 612 } 613 614 void park( void ) { 615 /* paranoid */ verify( kernelTLS.preemption_state.enabled ); 616 disable_interrupts(); 617 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 618 /* paranoid */ verify( kernelTLS.this_thread->preempted == __NO_PREEMPTION ); 619 577 620 returnToKernel(); 578 verify( ! kernelTLS.preemption_state.enabled ); 621 622 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 579 623 enable_interrupts( __cfaabi_dbg_ctx ); 580 } 581 582 void BlockInternal( __spinlock_t * lock ) { 624 /* paranoid */ verify( kernelTLS.preemption_state.enabled ); 625 626 } 627 628 // KERNEL ONLY 629 void __leave_thread() { 630 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 631 returnToKernel(); 632 abort(); 633 } 634 635 // KERNEL ONLY 636 bool force_yield( __Preemption_Reason reason ) { 637 /* paranoid */ verify( kernelTLS.preemption_state.enabled ); 583 638 disable_interrupts(); 584 with( *kernelTLS.this_processor ) { 585 finish.action_code = Release; 586 finish.lock = lock; 587 } 588 589 verify( ! kernelTLS.preemption_state.enabled ); 590 returnToKernel(); 591 verify( ! kernelTLS.preemption_state.enabled ); 592 593 enable_interrupts( __cfaabi_dbg_ctx ); 594 } 595 596 void BlockInternal( thread_desc * thrd ) { 597 disable_interrupts(); 598 with( * kernelTLS.this_processor ) { 599 finish.action_code = Schedule; 600 finish.thrd = thrd; 601 } 602 603 verify( ! kernelTLS.preemption_state.enabled ); 604 returnToKernel(); 605 verify( ! kernelTLS.preemption_state.enabled ); 606 607 enable_interrupts( __cfaabi_dbg_ctx ); 608 } 609 610 void BlockInternal( __spinlock_t * lock, thread_desc * thrd ) { 611 assert(thrd); 612 disable_interrupts(); 613 with( * kernelTLS.this_processor ) { 614 finish.action_code = Release_Schedule; 615 finish.lock = lock; 616 finish.thrd = thrd; 617 } 618 619 verify( ! kernelTLS.preemption_state.enabled ); 620 returnToKernel(); 621 verify( ! kernelTLS.preemption_state.enabled ); 622 623 enable_interrupts( __cfaabi_dbg_ctx ); 624 } 625 626 void BlockInternal(__spinlock_t * locks [], unsigned short count) { 627 disable_interrupts(); 628 with( * kernelTLS.this_processor ) { 629 finish.action_code = Release_Multi; 630 finish.locks = locks; 631 finish.lock_count = count; 632 } 633 634 verify( ! kernelTLS.preemption_state.enabled ); 635 returnToKernel(); 636 verify( ! kernelTLS.preemption_state.enabled ); 637 638 enable_interrupts( __cfaabi_dbg_ctx ); 639 } 640 641 void BlockInternal(__spinlock_t * locks [], unsigned short lock_count, thread_desc * thrds [], unsigned short thrd_count) { 642 disable_interrupts(); 643 with( *kernelTLS.this_processor ) { 644 finish.action_code = Release_Multi_Schedule; 645 finish.locks = locks; 646 finish.lock_count = lock_count; 647 finish.thrds = thrds; 648 finish.thrd_count = thrd_count; 649 } 650 651 verify( ! kernelTLS.preemption_state.enabled ); 652 returnToKernel(); 653 verify( ! kernelTLS.preemption_state.enabled ); 654 655 enable_interrupts( __cfaabi_dbg_ctx ); 656 } 657 658 void BlockInternal(__finish_callback_fptr_t callback) { 659 disable_interrupts(); 660 with( *kernelTLS.this_processor ) { 661 finish.action_code = Callback; 662 finish.callback = callback; 663 } 664 665 verify( ! kernelTLS.preemption_state.enabled ); 666 returnToKernel(); 667 verify( ! kernelTLS.preemption_state.enabled ); 668 669 enable_interrupts( __cfaabi_dbg_ctx ); 670 } 671 672 // KERNEL ONLY 673 void LeaveThread(__spinlock_t * lock, thread_desc * thrd) { 674 verify( ! kernelTLS.preemption_state.enabled ); 675 with( * kernelTLS.this_processor ) { 676 finish.action_code = thrd ? Release_Schedule : Release; 677 finish.lock = lock; 678 finish.thrd = thrd; 679 } 680 681 returnToKernel(); 639 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 640 641 $thread * thrd = kernelTLS.this_thread; 642 /* paranoid */ verify(thrd->state == Active || thrd->state == Rerun); 643 644 // SKULLDUGGERY: It is possible that we are preempting this thread just before 645 // it was going to park itself. If that is the case and it is already using the 646 // intrusive fields then we can't use them to preempt the thread 647 // If that is the case, abandon the preemption. 648 bool preempted = false; 649 if(thrd->next == 0p) { 650 preempted = true; 651 thrd->preempted = reason; 652 returnToKernel(); 653 } 654 655 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 656 enable_interrupts_noPoll(); 657 /* paranoid */ verify( kernelTLS.preemption_state.enabled ); 658 659 return preempted; 682 660 } 683 661 … … 687 665 //----------------------------------------------------------------------------- 688 666 // Kernel boot procedures 689 static void kernel_startup(void) {667 static void __kernel_startup(void) { 690 668 verify( ! kernelTLS.preemption_state.enabled ); 691 669 __cfaabi_dbg_print_safe("Kernel : Starting\n"); … … 705 683 // SKULLDUGGERY: the mainThread steals the process main thread 706 684 // which will then be scheduled by the mainProcessor normally 707 mainThread = ( thread_desc*)&storage_mainThread;685 mainThread = ($thread *)&storage_mainThread; 708 686 current_stack_info_t info; 709 687 info.storage = (__stack_t*)&storage_mainThreadCtx; … … 748 726 // Add the main thread to the ready queue 749 727 // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread 750 ScheduleThread(mainThread);728 __schedule_thread(mainThread); 751 729 752 730 // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX 753 // context. Hence, the main thread does not begin through CtxInvokeThread, like all other threads. The trick here is that731 // context. Hence, the main thread does not begin through __cfactx_invoke_thread, like all other threads. The trick here is that 754 732 // mainThread is on the ready queue when this call is made. 755 kernel_first_resume( kernelTLS.this_processor );733 __kernel_first_resume( kernelTLS.this_processor ); 756 734 757 735 … … 765 743 } 766 744 767 static void kernel_shutdown(void) {745 static void __kernel_shutdown(void) { 768 746 __cfaabi_dbg_print_safe("\n--------------------------------------------------\nKernel : Shutting down\n"); 769 747 … … 776 754 // which is currently here 777 755 __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE); 778 kernel_last_resume( kernelTLS.this_processor );756 __kernel_last_resume( kernelTLS.this_processor ); 779 757 mainThread->self_cor.state = Halted; 780 758 … … 802 780 // Kernel Quiescing 803 781 //============================================================================================= 804 static void halt(processor * this) with( *this ) {782 static void __halt(processor * this) with( *this ) { 805 783 // verify( ! __atomic_load_n(&do_terminate, __ATOMIC_SEQ_CST) ); 806 784 … … 857 835 858 836 void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) { 859 thread_desc* thrd = kernel_data;837 $thread * thrd = kernel_data; 860 838 861 839 if(thrd) { … … 913 891 914 892 // atomically release spin lock and block 915 BlockInternal( &lock ); 893 unlock( lock ); 894 park(); 916 895 } 917 896 else { … … 921 900 922 901 void V(semaphore & this) with( this ) { 923 thread_desc* thrd = 0p;902 $thread * thrd = 0p; 924 903 lock( lock __cfaabi_dbg_ctx2 ); 925 904 count += 1; … … 932 911 933 912 // make new owner 934 WakeThread( thrd );913 unpark( thrd ); 935 914 } 936 915 … … 949 928 } 950 929 951 void doregister( cluster * cltr, thread_desc& thrd ) {930 void doregister( cluster * cltr, $thread & thrd ) { 952 931 lock (cltr->thread_list_lock __cfaabi_dbg_ctx2); 953 932 cltr->nthreads += 1; … … 956 935 } 957 936 958 void unregister( cluster * cltr, thread_desc& thrd ) {937 void unregister( cluster * cltr, $thread & thrd ) { 959 938 lock (cltr->thread_list_lock __cfaabi_dbg_ctx2); 960 939 remove(cltr->threads, thrd ); … … 990 969 //----------------------------------------------------------------------------- 991 970 // Debug 992 bool threading_enabled(void) {971 bool threading_enabled(void) __attribute__((const)) { 993 972 return true; 994 973 } -
libcfa/src/concurrency/kernel.hfa
r41efd33 r04e6f93 32 32 __spinlock_t lock; 33 33 int count; 34 __queue_t( thread_desc) waiting;34 __queue_t($thread) waiting; 35 35 }; 36 36 … … 44 44 // Processor 45 45 extern struct cluster * mainCluster; 46 47 enum FinishOpCode { No_Action, Release, Schedule, Release_Schedule, Release_Multi, Release_Multi_Schedule, Callback };48 49 typedef void (*__finish_callback_fptr_t)(void);50 51 //TODO use union, many of these fields are mutually exclusive (i.e. MULTI vs NOMULTI)52 struct FinishAction {53 FinishOpCode action_code;54 /*55 // Union of possible actions56 union {57 // Option 1 : locks and threads58 struct {59 // 1 thread or N thread60 union {61 thread_desc * thrd;62 struct {63 thread_desc ** thrds;64 unsigned short thrd_count;65 };66 };67 // 1 lock or N lock68 union {69 __spinlock_t * lock;70 struct {71 __spinlock_t ** locks;72 unsigned short lock_count;73 };74 };75 };76 // Option 2 : action pointer77 __finish_callback_fptr_t callback;78 };79 /*/80 thread_desc * thrd;81 thread_desc ** thrds;82 unsigned short thrd_count;83 __spinlock_t * lock;84 __spinlock_t ** locks;85 unsigned short lock_count;86 __finish_callback_fptr_t callback;87 //*/88 };89 static inline void ?{}(FinishAction & this) {90 this.action_code = No_Action;91 this.thrd = 0p;92 this.lock = 0p;93 }94 static inline void ^?{}(FinishAction &) {}95 46 96 47 // Processor … … 116 67 // RunThread data 117 68 // Action to do after a thread is ran 118 struct FinishAction finish;69 $thread * destroyer; 119 70 120 71 // Preemption data … … 157 108 static inline void ?{}(processor & this, const char name[]) { this{name, *mainCluster }; } 158 109 159 static inline [processor *&, processor *& ] __get( processor & this ) { 160 return this.node.[next, prev]; 161 } 110 static inline [processor *&, processor *& ] __get( processor & this ) __attribute__((const)) { return this.node.[next, prev]; } 162 111 163 112 //----------------------------------------------------------------------------- … … 168 117 169 118 // Ready queue for threads 170 __queue_t( thread_desc) ready_queue;119 __queue_t($thread) ready_queue; 171 120 172 121 // Name of the cluster … … 184 133 // List of threads 185 134 __spinlock_t thread_list_lock; 186 __dllist_t(struct thread_desc) threads;135 __dllist_t(struct $thread) threads; 187 136 unsigned int nthreads; 188 137 … … 202 151 static inline void ?{} (cluster & this, const char name[]) { this{name, default_preemption()}; } 203 152 204 static inline [cluster *&, cluster *& ] __get( cluster & this ) { 205 return this.node.[next, prev]; 206 } 153 static inline [cluster *&, cluster *& ] __get( cluster & this ) __attribute__((const)) { return this.node.[next, prev]; } 207 154 208 155 static inline struct processor * active_processor() { return TL_GET( this_processor ); } // UNSAFE -
libcfa/src/concurrency/kernel_private.hfa
r41efd33 r04e6f93 31 31 } 32 32 33 void ScheduleThread( thread_desc * ); 34 static inline void WakeThread( thread_desc * thrd ) { 35 if( !thrd ) return; 36 37 verify(thrd->state == Inactive); 38 39 disable_interrupts(); 40 ScheduleThread( thrd ); 41 enable_interrupts( __cfaabi_dbg_ctx ); 42 } 43 thread_desc * nextThread(cluster * this); 33 void __schedule_thread( $thread * ) __attribute__((nonnull (1))); 44 34 45 35 //Block current thread and release/wake-up the following resources 46 void BlockInternal(void); 47 void BlockInternal(__spinlock_t * lock); 48 void BlockInternal(thread_desc * thrd); 49 void BlockInternal(__spinlock_t * lock, thread_desc * thrd); 50 void BlockInternal(__spinlock_t * locks [], unsigned short count); 51 void BlockInternal(__spinlock_t * locks [], unsigned short count, thread_desc * thrds [], unsigned short thrd_count); 52 void BlockInternal(__finish_callback_fptr_t callback); 53 void LeaveThread(__spinlock_t * lock, thread_desc * thrd); 36 void __leave_thread() __attribute__((noreturn)); 54 37 55 38 //----------------------------------------------------------------------------- … … 57 40 void main(processorCtx_t *); 58 41 59 void * create_pthread( pthread_t *, void * (*)(void *), void * );42 void * __create_pthread( pthread_t *, void * (*)(void *), void * ); 60 43 61 44 static inline void wake_fast(processor * this) { … … 88 71 // Threads 89 72 extern "C" { 90 void CtxInvokeThread(void (*main)(void *), void * this);73 void __cfactx_invoke_thread(void (*main)(void *), void * this); 91 74 } 92 75 93 extern void ThreadCtxSwitch(coroutine_desc * src, coroutine_desc * dst);94 95 76 __cfaabi_dbg_debug_do( 96 extern void __cfaabi_dbg_thread_register ( thread_desc* thrd );97 extern void __cfaabi_dbg_thread_unregister( thread_desc* thrd );77 extern void __cfaabi_dbg_thread_register ( $thread * thrd ); 78 extern void __cfaabi_dbg_thread_unregister( $thread * thrd ); 98 79 ) 99 80 … … 102 83 #define KERNEL_STORAGE(T,X) static char storage_##X[sizeof(T)] 103 84 104 static inline uint32_t tls_rand() {85 static inline uint32_t __tls_rand() { 105 86 kernelTLS.rand_seed ^= kernelTLS.rand_seed << 6; 106 87 kernelTLS.rand_seed ^= kernelTLS.rand_seed >> 21; … … 113 94 void unregister( struct cluster & cltr ); 114 95 115 void doregister( struct cluster * cltr, struct thread_desc& thrd );116 void unregister( struct cluster * cltr, struct thread_desc& thrd );96 void doregister( struct cluster * cltr, struct $thread & thrd ); 97 void unregister( struct cluster * cltr, struct $thread & thrd ); 117 98 118 99 void doregister( struct cluster * cltr, struct processor * proc ); -
libcfa/src/concurrency/monitor.cfa
r41efd33 r04e6f93 5 5 // file "LICENCE" distributed with Cforall. 6 6 // 7 // monitor_desc.c --7 // $monitor.c -- 8 8 // 9 9 // Author : Thierry Delisle … … 27 27 //----------------------------------------------------------------------------- 28 28 // Forward declarations 29 static inline void set_owner ( monitor_desc * this, thread_desc* owner );30 static inline void set_owner ( monitor_desc * storage [], __lock_size_t count, thread_desc* owner );31 static inline void set_mask ( monitor_desc* storage [], __lock_size_t count, const __waitfor_mask_t & mask );32 static inline void reset_mask( monitor_desc* this );33 34 static inline thread_desc * next_thread( monitor_desc* this );35 static inline bool is_accepted( monitor_desc* this, const __monitor_group_t & monitors );29 static inline void __set_owner ( $monitor * this, $thread * owner ); 30 static inline void __set_owner ( $monitor * storage [], __lock_size_t count, $thread * owner ); 31 static inline void set_mask ( $monitor * storage [], __lock_size_t count, const __waitfor_mask_t & mask ); 32 static inline void reset_mask( $monitor * this ); 33 34 static inline $thread * next_thread( $monitor * this ); 35 static inline bool is_accepted( $monitor * this, const __monitor_group_t & monitors ); 36 36 37 37 static inline void lock_all ( __spinlock_t * locks [], __lock_size_t count ); 38 static inline void lock_all ( monitor_desc* source [], __spinlock_t * /*out*/ locks [], __lock_size_t count );38 static inline void lock_all ( $monitor * source [], __spinlock_t * /*out*/ locks [], __lock_size_t count ); 39 39 static inline void unlock_all( __spinlock_t * locks [], __lock_size_t count ); 40 static inline void unlock_all( monitor_desc* locks [], __lock_size_t count );41 42 static inline void save ( monitor_desc* ctx [], __lock_size_t count, __spinlock_t * locks [], unsigned int /*out*/ recursions [], __waitfor_mask_t /*out*/ masks [] );43 static inline void restore( monitor_desc* ctx [], __lock_size_t count, __spinlock_t * locks [], unsigned int /*in */ recursions [], __waitfor_mask_t /*in */ masks [] );44 45 static inline void init ( __lock_size_t count, monitor_desc* monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] );46 static inline void init_push( __lock_size_t count, monitor_desc* monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] );47 48 static inline thread_desc* check_condition ( __condition_criterion_t * );40 static inline void unlock_all( $monitor * locks [], __lock_size_t count ); 41 42 static inline void save ( $monitor * ctx [], __lock_size_t count, __spinlock_t * locks [], unsigned int /*out*/ recursions [], __waitfor_mask_t /*out*/ masks [] ); 43 static inline void restore( $monitor * ctx [], __lock_size_t count, __spinlock_t * locks [], unsigned int /*in */ recursions [], __waitfor_mask_t /*in */ masks [] ); 44 45 static inline void init ( __lock_size_t count, $monitor * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ); 46 static inline void init_push( __lock_size_t count, $monitor * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ); 47 48 static inline $thread * check_condition ( __condition_criterion_t * ); 49 49 static inline void brand_condition ( condition & ); 50 static inline [ thread_desc *, int] search_entry_queue( const __waitfor_mask_t &, monitor_desc* monitors [], __lock_size_t count );50 static inline [$thread *, int] search_entry_queue( const __waitfor_mask_t &, $monitor * monitors [], __lock_size_t count ); 51 51 52 52 forall(dtype T | sized( T )) 53 53 static inline __lock_size_t insert_unique( T * array [], __lock_size_t & size, T * val ); 54 54 static inline __lock_size_t count_max ( const __waitfor_mask_t & mask ); 55 static inline __lock_size_t aggregate ( monitor_desc* storage [], const __waitfor_mask_t & mask );55 static inline __lock_size_t aggregate ( $monitor * storage [], const __waitfor_mask_t & mask ); 56 56 57 57 //----------------------------------------------------------------------------- … … 68 68 69 69 #define monitor_ctx( mons, cnt ) /* Define that create the necessary struct for internal/external scheduling operations */ \ 70 monitor_desc** monitors = mons; /* Save the targeted monitors */ \70 $monitor ** monitors = mons; /* Save the targeted monitors */ \ 71 71 __lock_size_t count = cnt; /* Save the count to a local variable */ \ 72 72 unsigned int recursions[ count ]; /* Save the current recursion levels to restore them later */ \ … … 80 80 //----------------------------------------------------------------------------- 81 81 // Enter/Leave routines 82 83 84 extern "C" { 85 // Enter single monitor 86 static void __enter_monitor_desc( monitor_desc * this, const __monitor_group_t & group ) { 87 // Lock the monitor spinlock 88 lock( this->lock __cfaabi_dbg_ctx2 ); 89 // Interrupts disable inside critical section 90 thread_desc * thrd = kernelTLS.this_thread; 91 92 __cfaabi_dbg_print_safe( "Kernel : %10p Entering mon %p (%p)\n", thrd, this, this->owner); 93 94 if( !this->owner ) { 95 // No one has the monitor, just take it 96 set_owner( this, thrd ); 97 98 __cfaabi_dbg_print_safe( "Kernel : mon is free \n" ); 99 } 100 else if( this->owner == thrd) { 101 // We already have the monitor, just note how many times we took it 102 this->recursion += 1; 103 104 __cfaabi_dbg_print_safe( "Kernel : mon already owned \n" ); 105 } 106 else if( is_accepted( this, group) ) { 107 // Some one was waiting for us, enter 108 set_owner( this, thrd ); 109 110 // Reset mask 111 reset_mask( this ); 112 113 __cfaabi_dbg_print_safe( "Kernel : mon accepts \n" ); 114 } 115 else { 116 __cfaabi_dbg_print_safe( "Kernel : blocking \n" ); 117 118 // Some one else has the monitor, wait in line for it 119 append( this->entry_queue, thrd ); 120 121 BlockInternal( &this->lock ); 122 123 __cfaabi_dbg_print_safe( "Kernel : %10p Entered mon %p\n", thrd, this); 124 125 // BlockInternal will unlock spinlock, no need to unlock ourselves 126 return; 127 } 82 // Enter single monitor 83 static void __enter( $monitor * this, const __monitor_group_t & group ) { 84 // Lock the monitor spinlock 85 lock( this->lock __cfaabi_dbg_ctx2 ); 86 // Interrupts disable inside critical section 87 $thread * thrd = kernelTLS.this_thread; 88 89 __cfaabi_dbg_print_safe( "Kernel : %10p Entering mon %p (%p)\n", thrd, this, this->owner); 90 91 if( !this->owner ) { 92 // No one has the monitor, just take it 93 __set_owner( this, thrd ); 94 95 __cfaabi_dbg_print_safe( "Kernel : mon is free \n" ); 96 } 97 else if( this->owner == thrd) { 98 // We already have the monitor, just note how many times we took it 99 this->recursion += 1; 100 101 __cfaabi_dbg_print_safe( "Kernel : mon already owned \n" ); 102 } 103 else if( is_accepted( this, group) ) { 104 // Some one was waiting for us, enter 105 __set_owner( this, thrd ); 106 107 // Reset mask 108 reset_mask( this ); 109 110 __cfaabi_dbg_print_safe( "Kernel : mon accepts \n" ); 111 } 112 else { 113 __cfaabi_dbg_print_safe( "Kernel : blocking \n" ); 114 115 // Some one else has the monitor, wait in line for it 116 /* paranoid */ verify( thrd->next == 0p ); 117 append( this->entry_queue, thrd ); 118 /* paranoid */ verify( thrd->next == 1p ); 119 120 unlock( this->lock ); 121 park(); 128 122 129 123 __cfaabi_dbg_print_safe( "Kernel : %10p Entered mon %p\n", thrd, this); 130 124 131 // Release the lock and leave 125 /* paranoid */ verifyf( kernelTLS.this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 126 return; 127 } 128 129 __cfaabi_dbg_print_safe( "Kernel : %10p Entered mon %p\n", thrd, this); 130 131 /* paranoid */ verifyf( kernelTLS.this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 132 /* paranoid */ verify( this->lock.lock ); 133 134 // Release the lock and leave 135 unlock( this->lock ); 136 return; 137 } 138 139 static void __dtor_enter( $monitor * this, fptr_t func ) { 140 // Lock the monitor spinlock 141 lock( this->lock __cfaabi_dbg_ctx2 ); 142 // Interrupts disable inside critical section 143 $thread * thrd = kernelTLS.this_thread; 144 145 __cfaabi_dbg_print_safe( "Kernel : %10p Entering dtor for mon %p (%p)\n", thrd, this, this->owner); 146 147 148 if( !this->owner ) { 149 __cfaabi_dbg_print_safe( "Kernel : Destroying free mon %p\n", this); 150 151 // No one has the monitor, just take it 152 __set_owner( this, thrd ); 153 154 verifyf( kernelTLS.this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 155 132 156 unlock( this->lock ); 133 157 return; 134 158 } 135 136 static void __enter_monitor_dtor( monitor_desc * this, fptr_t func ) { 137 // Lock the monitor spinlock 138 lock( this->lock __cfaabi_dbg_ctx2 ); 139 // Interrupts disable inside critical section 140 thread_desc * thrd = kernelTLS.this_thread; 141 142 __cfaabi_dbg_print_safe( "Kernel : %10p Entering dtor for mon %p (%p)\n", thrd, this, this->owner); 143 144 145 if( !this->owner ) { 146 __cfaabi_dbg_print_safe( "Kernel : Destroying free mon %p\n", this); 147 148 // No one has the monitor, just take it 149 set_owner( this, thrd ); 150 151 unlock( this->lock ); 152 return; 159 else if( this->owner == thrd) { 160 // We already have the monitor... but where about to destroy it so the nesting will fail 161 // Abort! 162 abort( "Attempt to destroy monitor %p by thread \"%.256s\" (%p) in nested mutex.", this, thrd->self_cor.name, thrd ); 163 } 164 165 __lock_size_t count = 1; 166 $monitor ** monitors = &this; 167 __monitor_group_t group = { &this, 1, func }; 168 if( is_accepted( this, group) ) { 169 __cfaabi_dbg_print_safe( "Kernel : mon accepts dtor, block and signal it \n" ); 170 171 // Wake the thread that is waiting for this 172 __condition_criterion_t * urgent = pop( this->signal_stack ); 173 /* paranoid */ verify( urgent ); 174 175 // Reset mask 176 reset_mask( this ); 177 178 // Create the node specific to this wait operation 179 wait_ctx_primed( thrd, 0 ) 180 181 // Some one else has the monitor, wait for him to finish and then run 182 unlock( this->lock ); 183 184 // Release the next thread 185 /* paranoid */ verifyf( urgent->owner->waiting_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 186 unpark( urgent->owner->waiting_thread ); 187 188 // Park current thread waiting 189 park(); 190 191 // Some one was waiting for us, enter 192 /* paranoid */ verifyf( kernelTLS.this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 193 } 194 else { 195 __cfaabi_dbg_print_safe( "Kernel : blocking \n" ); 196 197 wait_ctx( thrd, 0 ) 198 this->dtor_node = &waiter; 199 200 // Some one else has the monitor, wait in line for it 201 /* paranoid */ verify( thrd->next == 0p ); 202 append( this->entry_queue, thrd ); 203 /* paranoid */ verify( thrd->next == 1p ); 204 unlock( this->lock ); 205 206 // Park current thread waiting 207 park(); 208 209 /* paranoid */ verifyf( kernelTLS.this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 210 return; 211 } 212 213 __cfaabi_dbg_print_safe( "Kernel : Destroying %p\n", this); 214 215 } 216 217 // Leave single monitor 218 void __leave( $monitor * this ) { 219 // Lock the monitor spinlock 220 lock( this->lock __cfaabi_dbg_ctx2 ); 221 222 __cfaabi_dbg_print_safe( "Kernel : %10p Leaving mon %p (%p)\n", kernelTLS.this_thread, this, this->owner); 223 224 /* paranoid */ verifyf( kernelTLS.this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 225 226 // Leaving a recursion level, decrement the counter 227 this->recursion -= 1; 228 229 // If we haven't left the last level of recursion 230 // it means we don't need to do anything 231 if( this->recursion != 0) { 232 __cfaabi_dbg_print_safe( "Kernel : recursion still %d\n", this->recursion); 233 unlock( this->lock ); 234 return; 235 } 236 237 // Get the next thread, will be null on low contention monitor 238 $thread * new_owner = next_thread( this ); 239 240 // Check the new owner is consistent with who we wake-up 241 // new_owner might be null even if someone owns the monitor when the owner is still waiting for another monitor 242 /* paranoid */ verifyf( !new_owner || new_owner == this->owner, "Expected owner to be %p, got %p (m: %p)", new_owner, this->owner, this ); 243 244 // We can now let other threads in safely 245 unlock( this->lock ); 246 247 //We need to wake-up the thread 248 /* paranoid */ verifyf( !new_owner || new_owner == this->owner, "Expected owner to be %p, got %p (m: %p)", new_owner, this->owner, this ); 249 unpark( new_owner ); 250 } 251 252 // Leave single monitor for the last time 253 void __dtor_leave( $monitor * this ) { 254 __cfaabi_dbg_debug_do( 255 if( TL_GET( this_thread ) != this->owner ) { 256 abort( "Destroyed monitor %p has inconsistent owner, expected %p got %p.\n", this, TL_GET( this_thread ), this->owner); 153 257 } 154 else if( this->owner == thrd) { 155 // We already have the monitor... but where about to destroy it so the nesting will fail 156 // Abort! 157 abort( "Attempt to destroy monitor %p by thread \"%.256s\" (%p) in nested mutex.", this, thrd->self_cor.name, thrd ); 258 if( this->recursion != 1 ) { 259 abort( "Destroyed monitor %p has %d outstanding nested calls.\n", this, this->recursion - 1); 158 260 } 159 160 __lock_size_t count = 1; 161 monitor_desc ** monitors = &this; 162 __monitor_group_t group = { &this, 1, func }; 163 if( is_accepted( this, group) ) { 164 __cfaabi_dbg_print_safe( "Kernel : mon accepts dtor, block and signal it \n" ); 165 166 // Wake the thread that is waiting for this 167 __condition_criterion_t * urgent = pop( this->signal_stack ); 168 verify( urgent ); 169 170 // Reset mask 171 reset_mask( this ); 172 173 // Create the node specific to this wait operation 174 wait_ctx_primed( thrd, 0 ) 175 176 // Some one else has the monitor, wait for him to finish and then run 177 BlockInternal( &this->lock, urgent->owner->waiting_thread ); 178 179 // Some one was waiting for us, enter 180 set_owner( this, thrd ); 181 } 182 else { 183 __cfaabi_dbg_print_safe( "Kernel : blocking \n" ); 184 185 wait_ctx( thrd, 0 ) 186 this->dtor_node = &waiter; 187 188 // Some one else has the monitor, wait in line for it 189 append( this->entry_queue, thrd ); 190 BlockInternal( &this->lock ); 191 192 // BlockInternal will unlock spinlock, no need to unlock ourselves 193 return; 194 } 195 196 __cfaabi_dbg_print_safe( "Kernel : Destroying %p\n", this); 197 198 } 199 200 // Leave single monitor 201 void __leave_monitor_desc( monitor_desc * this ) { 202 // Lock the monitor spinlock 203 lock( this->lock __cfaabi_dbg_ctx2 ); 204 205 __cfaabi_dbg_print_safe( "Kernel : %10p Leaving mon %p (%p)\n", kernelTLS.this_thread, this, this->owner); 206 207 verifyf( kernelTLS.this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 208 209 // Leaving a recursion level, decrement the counter 210 this->recursion -= 1; 211 212 // If we haven't left the last level of recursion 213 // it means we don't need to do anything 214 if( this->recursion != 0) { 215 __cfaabi_dbg_print_safe( "Kernel : recursion still %d\n", this->recursion); 216 unlock( this->lock ); 217 return; 218 } 219 220 // Get the next thread, will be null on low contention monitor 221 thread_desc * new_owner = next_thread( this ); 222 223 // We can now let other threads in safely 224 unlock( this->lock ); 225 226 //We need to wake-up the thread 227 WakeThread( new_owner ); 228 } 229 230 // Leave single monitor for the last time 231 void __leave_dtor_monitor_desc( monitor_desc * this ) { 232 __cfaabi_dbg_debug_do( 233 if( TL_GET( this_thread ) != this->owner ) { 234 abort( "Destroyed monitor %p has inconsistent owner, expected %p got %p.\n", this, TL_GET( this_thread ), this->owner); 235 } 236 if( this->recursion != 1 ) { 237 abort( "Destroyed monitor %p has %d outstanding nested calls.\n", this, this->recursion - 1); 238 } 239 ) 240 } 241 261 ) 262 } 263 264 extern "C" { 242 265 // Leave the thread monitor 243 266 // last routine called by a thread. 244 267 // Should never return 245 void __ leave_thread_monitor() {246 thread_desc* thrd = TL_GET( this_thread );247 monitor_desc* this = &thrd->self_mon;268 void __cfactx_thrd_leave() { 269 $thread * thrd = TL_GET( this_thread ); 270 $monitor * this = &thrd->self_mon; 248 271 249 272 // Lock the monitor now … … 252 275 disable_interrupts(); 253 276 254 thrd->s elf_cor.state = Halted;255 256 verifyf( thrd == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", thrd, this->owner, this->recursion, this );277 thrd->state = Halted; 278 279 /* paranoid */ verifyf( thrd == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", thrd, this->owner, this->recursion, this ); 257 280 258 281 // Leaving a recursion level, decrement the counter … … 264 287 265 288 // Fetch the next thread, can be null 266 thread_desc * new_owner = next_thread( this ); 267 268 // Leave the thread, this will unlock the spinlock 269 // Use leave thread instead of BlockInternal which is 270 // specialized for this case and supports null new_owner 271 LeaveThread( &this->lock, new_owner ); 289 $thread * new_owner = next_thread( this ); 290 291 // Release the monitor lock 292 unlock( this->lock ); 293 294 // Unpark the next owner if needed 295 /* paranoid */ verifyf( !new_owner || new_owner == this->owner, "Expected owner to be %p, got %p (m: %p)", new_owner, this->owner, this ); 296 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); 297 /* paranoid */ verify( ! kernelTLS.this_processor->destroyer ); 298 /* paranoid */ verify( thrd->state == Halted ); 299 300 kernelTLS.this_processor->destroyer = new_owner; 301 302 // Leave the thread 303 __leave_thread(); 272 304 273 305 // Control flow should never reach here! … … 279 311 static inline void enter( __monitor_group_t monitors ) { 280 312 for( __lock_size_t i = 0; i < monitors.size; i++) { 281 __enter _monitor_desc( monitors[i], monitors );313 __enter( monitors[i], monitors ); 282 314 } 283 315 } … … 285 317 // Leave multiple monitor 286 318 // relies on the monitor array being sorted 287 static inline void leave( monitor_desc* monitors [], __lock_size_t count) {319 static inline void leave($monitor * monitors [], __lock_size_t count) { 288 320 for( __lock_size_t i = count - 1; i >= 0; i--) { 289 __leave _monitor_desc( monitors[i] );321 __leave( monitors[i] ); 290 322 } 291 323 } … … 293 325 // Ctor for monitor guard 294 326 // Sorts monitors before entering 295 void ?{}( monitor_guard_t & this, monitor_desc* m [], __lock_size_t count, fptr_t func ) {296 thread_desc* thrd = TL_GET( this_thread );327 void ?{}( monitor_guard_t & this, $monitor * m [], __lock_size_t count, fptr_t func ) { 328 $thread * thrd = TL_GET( this_thread ); 297 329 298 330 // Store current array … … 334 366 // Ctor for monitor guard 335 367 // Sorts monitors before entering 336 void ?{}( monitor_dtor_guard_t & this, monitor_desc* m [], fptr_t func ) {368 void ?{}( monitor_dtor_guard_t & this, $monitor * m [], fptr_t func ) { 337 369 // optimization 338 thread_desc* thrd = TL_GET( this_thread );370 $thread * thrd = TL_GET( this_thread ); 339 371 340 372 // Store current array … … 347 379 (thrd->monitors){m, 1, func}; 348 380 349 __ enter_monitor_dtor( this.m, func );381 __dtor_enter( this.m, func ); 350 382 } 351 383 … … 353 385 void ^?{}( monitor_dtor_guard_t & this ) { 354 386 // Leave the monitors in order 355 __ leave_dtor_monitor_desc( this.m );387 __dtor_leave( this.m ); 356 388 357 389 // Restore thread context … … 361 393 //----------------------------------------------------------------------------- 362 394 // Internal scheduling types 363 void ?{}(__condition_node_t & this, thread_desc* waiting_thread, __lock_size_t count, uintptr_t user_info ) {395 void ?{}(__condition_node_t & this, $thread * waiting_thread, __lock_size_t count, uintptr_t user_info ) { 364 396 this.waiting_thread = waiting_thread; 365 397 this.count = count; … … 375 407 } 376 408 377 void ?{}(__condition_criterion_t & this, monitor_desc* target, __condition_node_t & owner ) {409 void ?{}(__condition_criterion_t & this, $monitor * target, __condition_node_t & owner ) { 378 410 this.ready = false; 379 411 this.target = target; … … 400 432 // Append the current wait operation to the ones already queued on the condition 401 433 // We don't need locks for that since conditions must always be waited on inside monitor mutual exclusion 434 /* paranoid */ verify( waiter.next == 0p ); 402 435 append( this.blocked, &waiter ); 436 /* paranoid */ verify( waiter.next == 1p ); 403 437 404 438 // Lock all monitors (aggregates the locks as well) … … 407 441 // Find the next thread(s) to run 408 442 __lock_size_t thread_count = 0; 409 thread_desc* threads[ count ];443 $thread * threads[ count ]; 410 444 __builtin_memset( threads, 0, sizeof( threads ) ); 411 445 … … 415 449 // Remove any duplicate threads 416 450 for( __lock_size_t i = 0; i < count; i++) { 417 thread_desc* new_owner = next_thread( monitors[i] );451 $thread * new_owner = next_thread( monitors[i] ); 418 452 insert_unique( threads, thread_count, new_owner ); 419 453 } 420 454 455 // Unlock the locks, we don't need them anymore 456 for(int i = 0; i < count; i++) { 457 unlock( *locks[i] ); 458 } 459 460 // Wake the threads 461 for(int i = 0; i < thread_count; i++) { 462 unpark( threads[i] ); 463 } 464 421 465 // Everything is ready to go to sleep 422 BlockInternal( locks, count, threads, thread_count);466 park(); 423 467 424 468 // We are back, restore the owners and recursions … … 435 479 //Some more checking in debug 436 480 __cfaabi_dbg_debug_do( 437 thread_desc* this_thrd = TL_GET( this_thread );481 $thread * this_thrd = TL_GET( this_thread ); 438 482 if ( this.monitor_count != this_thrd->monitors.size ) { 439 483 abort( "Signal on condition %p made with different number of monitor(s), expected %zi got %zi", &this, this.monitor_count, this_thrd->monitors.size ); … … 489 533 490 534 //Find the thread to run 491 thread_desc * signallee = pop_head( this.blocked )->waiting_thread; 492 set_owner( monitors, count, signallee ); 535 $thread * signallee = pop_head( this.blocked )->waiting_thread; 536 /* paranoid */ verify( signallee->next == 0p ); 537 __set_owner( monitors, count, signallee ); 493 538 494 539 __cfaabi_dbg_print_buffer_decl( "Kernel : signal_block condition %p (s: %p)\n", &this, signallee ); 495 540 541 // unlock all the monitors 542 unlock_all( locks, count ); 543 544 // unpark the thread we signalled 545 unpark( signallee ); 546 496 547 //Everything is ready to go to sleep 497 BlockInternal( locks, count, &signallee, 1);548 park(); 498 549 499 550 … … 536 587 // Create one! 537 588 __lock_size_t max = count_max( mask ); 538 monitor_desc* mon_storage[max];589 $monitor * mon_storage[max]; 539 590 __builtin_memset( mon_storage, 0, sizeof( mon_storage ) ); 540 591 __lock_size_t actual_count = aggregate( mon_storage, mask ); … … 554 605 { 555 606 // Check if the entry queue 556 thread_desc* next; int index;607 $thread * next; int index; 557 608 [next, index] = search_entry_queue( mask, monitors, count ); 558 609 … … 564 615 verifyf( accepted.size == 1, "ERROR: Accepted dtor has more than 1 mutex parameter." ); 565 616 566 monitor_desc* mon2dtor = accepted[0];617 $monitor * mon2dtor = accepted[0]; 567 618 verifyf( mon2dtor->dtor_node, "ERROR: Accepted monitor has no dtor_node." ); 568 619 … … 590 641 591 642 // Set the owners to be the next thread 592 set_owner( monitors, count, next ); 593 594 // Everything is ready to go to sleep 595 BlockInternal( locks, count, &next, 1 ); 643 __set_owner( monitors, count, next ); 644 645 // unlock all the monitors 646 unlock_all( locks, count ); 647 648 // unpark the thread we signalled 649 unpark( next ); 650 651 //Everything is ready to go to sleep 652 park(); 596 653 597 654 // We are back, restore the owners and recursions … … 631 688 } 632 689 690 // unlock all the monitors 691 unlock_all( locks, count ); 692 633 693 //Everything is ready to go to sleep 634 BlockInternal( locks, count);694 park(); 635 695 636 696 … … 649 709 // Utilities 650 710 651 static inline void set_owner( monitor_desc * this, thread_desc* owner ) {652 / / __cfaabi_dbg_print_safe( "Kernal : Setting owner of %p to %p ( was %p)\n", this, owner, this->owner);711 static inline void __set_owner( $monitor * this, $thread * owner ) { 712 /* paranoid */ verify( this->lock.lock ); 653 713 654 714 //Pass the monitor appropriately … … 659 719 } 660 720 661 static inline void set_owner( monitor_desc * monitors [], __lock_size_t count, thread_desc * owner ) { 662 monitors[0]->owner = owner; 663 monitors[0]->recursion = 1; 721 static inline void __set_owner( $monitor * monitors [], __lock_size_t count, $thread * owner ) { 722 /* paranoid */ verify ( monitors[0]->lock.lock ); 723 /* paranoid */ verifyf( monitors[0]->owner == kernelTLS.this_thread, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, monitors[0]->owner, monitors[0]->recursion, monitors[0] ); 724 monitors[0]->owner = owner; 725 monitors[0]->recursion = 1; 664 726 for( __lock_size_t i = 1; i < count; i++ ) { 665 monitors[i]->owner = owner; 666 monitors[i]->recursion = 0; 667 } 668 } 669 670 static inline void set_mask( monitor_desc * storage [], __lock_size_t count, const __waitfor_mask_t & mask ) { 727 /* paranoid */ verify ( monitors[i]->lock.lock ); 728 /* paranoid */ verifyf( monitors[i]->owner == kernelTLS.this_thread, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, monitors[i]->owner, monitors[i]->recursion, monitors[i] ); 729 monitors[i]->owner = owner; 730 monitors[i]->recursion = 0; 731 } 732 } 733 734 static inline void set_mask( $monitor * storage [], __lock_size_t count, const __waitfor_mask_t & mask ) { 671 735 for( __lock_size_t i = 0; i < count; i++) { 672 736 storage[i]->mask = mask; … … 674 738 } 675 739 676 static inline void reset_mask( monitor_desc* this ) {740 static inline void reset_mask( $monitor * this ) { 677 741 this->mask.accepted = 0p; 678 742 this->mask.data = 0p; … … 680 744 } 681 745 682 static inline thread_desc * next_thread( monitor_desc* this ) {746 static inline $thread * next_thread( $monitor * this ) { 683 747 //Check the signaller stack 684 748 __cfaabi_dbg_print_safe( "Kernel : mon %p AS-stack top %p\n", this, this->signal_stack.top); … … 688 752 //regardless of if we are ready to baton pass, 689 753 //we need to set the monitor as in use 690 set_owner( this, urgent->owner->waiting_thread ); 754 /* paranoid */ verifyf( !this->owner || kernelTLS.this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 755 __set_owner( this, urgent->owner->waiting_thread ); 691 756 692 757 return check_condition( urgent ); … … 695 760 // No signaller thread 696 761 // Get the next thread in the entry_queue 697 thread_desc * new_owner = pop_head( this->entry_queue ); 698 set_owner( this, new_owner ); 762 $thread * new_owner = pop_head( this->entry_queue ); 763 /* paranoid */ verifyf( !this->owner || kernelTLS.this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", kernelTLS.this_thread, this->owner, this->recursion, this ); 764 /* paranoid */ verify( !new_owner || new_owner->next == 0p ); 765 __set_owner( this, new_owner ); 699 766 700 767 return new_owner; 701 768 } 702 769 703 static inline bool is_accepted( monitor_desc* this, const __monitor_group_t & group ) {770 static inline bool is_accepted( $monitor * this, const __monitor_group_t & group ) { 704 771 __acceptable_t * it = this->mask.data; // Optim 705 772 __lock_size_t count = this->mask.size; … … 723 790 } 724 791 725 static inline void init( __lock_size_t count, monitor_desc* monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ) {792 static inline void init( __lock_size_t count, $monitor * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ) { 726 793 for( __lock_size_t i = 0; i < count; i++) { 727 794 (criteria[i]){ monitors[i], waiter }; … … 731 798 } 732 799 733 static inline void init_push( __lock_size_t count, monitor_desc* monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ) {800 static inline void init_push( __lock_size_t count, $monitor * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ) { 734 801 for( __lock_size_t i = 0; i < count; i++) { 735 802 (criteria[i]){ monitors[i], waiter }; … … 747 814 } 748 815 749 static inline void lock_all( monitor_desc* source [], __spinlock_t * /*out*/ locks [], __lock_size_t count ) {816 static inline void lock_all( $monitor * source [], __spinlock_t * /*out*/ locks [], __lock_size_t count ) { 750 817 for( __lock_size_t i = 0; i < count; i++ ) { 751 818 __spinlock_t * l = &source[i]->lock; … … 761 828 } 762 829 763 static inline void unlock_all( monitor_desc* locks [], __lock_size_t count ) {830 static inline void unlock_all( $monitor * locks [], __lock_size_t count ) { 764 831 for( __lock_size_t i = 0; i < count; i++ ) { 765 832 unlock( locks[i]->lock ); … … 768 835 769 836 static inline void save( 770 monitor_desc* ctx [],837 $monitor * ctx [], 771 838 __lock_size_t count, 772 839 __attribute((unused)) __spinlock_t * locks [], … … 781 848 782 849 static inline void restore( 783 monitor_desc* ctx [],850 $monitor * ctx [], 784 851 __lock_size_t count, 785 852 __spinlock_t * locks [], … … 799 866 // 2 - Checks if all the monitors are ready to run 800 867 // if so return the thread to run 801 static inline thread_desc* check_condition( __condition_criterion_t * target ) {868 static inline $thread * check_condition( __condition_criterion_t * target ) { 802 869 __condition_node_t * node = target->owner; 803 870 unsigned short count = node->count; … … 822 889 823 890 static inline void brand_condition( condition & this ) { 824 thread_desc* thrd = TL_GET( this_thread );891 $thread * thrd = TL_GET( this_thread ); 825 892 if( !this.monitors ) { 826 893 // __cfaabi_dbg_print_safe( "Branding\n" ); … … 828 895 this.monitor_count = thrd->monitors.size; 829 896 830 this.monitors = ( monitor_desc**)malloc( this.monitor_count * sizeof( *this.monitors ) );897 this.monitors = ($monitor **)malloc( this.monitor_count * sizeof( *this.monitors ) ); 831 898 for( int i = 0; i < this.monitor_count; i++ ) { 832 899 this.monitors[i] = thrd->monitors[i]; … … 835 902 } 836 903 837 static inline [ thread_desc *, int] search_entry_queue( const __waitfor_mask_t & mask, monitor_desc* monitors [], __lock_size_t count ) {838 839 __queue_t( thread_desc) & entry_queue = monitors[0]->entry_queue;904 static inline [$thread *, int] search_entry_queue( const __waitfor_mask_t & mask, $monitor * monitors [], __lock_size_t count ) { 905 906 __queue_t($thread) & entry_queue = monitors[0]->entry_queue; 840 907 841 908 // For each thread in the entry-queue 842 for( thread_desc** thrd_it = &entry_queue.head;843 *thrd_it ;909 for( $thread ** thrd_it = &entry_queue.head; 910 *thrd_it != 1p; 844 911 thrd_it = &(*thrd_it)->next 845 912 ) { … … 884 951 } 885 952 886 static inline __lock_size_t aggregate( monitor_desc* storage [], const __waitfor_mask_t & mask ) {953 static inline __lock_size_t aggregate( $monitor * storage [], const __waitfor_mask_t & mask ) { 887 954 __lock_size_t size = 0; 888 955 for( __lock_size_t i = 0; i < mask.size; i++ ) { -
libcfa/src/concurrency/monitor.hfa
r41efd33 r04e6f93 23 23 24 24 trait is_monitor(dtype T) { 25 monitor_desc* get_monitor( T & );25 $monitor * get_monitor( T & ); 26 26 void ^?{}( T & mutex ); 27 27 }; 28 28 29 static inline void ?{}( monitor_desc& this) with( this ) {29 static inline void ?{}($monitor & this) with( this ) { 30 30 lock{}; 31 31 entry_queue{}; … … 39 39 } 40 40 41 static inline void ^?{}( monitor_desc& ) {}41 static inline void ^?{}($monitor & ) {} 42 42 43 43 struct monitor_guard_t { 44 monitor_desc** m;44 $monitor ** m; 45 45 __lock_size_t count; 46 46 __monitor_group_t prev; 47 47 }; 48 48 49 void ?{}( monitor_guard_t & this, monitor_desc** m, __lock_size_t count, void (*func)() );49 void ?{}( monitor_guard_t & this, $monitor ** m, __lock_size_t count, void (*func)() ); 50 50 void ^?{}( monitor_guard_t & this ); 51 51 52 52 struct monitor_dtor_guard_t { 53 monitor_desc* m;53 $monitor * m; 54 54 __monitor_group_t prev; 55 55 }; 56 56 57 void ?{}( monitor_dtor_guard_t & this, monitor_desc** m, void (*func)() );57 void ?{}( monitor_dtor_guard_t & this, $monitor ** m, void (*func)() ); 58 58 void ^?{}( monitor_dtor_guard_t & this ); 59 59 … … 72 72 73 73 // The monitor this criterion concerns 74 monitor_desc* target;74 $monitor * target; 75 75 76 76 // The parent node to which this criterion belongs … … 87 87 struct __condition_node_t { 88 88 // Thread that needs to be woken when all criteria are met 89 thread_desc* waiting_thread;89 $thread * waiting_thread; 90 90 91 91 // Array of criteria (Criterions are contiguous in memory) … … 106 106 } 107 107 108 void ?{}(__condition_node_t & this, thread_desc* waiting_thread, __lock_size_t count, uintptr_t user_info );108 void ?{}(__condition_node_t & this, $thread * waiting_thread, __lock_size_t count, uintptr_t user_info ); 109 109 void ?{}(__condition_criterion_t & this ); 110 void ?{}(__condition_criterion_t & this, monitor_desc* target, __condition_node_t * owner );110 void ?{}(__condition_criterion_t & this, $monitor * target, __condition_node_t * owner ); 111 111 112 112 struct condition { … … 115 115 116 116 // Array of monitor pointers (Monitors are NOT contiguous in memory) 117 monitor_desc** monitors;117 $monitor ** monitors; 118 118 119 119 // Number of monitors in the array … … 133 133 bool signal ( condition & this ); 134 134 bool signal_block( condition & this ); 135 static inline bool is_empty ( condition & this ) { return !this.blocked.head; }135 static inline bool is_empty ( condition & this ) { return this.blocked.head == 1p; } 136 136 uintptr_t front ( condition & this ); 137 137 -
libcfa/src/concurrency/mutex.cfa
r41efd33 r04e6f93 40 40 if( is_locked ) { 41 41 append( blocked_threads, kernelTLS.this_thread ); 42 BlockInternal( &lock ); 42 unlock( lock ); 43 park(); 43 44 } 44 45 else { … … 62 63 lock( this.lock __cfaabi_dbg_ctx2 ); 63 64 this.is_locked = (this.blocked_threads != 0); 64 WakeThread(65 unpark( 65 66 pop_head( this.blocked_threads ) 66 67 ); … … 94 95 else { 95 96 append( blocked_threads, kernelTLS.this_thread ); 96 BlockInternal( &lock ); 97 unlock( lock ); 98 park(); 97 99 } 98 100 } … … 118 120 recursion_count--; 119 121 if( recursion_count == 0 ) { 120 thread_desc* thrd = pop_head( blocked_threads );122 $thread * thrd = pop_head( blocked_threads ); 121 123 owner = thrd; 122 124 recursion_count = (thrd ? 1 : 0); 123 WakeThread( thrd );125 unpark( thrd ); 124 126 } 125 127 unlock( lock ); … … 138 140 void notify_one(condition_variable & this) with(this) { 139 141 lock( lock __cfaabi_dbg_ctx2 ); 140 WakeThread(142 unpark( 141 143 pop_head( this.blocked_threads ) 142 144 ); … … 147 149 lock( lock __cfaabi_dbg_ctx2 ); 148 150 while(this.blocked_threads) { 149 WakeThread(151 unpark( 150 152 pop_head( this.blocked_threads ) 151 153 ); … … 157 159 lock( this.lock __cfaabi_dbg_ctx2 ); 158 160 append( this.blocked_threads, kernelTLS.this_thread ); 159 BlockInternal( &this.lock ); 161 unlock( this.lock ); 162 park(); 160 163 } 161 164 … … 164 167 lock( this.lock __cfaabi_dbg_ctx2 ); 165 168 append( this.blocked_threads, kernelTLS.this_thread ); 166 void __unlock(void) { 167 unlock(l); 168 unlock(this.lock); 169 } 170 BlockInternal( __unlock ); 169 unlock(l); 170 unlock(this.lock); 171 park(); 171 172 lock(l); 172 173 } -
libcfa/src/concurrency/mutex.hfa
r41efd33 r04e6f93 36 36 37 37 // List of blocked threads 38 __queue_t(struct thread_desc) blocked_threads;38 __queue_t(struct $thread) blocked_threads; 39 39 40 40 // Locked flag … … 55 55 56 56 // List of blocked threads 57 __queue_t(struct thread_desc) blocked_threads;57 __queue_t(struct $thread) blocked_threads; 58 58 59 59 // Current thread owning the lock 60 struct thread_desc* owner;60 struct $thread * owner; 61 61 62 62 // Number of recursion level … … 83 83 84 84 // List of blocked threads 85 __queue_t(struct thread_desc) blocked_threads;85 __queue_t(struct $thread) blocked_threads; 86 86 }; 87 87 -
libcfa/src/concurrency/preemption.cfa
r41efd33 r04e6f93 39 39 // FwdDeclarations : timeout handlers 40 40 static void preempt( processor * this ); 41 static void timeout( thread_desc* this );41 static void timeout( $thread * this ); 42 42 43 43 // FwdDeclarations : Signal handlers … … 184 184 185 185 // Enable interrupts by decrementing the counter 186 // If counter reaches 0, execute any pending CtxSwitch186 // If counter reaches 0, execute any pending __cfactx_switch 187 187 void enable_interrupts( __cfaabi_dbg_ctx_param ) { 188 188 processor * proc = kernelTLS.this_processor; // Cache the processor now since interrupts can start happening after the atomic store 189 thread_desc * thrd = kernelTLS.this_thread; // Cache the thread now since interrupts can start happening after the atomic store190 189 191 190 with( kernelTLS.preemption_state ){ … … 209 208 if( proc->pending_preemption ) { 210 209 proc->pending_preemption = false; 211 BlockInternal( thrd);210 force_yield( __POLL_PREEMPTION ); 212 211 } 213 212 } … … 219 218 220 219 // Disable interrupts by incrementint the counter 221 // Don't execute any pending CtxSwitch even if counter reaches 0220 // Don't execute any pending __cfactx_switch even if counter reaches 0 222 221 void enable_interrupts_noPoll() { 223 222 unsigned short prev = kernelTLS.preemption_state.disable_count; … … 268 267 269 268 // reserved for future use 270 static void timeout( thread_desc* this ) {269 static void timeout( $thread * this ) { 271 270 //TODO : implement waking threads 272 271 } 273 272 274 273 // KERNEL ONLY 275 // Check if a CtxSwitch signal handler shoud defer274 // Check if a __cfactx_switch signal handler shoud defer 276 275 // If true : preemption is safe 277 276 // If false : preemption is unsafe and marked as pending … … 303 302 304 303 // Setup proper signal handlers 305 __cfaabi_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO | SA_RESTART ); // CtxSwitch handler304 __cfaabi_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO | SA_RESTART ); // __cfactx_switch handler 306 305 307 306 signal_block( SIGALRM ); 308 307 309 alarm_stack = create_pthread( &alarm_thread, alarm_loop, 0p );308 alarm_stack = __create_pthread( &alarm_thread, alarm_loop, 0p ); 310 309 } 311 310 … … 394 393 // Preemption can occur here 395 394 396 BlockInternal( kernelTLS.this_thread ); // Do the actual CtxSwitch395 force_yield( __ALARM_PREEMPTION ); // Do the actual __cfactx_switch 397 396 } 398 397 -
libcfa/src/concurrency/thread.cfa
r41efd33 r04e6f93 23 23 #include "invoke.h" 24 24 25 extern "C" {26 #include <fenv.h>27 #include <stddef.h>28 }29 30 //extern volatile thread_local processor * this_processor;31 32 25 //----------------------------------------------------------------------------- 33 26 // Thread ctors and dtors 34 void ?{}( thread_desc& this, const char * const name, cluster & cl, void * storage, size_t storageSize ) with( this ) {27 void ?{}($thread & this, const char * const name, cluster & cl, void * storage, size_t storageSize ) with( this ) { 35 28 context{ 0p, 0p }; 36 29 self_cor{ name, storage, storageSize }; 37 30 state = Start; 31 preempted = __NO_PREEMPTION; 38 32 curr_cor = &self_cor; 39 33 self_mon.owner = &this; … … 50 44 } 51 45 52 void ^?{}( thread_desc& this) with( this ) {46 void ^?{}($thread& this) with( this ) { 53 47 unregister(curr_cluster, this); 54 48 ^self_cor{}; 55 49 } 56 50 51 //----------------------------------------------------------------------------- 52 // Starting and stopping threads 53 forall( dtype T | is_thread(T) ) 54 void __thrd_start( T & this, void (*main_p)(T &) ) { 55 $thread * this_thrd = get_thread(this); 56 57 disable_interrupts(); 58 __cfactx_start(main_p, get_coroutine(this), this, __cfactx_invoke_thread); 59 60 this_thrd->context.[SP, FP] = this_thrd->self_cor.context.[SP, FP]; 61 verify( this_thrd->context.SP ); 62 63 __schedule_thread(this_thrd); 64 enable_interrupts( __cfaabi_dbg_ctx ); 65 } 66 67 //----------------------------------------------------------------------------- 68 // Support for threads that don't ues the thread keyword 57 69 forall( dtype T | sized(T) | is_thread(T) | { void ?{}(T&); } ) 58 70 void ?{}( scoped(T)& this ) with( this ) { … … 72 84 } 73 85 74 //-----------------------------------------------------------------------------75 // Starting and stopping threads76 forall( dtype T | is_thread(T) )77 void __thrd_start( T & this, void (*main_p)(T &) ) {78 thread_desc * this_thrd = get_thread(this);79 thread_desc * curr_thrd = TL_GET( this_thread );80 81 disable_interrupts();82 CtxStart(main_p, get_coroutine(this), this, CtxInvokeThread);83 84 this_thrd->context.[SP, FP] = this_thrd->self_cor.context.[SP, FP];85 verify( this_thrd->context.SP );86 // CtxSwitch( &curr_thrd->context, &this_thrd->context );87 88 ScheduleThread(this_thrd);89 enable_interrupts( __cfaabi_dbg_ctx );90 }91 92 void yield( void ) {93 // Safety note : This could cause some false positives due to preemption94 verify( TL_GET( preemption_state.enabled ) );95 BlockInternal( TL_GET( this_thread ) );96 // Safety note : This could cause some false positives due to preemption97 verify( TL_GET( preemption_state.enabled ) );98 }99 100 void yield( unsigned times ) {101 for( unsigned i = 0; i < times; i++ ) {102 yield();103 }104 }105 106 86 // Local Variables: // 107 87 // mode: c // -
libcfa/src/concurrency/thread.hfa
r41efd33 r04e6f93 28 28 void ^?{}(T& mutex this); 29 29 void main(T& this); 30 thread_desc* get_thread(T& this);30 $thread* get_thread(T& this); 31 31 }; 32 32 33 #define DECL_THREAD(X) thread_desc* get_thread(X& this) { return &this.__thrd; } void main(X& this) 33 // define that satisfies the trait without using the thread keyword 34 #define DECL_THREAD(X) $thread* get_thread(X& this) __attribute__((const)) { return &this.__thrd; } void main(X& this) 35 36 // Inline getters for threads/coroutines/monitors 37 forall( dtype T | is_thread(T) ) 38 static inline $coroutine* get_coroutine(T & this) __attribute__((const)) { return &get_thread(this)->self_cor; } 34 39 35 40 forall( dtype T | is_thread(T) ) 36 static inline coroutine_desc* get_coroutine(T & this) { 37 return &get_thread(this)->self_cor; 38 } 41 static inline $monitor * get_monitor (T & this) __attribute__((const)) { return &get_thread(this)->self_mon; } 39 42 40 forall( dtype T | is_thread(T) ) 41 static inline monitor_desc* get_monitor(T & this) { 42 return &get_thread(this)->self_mon; 43 } 43 static inline $coroutine* get_coroutine($thread * this) __attribute__((const)) { return &this->self_cor; } 44 static inline $monitor * get_monitor ($thread * this) __attribute__((const)) { return &this->self_mon; } 44 45 45 static inline coroutine_desc* get_coroutine(thread_desc * this) { 46 return &this->self_cor; 47 } 48 49 static inline monitor_desc* get_monitor(thread_desc * this) { 50 return &this->self_mon; 51 } 52 46 //----------------------------------------------------------------------------- 47 // forward declarations needed for threads 53 48 extern struct cluster * mainCluster; 54 49 … … 58 53 //----------------------------------------------------------------------------- 59 54 // Ctors and dtors 60 void ?{}( thread_desc& this, const char * const name, struct cluster & cl, void * storage, size_t storageSize );61 void ^?{}( thread_desc& this);55 void ?{}($thread & this, const char * const name, struct cluster & cl, void * storage, size_t storageSize ); 56 void ^?{}($thread & this); 62 57 63 static inline void ?{}( thread_desc& this) { this{ "Anonymous Thread", *mainCluster, 0p, 65000 }; }64 static inline void ?{}( thread_desc& this, size_t stackSize ) { this{ "Anonymous Thread", *mainCluster, 0p, stackSize }; }65 static inline void ?{}( thread_desc& this, void * storage, size_t storageSize ) { this{ "Anonymous Thread", *mainCluster, storage, storageSize }; }66 static inline void ?{}( thread_desc& this, struct cluster & cl ) { this{ "Anonymous Thread", cl, 0p, 65000 }; }67 static inline void ?{}( thread_desc& this, struct cluster & cl, size_t stackSize ) { this{ "Anonymous Thread", cl, 0p, stackSize }; }68 static inline void ?{}( thread_desc& this, struct cluster & cl, void * storage, size_t storageSize ) { this{ "Anonymous Thread", cl, storage, storageSize }; }69 static inline void ?{}( thread_desc& this, const char * const name) { this{ name, *mainCluster, 0p, 65000 }; }70 static inline void ?{}( thread_desc& this, const char * const name, struct cluster & cl ) { this{ name, cl, 0p, 65000 }; }71 static inline void ?{}( thread_desc& this, const char * const name, struct cluster & cl, size_t stackSize ) { this{ name, cl, 0p, stackSize }; }58 static inline void ?{}($thread & this) { this{ "Anonymous Thread", *mainCluster, 0p, 65000 }; } 59 static inline void ?{}($thread & this, size_t stackSize ) { this{ "Anonymous Thread", *mainCluster, 0p, stackSize }; } 60 static inline void ?{}($thread & this, void * storage, size_t storageSize ) { this{ "Anonymous Thread", *mainCluster, storage, storageSize }; } 61 static inline void ?{}($thread & this, struct cluster & cl ) { this{ "Anonymous Thread", cl, 0p, 65000 }; } 62 static inline void ?{}($thread & this, struct cluster & cl, size_t stackSize ) { this{ "Anonymous Thread", cl, 0p, stackSize }; } 63 static inline void ?{}($thread & this, struct cluster & cl, void * storage, size_t storageSize ) { this{ "Anonymous Thread", cl, storage, storageSize }; } 64 static inline void ?{}($thread & this, const char * const name) { this{ name, *mainCluster, 0p, 65000 }; } 65 static inline void ?{}($thread & this, const char * const name, struct cluster & cl ) { this{ name, cl, 0p, 65000 }; } 66 static inline void ?{}($thread & this, const char * const name, struct cluster & cl, size_t stackSize ) { this{ name, cl, 0p, stackSize }; } 72 67 73 68 //----------------------------------------------------------------------------- … … 88 83 void ^?{}( scoped(T)& this ); 89 84 90 void yield(); 91 void yield( unsigned times ); 85 //----------------------------------------------------------------------------- 86 // Thread getters 87 static inline struct $thread * active_thread () { return TL_GET( this_thread ); } 92 88 93 static inline struct thread_desc * active_thread () { return TL_GET( this_thread ); } 89 //----------------------------------------------------------------------------- 90 // Scheduler API 91 92 //---------- 93 // Park thread: block until corresponding call to unpark, won't block if unpark is already called 94 void park( void ); 95 96 //---------- 97 // Unpark a thread, if the thread is already blocked, schedule it 98 // if the thread is not yet block, signal that it should rerun immediately 99 void unpark( $thread * this ); 100 101 forall( dtype T | is_thread(T) ) 102 static inline void unpark( T & this ) { if(!&this) return; unpark( get_thread( this ) );} 103 104 //---------- 105 // Yield: force thread to block and be rescheduled 106 bool force_yield( enum __Preemption_Reason ); 107 108 static inline void yield() { 109 force_yield(__MANUAL_PREEMPTION); 110 } 111 112 // Yield: yield N times 113 static inline void yield( unsigned times ) { 114 for( times ) { 115 yield(); 116 } 117 } 94 118 95 119 // Local Variables: // -
libcfa/src/exception.c
r41efd33 r04e6f93 248 248 } 249 249 250 #if defined(PIC) 251 #warning Exceptions not yet supported when using Position-Independent Code 252 __attribute__((noinline)) 253 void __cfaabi_ehm__try_terminate(void (*try_block)(), 254 void (*catch_block)(int index, exception_t * except), 255 __attribute__((unused)) int (*match_block)(exception_t * except)) { 256 abort(); 257 } 258 #else // PIC 250 #pragma GCC push_options 251 #pragma GCC optimize("O0") 252 259 253 // This is our personality routine. For every stack frame annotated with 260 254 // ".cfi_personality 0x3,__gcfa_personality_v0" this function will be called twice when unwinding. … … 431 425 432 426 // Setup the personality routine and exception table. 427 #ifdef __PIC__ 428 asm volatile (".cfi_personality 0x9b,CFA.ref.__gcfa_personality_v0"); 429 asm volatile (".cfi_lsda 0x1b, .LLSDACFA2"); 430 #else 433 431 asm volatile (".cfi_personality 0x3,__gcfa_personality_v0"); 434 432 asm volatile (".cfi_lsda 0x3, .LLSDACFA2"); 433 #endif 435 434 436 435 // Label which defines the start of the area for which the handler is setup. … … 464 463 // have a single call to the try routine. 465 464 465 #ifdef __PIC__ 466 #if defined( __i386 ) || defined( __x86_64 ) 467 asm ( 468 // HEADER 469 ".LFECFA1:\n" 470 " .globl __gcfa_personality_v0\n" 471 " .section .gcc_except_table,\"a\",@progbits\n" 472 // TABLE HEADER (important field is the BODY length at the end) 473 ".LLSDACFA2:\n" 474 " .byte 0xff\n" 475 " .byte 0xff\n" 476 " .byte 0x1\n" 477 " .uleb128 .LLSDACSECFA2-.LLSDACSBCFA2\n" 478 // BODY (language specific data) 479 // This uses language specific data and can be modified arbitrarily 480 // We use handled area offset, handled area length, 481 // handler landing pad offset and 1 (action code, gcc seems to use 0). 482 ".LLSDACSBCFA2:\n" 483 " .uleb128 .TRYSTART-__cfaabi_ehm__try_terminate\n" 484 " .uleb128 .TRYEND-.TRYSTART\n" 485 " .uleb128 .CATCH-__cfaabi_ehm__try_terminate\n" 486 " .uleb128 1\n" 487 ".LLSDACSECFA2:\n" 488 // TABLE FOOTER 489 " .text\n" 490 " .size __cfaabi_ehm__try_terminate, .-__cfaabi_ehm__try_terminate\n" 491 ); 492 493 // Somehow this piece of helps with the resolution of debug symbols. 494 __attribute__((unused)) static const int dummy = 0; 495 496 asm ( 497 // Add a hidden symbol which points at the function. 498 " .hidden CFA.ref.__gcfa_personality_v0\n" 499 " .weak CFA.ref.__gcfa_personality_v0\n" 500 // No clue what this does specifically 501 " .section .data.rel.local.CFA.ref.__gcfa_personality_v0,\"awG\",@progbits,CFA.ref.__gcfa_personality_v0,comdat\n" 502 " .align 8\n" 503 " .type CFA.ref.__gcfa_personality_v0, @object\n" 504 " .size CFA.ref.__gcfa_personality_v0, 8\n" 505 "CFA.ref.__gcfa_personality_v0:\n" 506 #if defined( __x86_64 ) 507 " .quad __gcfa_personality_v0\n" 508 #else // then __i386 509 " .long __gcfa_personality_v0\n" 510 #endif 511 ); 512 #else 513 #error Exception Handling: unknown architecture for position independent code. 514 #endif // __i386 || __x86_64 515 #else // __PIC__ 466 516 #if defined( __i386 ) || defined( __x86_64 ) 467 517 asm ( … … 491 541 " .size __cfaabi_ehm__try_terminate, .-__cfaabi_ehm__try_terminate\n" 492 542 " .ident \"GCC: (Ubuntu 6.2.0-3ubuntu11~16.04) 6.2.0 20160901\"\n" 493 //" .section .note.GNU-stack,\"x\",@progbits\n"543 " .section .note.GNU-stack,\"x\",@progbits\n" 494 544 ); 545 #else 546 #error Exception Handling: unknown architecture for position dependent code. 495 547 #endif // __i386 || __x86_64 496 #endif // PIC 548 #endif // __PIC__ 549 550 #pragma GCC pop_options -
libcfa/src/fstream.hfa
r41efd33 r04e6f93 10 10 // Created On : Wed May 27 17:56:53 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Feb 7 19:00:51202013 // Update Count : 17 412 // Last Modified On : Mon Feb 17 08:29:23 2020 13 // Update Count : 175 14 14 // 15 15 … … 67 67 void close( ofstream & ); 68 68 ofstream & write( ofstream &, const char data[], size_t size ); 69 int fmt( ofstream &, const char format[], ... ) ;69 int fmt( ofstream &, const char format[], ... ) __attribute__(( format(printf, 2, 3) )); 70 70 71 71 void ?{}( ofstream & os ); … … 97 97 ifstream & read( ifstream & is, char * data, size_t size ); 98 98 ifstream & ungetc( ifstream & is, char c ); 99 int fmt( ifstream &, const char format[], ... ) ;99 int fmt( ifstream &, const char format[], ... ) __attribute__(( format(scanf, 2, 3) )); 100 100 101 101 void ?{}( ifstream & is ); -
libcfa/src/interpose.cfa
r41efd33 r04e6f93 10 10 // Created On : Wed Mar 29 16:10:31 2017 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Sat Feb 8 08:40:34202013 // Update Count : 16 312 // Last Modified On : Mon Feb 17 10:18:53 2020 13 // Update Count : 166 14 14 // 15 15 … … 237 237 if ( fmt[strlen( fmt ) - 1] != '\n' ) { // add optional newline if missing at the end of the format text 238 238 __cfaabi_dbg_write( "\n", 1 ); 239 } 240 239 } // if 241 240 kernel_abort_msg( kernel_data, abort_text, abort_text_size ); 242 __cfaabi_backtrace( signalAbort ? 4 : 3 ); 241 242 __cfaabi_backtrace( signalAbort ? 4 : 2 ); 243 243 244 244 __cabi_libc.abort(); // print stack trace in handler -
libcfa/src/iostream.cfa
r41efd33 r04e6f93 10 10 // Created On : Wed May 27 17:56:53 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Feb 7 18:48:38202013 // Update Count : 82 512 // Last Modified On : Thu Feb 20 15:53:23 2020 13 // Update Count : 829 14 14 // 15 15 … … 19 19 #include <stdio.h> 20 20 #include <stdbool.h> // true/false 21 #include <stdint.h> // UINT64_MAX 21 22 //#include <string.h> // strlen, strcmp 22 23 extern size_t strlen (const char *__s) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))); … … 159 160 (ostype &)(os | ulli); ends( os ); 160 161 } // ?|? 162 163 #if defined( __SIZEOF_INT128__ ) 164 // UINT64_MAX 18_446_744_073_709_551_615_ULL 165 #define P10_UINT64 10_000_000_000_000_000_000_ULL // 19 zeroes 166 167 static void base10_128( ostype & os, unsigned int128 val ) { 168 if ( val > UINT64_MAX ) { 169 base10_128( os, val / P10_UINT64 ); // recursive 170 fmt( os, "%.19lu", (uint64_t)(val % P10_UINT64) ); 171 } else { 172 fmt( os, "%lu", (uint64_t)val ); 173 } // if 174 } // base10_128 175 176 static void base10_128( ostype & os, int128 val ) { 177 if ( val < 0 ) { 178 fmt( os, "-" ); // leading negative sign 179 val = -val; 180 } // if 181 base10_128( os, (unsigned int128)val ); // print zero/positive value 182 } // base10_128 183 184 ostype & ?|?( ostype & os, int128 llli ) { 185 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) ); 186 base10_128( os, llli ); 187 return os; 188 } // ?|? 189 void & ?|?( ostype & os, int128 llli ) { 190 (ostype &)(os | llli); ends( os ); 191 } // ?|? 192 193 ostype & ?|?( ostype & os, unsigned int128 ullli ) { 194 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) ); 195 base10_128( os, ullli ); 196 return os; 197 } // ?|? 198 void & ?|?( ostype & os, unsigned int128 ullli ) { 199 (ostype &)(os | ullli); ends( os ); 200 } // ?|? 201 #endif // __SIZEOF_INT128__ 161 202 162 203 #define PrintWithDP( os, format, val, ... ) \ … … 464 505 \ 465 506 if ( ! f.flags.pc ) { /* no precision */ \ 466 /* printf( "%s\n", &fmtstr[star] ); */ \467 507 fmtstr[sizeof(IFMTNP)-2] = f.base; /* sizeof includes '\0' */ \ 508 /* printf( "%s %c %c\n", &fmtstr[star], f.base, CODE ); */ \ 468 509 fmt( os, &fmtstr[star], f.wd, f.val ); \ 469 510 } else { /* precision */ \ 470 511 fmtstr[sizeof(IFMTP)-2] = f.base; /* sizeof includes '\0' */ \ 471 /* printf( "%s \n", &fmtstr[star]); */ \512 /* printf( "%s %c %c\n", &fmtstr[star], f.base, CODE ); */ \ 472 513 fmt( os, &fmtstr[star], f.wd, f.pc, f.val ); \ 473 514 } /* if */ \ … … 487 528 IntegralFMTImpl( signed long long int, 'd', "% *ll ", "% *.*ll " ) 488 529 IntegralFMTImpl( unsigned long long int, 'u', "% *ll ", "% *.*ll " ) 530 531 532 #if defined( __SIZEOF_INT128__ ) 533 // Default prefix for non-decimal prints is 0b, 0, 0x. 534 #define IntegralFMTImpl128( T, SIGNED, CODE, IFMTNP, IFMTP ) \ 535 forall( dtype ostype | ostream( ostype ) ) \ 536 static void base10_128( ostype & os, _Ostream_Manip(T) fmt ) { \ 537 if ( fmt.val > UINT64_MAX ) { \ 538 fmt.val /= P10_UINT64; \ 539 base10_128( os, fmt ); /* recursive */ \ 540 _Ostream_Manip(unsigned long long int) fmt2 @= { (uint64_t)(fmt.val % P10_UINT64), 0, 19, 'u', { .all : 0 } }; \ 541 fmt2.flags.nobsdp = true; \ 542 printf( "fmt2 %c %lld %d\n", fmt2.base, fmt2.val, fmt2.all ); \ 543 sepOff( os ); \ 544 (ostype &)(os | fmt2); \ 545 } else { \ 546 printf( "fmt %c %lld %d\n", fmt.base, fmt.val, fmt.all ); \ 547 (ostype &)(os | fmt); \ 548 } /* if */ \ 549 } /* base10_128 */ \ 550 forall( dtype ostype | ostream( ostype ) ) { \ 551 ostype & ?|?( ostype & os, _Ostream_Manip(T) f ) { \ 552 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) ); \ 553 \ 554 if ( f.base == 'b' | f.base == 'o' | f.base == 'x' | f.base == 'X' ) { \ 555 unsigned long long int msig = (unsigned long long int)(f.val >> 64); \ 556 unsigned long long int lsig = (unsigned long long int)(f.val); \ 557 _Ostream_Manip(SIGNED long long int) fmt @= { msig, f.wd, f.pc, f.base, { .all : f.all } }; \ 558 _Ostream_Manip(unsigned long long int) fmt2 @= { lsig, 0, 0, f.base, { .all : 0 } }; \ 559 if ( msig == 0 ) { \ 560 fmt.val = lsig; \ 561 (ostype &)(os | fmt); \ 562 } else { \ 563 fmt2.flags.pad0 = fmt2.flags.nobsdp = true; \ 564 if ( f.base == 'b' ) { \ 565 if ( f.wd > 64 ) fmt.wd = f.wd - 64; \ 566 fmt2.wd = 64; \ 567 (ostype &)(os | fmt | "" | fmt2); \ 568 } else if ( f.base == 'o' ) { \ 569 fmt.val = (unsigned long long int)fmt.val >> 2; \ 570 if ( f.wd > 21 ) fmt.wd = f.wd - 21; \ 571 fmt2.wd = 1; \ 572 fmt2.val = ((msig & 0x3) << 1) + 1; \ 573 (ostype &)(os | fmt | "" | fmt2); \ 574 sepOff( os ); \ 575 fmt2.wd = 21; \ 576 fmt2.val = lsig & 0x7fffffffffffffff; \ 577 (ostype &)(os | fmt2); \ 578 } else { \ 579 if ( f.flags.left ) { \ 580 if ( f.wd > 16 ) fmt2.wd = f.wd - 16; \ 581 fmt.wd = 16; \ 582 } else { \ 583 if ( f.wd > 16 ) fmt.wd = f.wd - 16; \ 584 fmt2.wd = 16; \ 585 } /* if */ \ 586 (ostype &)(os | fmt | "" | fmt2); \ 587 } /* if */ \ 588 } /* if */ \ 589 } else { \ 590 base10_128( os, f ); \ 591 } /* if */ \ 592 return os; \ 593 } /* ?|? */ \ 594 void ?|?( ostype & os, _Ostream_Manip(T) f ) { (ostype &)(os | f); ends( os ); } \ 595 } // distribution 596 597 IntegralFMTImpl128( int128, signed, 'd', "% *ll ", "% *.*ll " ) 598 IntegralFMTImpl128( unsigned int128, unsigned, 'u', "% *ll ", "% *.*ll " ) 599 #endif // __SIZEOF_INT128__ 489 600 490 601 //*********************************** floating point *********************************** -
libcfa/src/iostream.hfa
r41efd33 r04e6f93 10 10 // Created On : Wed May 27 17:56:53 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Feb 7 17:53:52202013 // Update Count : 33 612 // Last Modified On : Thu Feb 20 15:30:56 2020 13 // Update Count : 337 14 14 // 15 15 … … 98 98 ostype & ?|?( ostype &, unsigned long long int ); 99 99 void ?|?( ostype &, unsigned long long int ); 100 #if defined( __SIZEOF_INT128__ ) 101 ostype & ?|?( ostype &, int128 ); 102 void ?|?( ostype &, int128 ); 103 ostype & ?|?( ostype &, unsigned int128 ); 104 void ?|?( ostype &, unsigned int128 ); 105 #endif // __SIZEOF_INT128__ 100 106 101 107 ostype & ?|?( ostype &, float ); … … 206 212 IntegralFMTDecl( signed long long int, 'd' ) 207 213 IntegralFMTDecl( unsigned long long int, 'u' ) 214 #if defined( __SIZEOF_INT128__ ) 215 IntegralFMTDecl( int128, 'd' ) 216 IntegralFMTDecl( unsigned int128, 'u' ) 217 #endif 208 218 209 219 //*********************************** floating point *********************************** -
longrun_tests/Makefile.in
r41efd33 r04e6f93 502 502 am__v_GOC_0 = @echo " GOC " $@; 503 503 am__v_GOC_1 = 504 AM_V_PY = $(am__v_PY_@AM_V@) 505 am__v_PY_ = $(am__v_PY_@AM_DEFAULT_V@) 506 am__v_PY_0 = @echo " PYTHON " $@; 507 am__v_PY_1 = 504 508 AM_V_RUST = $(am__v_RUST_@AM_V@) 505 509 am__v_RUST_ = $(am__v_RUST_@AM_DEFAULT_V@) 506 am__v_RUST_0 = @echo " RUST 510 am__v_RUST_0 = @echo " RUST " $@; 507 511 am__v_RUST_1 = 508 512 AM_V_NODEJS = $(am__v_NODEJS_@AM_V@) 509 513 am__v_NODEJS_ = $(am__v_NODEJS_@AM_DEFAULT_V@) 510 am__v_NODEJS_0 = @echo " NODEJS 514 am__v_NODEJS_0 = @echo " NODEJS " $@; 511 515 am__v_NODEJS_1 = 512 516 AM_V_JAVAC = $(am__v_JAVAC_@AM_V@) -
src/CodeGen/CodeGenerator.cc
r41efd33 r04e6f93 10 10 // Created On : Mon May 18 07:44:20 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Dec 13 23:13:28 201913 // Update Count : 5 0812 // Last Modified On : Sun Feb 16 08:32:48 2020 13 // Update Count : 532 14 14 // 15 15 #include "CodeGenerator.h" … … 39 39 int CodeGenerator::tabsize = 4; 40 40 41 // the kinds of statements that would ideally be followed by whitespace41 // The kinds of statements that would ideally be followed by whitespace. 42 42 bool wantSpacing( Statement * stmt) { 43 43 return dynamic_cast< IfStmt * >( stmt ) || dynamic_cast< CompoundStmt * >( stmt ) || … … 78 78 } 79 79 80 /* Using updateLocation at the beginning of a node and endl 81 * within a node should become the method of formating. 82 */ 80 // Using updateLocation at the beginning of a node and endl within a node should become the method of formating. 83 81 void CodeGenerator::updateLocation( CodeLocation const & to ) { 84 82 // skip if linemarks shouldn't appear or if codelocation is unset … … 95 93 } else { 96 94 output << "\n# " << to.first_line << " \"" << to.filename 97 95 << "\"\n" << indent; 98 96 currentLocation = to; 99 97 } … … 131 129 132 130 void CodeGenerator::genAttributes( list< Attribute * > & attributes ) { 133 131 if ( attributes.empty() ) return; 134 132 output << "__attribute__ (("; 135 133 for ( list< Attribute * >::iterator attr( attributes.begin() );; ) { … … 140 138 output << ")"; 141 139 } // if 142 140 if ( ++attr == attributes.end() ) break; 143 141 output << ","; // separator 144 142 } // for … … 165 163 previsit( (BaseSyntaxNode *)node ); 166 164 GuardAction( [this, node](){ 167 if ( options.printExprTypes && node->result ) {168 output << " /* " << genType( node->result, "", options ) << " */ ";169 }170 } );165 if ( options.printExprTypes && node->result ) { 166 output << " /* " << genType( node->result, "", options ) << " */ "; 167 } 168 } ); 171 169 } 172 170 … … 399 397 extension( applicationExpr ); 400 398 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr* >( applicationExpr->get_function() ) ) { 401 OperatorInfoopInfo;402 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( varExpr->get_var()->get_name(), opInfo) ) {399 const OperatorInfo * opInfo; 400 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && ( opInfo = operatorLookup( varExpr->get_var()->get_name() ) ) ) { 403 401 std::list< Expression* >::iterator arg = applicationExpr->get_args().begin(); 404 switch ( opInfo .type ) {402 switch ( opInfo->type ) { 405 403 case OT_INDEX: 406 404 assert( applicationExpr->get_args().size() == 2 ); … … 423 421 output << "("; 424 422 (*arg++)->accept( *visitor ); 425 output << ") /* " << opInfo .inputName << " */";423 output << ") /* " << opInfo->inputName << " */"; 426 424 } else if ( applicationExpr->get_args().size() == 2 ) { 427 425 // intrinsic two parameter constructors are essentially bitwise assignment 428 426 output << "("; 429 427 (*arg++)->accept( *visitor ); 430 output << opInfo .symbol;428 output << opInfo->symbol; 431 429 (*arg)->accept( *visitor ); 432 output << ") /* " << opInfo .inputName << " */";430 output << ") /* " << opInfo->inputName << " */"; 433 431 } else { 434 432 // no constructors with 0 or more than 2 parameters … … 441 439 assert( applicationExpr->get_args().size() == 1 ); 442 440 output << "("; 443 output << opInfo .symbol;441 output << opInfo->symbol; 444 442 (*arg)->accept( *visitor ); 445 443 output << ")"; … … 450 448 assert( applicationExpr->get_args().size() == 1 ); 451 449 (*arg)->accept( *visitor ); 452 output << opInfo .symbol;450 output << opInfo->symbol; 453 451 break; 454 452 … … 459 457 output << "("; 460 458 (*arg++)->accept( *visitor ); 461 output << opInfo .symbol;459 output << opInfo->symbol; 462 460 (*arg)->accept( *visitor ); 463 461 output << ")"; … … 486 484 extension( untypedExpr ); 487 485 if ( NameExpr * nameExpr = dynamic_cast< NameExpr* >( untypedExpr->function ) ) { 488 OperatorInfo opInfo;489 if ( op eratorLookup( nameExpr->name, opInfo )) {486 const OperatorInfo * opInfo = operatorLookup( nameExpr->name ); 487 if ( opInfo ) { 490 488 std::list< Expression* >::iterator arg = untypedExpr->args.begin(); 491 switch ( opInfo .type ) {489 switch ( opInfo->type ) { 492 490 case OT_INDEX: 493 491 assert( untypedExpr->args.size() == 2 ); … … 508 506 output << "("; 509 507 (*arg++)->accept( *visitor ); 510 output << ") /* " << opInfo .inputName << " */";508 output << ") /* " << opInfo->inputName << " */"; 511 509 } else if ( untypedExpr->get_args().size() == 2 ) { 512 510 // intrinsic two parameter constructors are essentially bitwise assignment 513 511 output << "("; 514 512 (*arg++)->accept( *visitor ); 515 output << opInfo .symbol;513 output << opInfo->symbol; 516 514 (*arg)->accept( *visitor ); 517 output << ") /* " << opInfo .inputName << " */";515 output << ") /* " << opInfo->inputName << " */"; 518 516 } else { 519 517 // no constructors with 0 or more than 2 parameters … … 521 519 output << "("; 522 520 (*arg++)->accept( *visitor ); 523 output << opInfo .symbol << "{ ";521 output << opInfo->symbol << "{ "; 524 522 genCommaList( arg, untypedExpr->args.end() ); 525 output << "}) /* " << opInfo .inputName << " */";523 output << "}) /* " << opInfo->inputName << " */"; 526 524 } // if 527 525 break; … … 532 530 assert( untypedExpr->args.size() == 1 ); 533 531 output << "("; 534 output << opInfo .symbol;532 output << opInfo->symbol; 535 533 (*arg)->accept( *visitor ); 536 534 output << ")"; … … 541 539 assert( untypedExpr->args.size() == 1 ); 542 540 (*arg)->accept( *visitor ); 543 output << opInfo .symbol;541 output << opInfo->symbol; 544 542 break; 545 543 … … 549 547 output << "("; 550 548 (*arg++)->accept( *visitor ); 551 output << opInfo .symbol;549 output << opInfo->symbol; 552 550 (*arg)->accept( *visitor ); 553 551 output << ")"; … … 581 579 void CodeGenerator::postvisit( NameExpr * nameExpr ) { 582 580 extension( nameExpr ); 583 OperatorInfo opInfo;584 if ( op eratorLookup( nameExpr->name, opInfo )) {585 if ( opInfo .type == OT_CONSTANT ) {586 output << opInfo .symbol;581 const OperatorInfo * opInfo = operatorLookup( nameExpr->name ); 582 if ( opInfo ) { 583 if ( opInfo->type == OT_CONSTANT ) { 584 output << opInfo->symbol; 587 585 } else { 588 output << opInfo .outputName;586 output << opInfo->outputName; 589 587 } 590 588 } else { … … 654 652 void CodeGenerator::postvisit( VariableExpr * variableExpr ) { 655 653 extension( variableExpr ); 656 OperatorInfoopInfo;657 if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( variableExpr->get_var()->get_name(), opInfo ) && opInfo.type == OT_CONSTANT ) {658 output << opInfo .symbol;654 const OperatorInfo * opInfo; 655 if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && (opInfo = operatorLookup( variableExpr->get_var()->get_name() )) && opInfo->type == OT_CONSTANT ) { 656 output << opInfo->symbol; 659 657 } else { 660 658 output << mangleName( variableExpr->get_var() ); … … 1011 1009 case BranchStmt::FallThroughDefault: 1012 1010 assertf( ! options.genC, "fallthru should not reach code generation." ); 1013 1011 output << "fallthru"; 1014 1012 break; 1015 1013 } // switch … … 1035 1033 1036 1034 output << ((throwStmt->get_kind() == ThrowStmt::Terminate) ? 1037 1035 "throw" : "throwResume"); 1038 1036 if (throwStmt->get_expr()) { 1039 1037 output << " "; … … 1050 1048 1051 1049 output << ((stmt->get_kind() == CatchStmt::Terminate) ? 1052 "catch" : "catchResume");1050 "catch" : "catchResume"); 1053 1051 output << "( "; 1054 1052 stmt->decl->accept( *visitor ); … … 1187 1185 1188 1186 std::string genName( DeclarationWithType * decl ) { 1189 CodeGen::OperatorInfo opInfo;1190 if ( op eratorLookup( decl->get_name(), opInfo )) {1191 return opInfo .outputName;1187 const OperatorInfo * opInfo = operatorLookup( decl->get_name() ); 1188 if ( opInfo ) { 1189 return opInfo->outputName; 1192 1190 } else { 1193 1191 return decl->get_name(); -
src/CodeGen/CodeGenerator.h
r41efd33 r04e6f93 9 9 // Author : Richard C. Bilson 10 10 // Created On : Mon May 18 07:44:20 2015 11 // Last Modified By : Andrew Beach12 // Last Modified On : Tue Apr 30 12:01:00 201913 // Update Count : 5711 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Sun Feb 16 03:58:31 2020 13 // Update Count : 62 14 14 // 15 15 … … 29 29 namespace CodeGen { 30 30 struct CodeGenerator : public WithShortCircuiting, public WithGuards, public WithVisitorRef<CodeGenerator> { 31 31 static int tabsize; 32 32 33 33 CodeGenerator( std::ostream &os, bool pretty = false, bool genC = false, bool lineMarks = false, bool printExprTypes = false ); … … 104 104 void postvisit( AsmStmt * ); 105 105 void postvisit( DirectiveStmt * ); 106 void postvisit( AsmDecl * ); // special: statement in declaration context106 void postvisit( AsmDecl * ); // special: statement in declaration context 107 107 void postvisit( IfStmt * ); 108 108 void postvisit( SwitchStmt * ); … … 147 147 LabelPrinter printLabels; 148 148 Options options; 149 public:149 public: 150 150 LineEnder endl; 151 private:151 private: 152 152 153 153 CodeLocation currentLocation; … … 162 162 template< class Iterator > 163 163 void CodeGenerator::genCommaList( Iterator begin, Iterator end ) { 164 164 if ( begin == end ) return; 165 165 for ( ;; ) { 166 166 (*begin++)->accept( *visitor ); 167 167 if ( begin == end ) break; 168 168 output << ", "; // separator 169 169 } // for -
src/CodeGen/FixMain.h
r41efd33 r04e6f93 10 10 // Created On : Thr Jan 12 14:11:09 2017 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Dec 13 23:12:21 201913 // Update Count : 312 // Last Modified On : Sun Feb 16 03:24:32 2020 13 // Update Count : 5 14 14 // 15 15 … … 42 42 static std::unique_ptr<FunctionDecl> main_signature; 43 43 }; 44 } ;44 } // namespace CodeGen -
src/CodeGen/GenType.h
r41efd33 r04e6f93 9 9 // Author : Richard C. Bilson 10 10 // Created On : Mon May 18 07:44:20 2015 11 // Last Modified By : Andrew Beach12 // Last Modified On : Tue Apr 30 11:47:00 201913 // Update Count : 311 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Sun Feb 16 04:11:40 2020 13 // Update Count : 5 14 14 // 15 15 … … 25 25 std::string genType( Type *type, const std::string &baseString, const Options &options ); 26 26 std::string genType( Type *type, const std::string &baseString, bool pretty = false, bool genC = false, bool lineMarks = false ); 27 27 std::string genPrettyType( Type * type, const std::string & baseString ); 28 28 } // namespace CodeGen 29 29 -
src/CodeGen/Generate.cc
r41efd33 r04e6f93 10 10 // Created On : Mon May 18 07:44:20 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Dec 13 23:38:56 201913 // Update Count : 812 // Last Modified On : Sun Feb 16 03:01:51 2020 13 // Update Count : 9 14 14 // 15 15 #include "Generate.h" … … 64 64 void generate( BaseSyntaxNode * node, std::ostream & os ) { 65 65 if ( Type * type = dynamic_cast< Type * >( node ) ) { 66 os << CodeGen::genPrettyType( type, "" );66 os << genPrettyType( type, "" ); 67 67 } else { 68 68 PassVisitor<CodeGenerator> cgv( os, true, false, false, false ); -
src/CodeGen/OperatorTable.cc
r41efd33 r04e6f93 10 10 // Created On : Mon May 18 07:44:20 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Sat Jul 15 17:12:22 201713 // Update Count : 1512 // Last Modified On : Tue Feb 18 15:55:01 2020 13 // Update Count : 55 14 14 // 15 15 … … 17 17 #include <map> // for map, _Rb_tree_const_iterator, map<>::const_iterator 18 18 #include <utility> // for pair 19 using namespace std; 19 20 20 21 #include "OperatorTable.h" … … 22 23 23 24 namespace CodeGen { 24 namespace{25 const OperatorInfo tableValues[] = {26 { "?[?]", "", "_operator_index", OT_INDEX},27 { "?{}", "=", "_constructor", OT_CTOR},28 { "^?{}", "", "_destructor", OT_DTOR},29 { "?()", "", "_operator_call", OT_CALL},30 { "?++", "++", "_operator_postincr", OT_POSTFIXASSIGN},31 { "?--", "--", "_operator_postdecr", OT_POSTFIXASSIGN},32 { "*?", "*", "_operator_deref", OT_PREFIX},33 { "+?", "+", "_operator_unaryplus", OT_PREFIX},34 { "-?", "-", "_operator_unaryminus", OT_PREFIX},35 { "~?", "~", "_operator_bitnot", OT_PREFIX},36 { "!?", "!", "_operator_lognot", OT_PREFIX},37 { "++?", "++", "_operator_preincr", OT_PREFIXASSIGN},38 { "--?", "--", "_operator_predecr", OT_PREFIXASSIGN},39 { "?\\?", "\\", "_operator_exponential", OT_INFIX},40 { "?*?", "*", "_operator_multiply", OT_INFIX},41 { "?/?", "/", "_operator_divide", OT_INFIX},42 { "?%?", "%", "_operator_modulus", OT_INFIX},43 { "?+?", "+", "_operator_add", OT_INFIX},44 { "?-?", "-", "_operator_subtract", OT_INFIX},45 { "?<<?", "<<", "_operator_shiftleft", OT_INFIX},46 { "?>>?", ">>", "_operator_shiftright", OT_INFIX},47 { "?<?", "<", "_operator_less", OT_INFIX},48 { "?>?", ">", "_operator_greater", OT_INFIX},49 { "?<=?", "<=", "_operator_lessequal", OT_INFIX},50 { "?>=?", ">=", "_operator_greaterequal", OT_INFIX},51 { "?==?", "==", "_operator_equal", OT_INFIX},52 { "?!=?", "!=", "_operator_notequal", OT_INFIX},53 { "?&?", "&", "_operator_bitand", OT_INFIX},54 { "?^?", "^", "_operator_bitxor", OT_INFIX},55 { "?|?", "|", "_operator_bitor", OT_INFIX},56 { "?=?", "=", "_operator_assign", OT_INFIXASSIGN},57 { "?\\=?", "\\=", "_operator_expassign", OT_INFIXASSIGN},58 { "?*=?", "*=", "_operator_multassign", OT_INFIXASSIGN},59 { "?/=?", "/=", "_operator_divassign", OT_INFIXASSIGN},60 { "?%=?", "%=", "_operator_modassign", OT_INFIXASSIGN},61 { "?+=?", "+=", "_operator_addassign", OT_INFIXASSIGN},62 { "?-=?", "-=", "_operator_subassign", OT_INFIXASSIGN},63 { "?<<=?", "<<=", "_operator_shiftleftassign", OT_INFIXASSIGN},64 { "?>>=?", ">>=", "_operator_shiftrightassign", OT_INFIXASSIGN},65 { "?&=?", "&=", "_operator_bitandassign", OT_INFIXASSIGN},66 { "?^=?", "^=", "_operator_bitxorassign", OT_INFIXASSIGN},67 { "?|=?", "|=", "_operator_bitorassign", OT_INFIXASSIGN},68 };25 const OperatorInfo CodeGen::tableValues[] = { 26 // inputName symbol outputName friendlyName type 27 { "?[?]", "", "_operator_index", "Index", OT_INDEX }, 28 { "?{}", "=", "_constructor", "Constructor", OT_CTOR }, 29 { "^?{}", "", "_destructor", "Destructor", OT_DTOR }, 30 { "?()", "", "_operator_call", "Call Operator", OT_CALL }, 31 { "?++", "++", "_operator_postincr", "Postfix Increment", OT_POSTFIXASSIGN }, 32 { "?--", "--", "_operator_postdecr", "Postfix Decrement", OT_POSTFIXASSIGN }, 33 { "*?", "*", "_operator_deref", "Dereference", OT_PREFIX }, 34 { "+?", "+", "_operator_unaryplus", "Plus", OT_PREFIX }, 35 { "-?", "-", "_operator_unaryminus", "Minus", OT_PREFIX }, 36 { "~?", "~", "_operator_bitnot", "Bitwise Not", OT_PREFIX }, 37 { "!?", "!", "_operator_lognot", "Logical Not", OT_PREFIX }, 38 { "++?", "++", "_operator_preincr", "Prefix Increment", OT_PREFIXASSIGN }, 39 { "--?", "--", "_operator_predecr", "Prefix Decrement", OT_PREFIXASSIGN }, 40 { "?\\?", "\\", "_operator_exponential", "Exponentiation", OT_INFIX }, 41 { "?*?", "*", "_operator_multiply", "Multiplication", OT_INFIX }, 42 { "?/?", "/", "_operator_divide", "Division", OT_INFIX }, 43 { "?%?", "%", "_operator_modulus", "Modulo", OT_INFIX }, 44 { "?+?", "+", "_operator_add", "Addition", OT_INFIX }, 45 { "?-?", "-", "_operator_subtract", "Substraction", OT_INFIX }, 46 { "?<<?", "<<", "_operator_shiftleft", "Shift Left", OT_INFIX }, 47 { "?>>?", ">>", "_operator_shiftright", "Shift Right", OT_INFIX }, 48 { "?<?", "<", "_operator_less", "Less-than", OT_INFIX }, 49 { "?>?", ">", "_operator_greater", "Greater-than", OT_INFIX }, 50 { "?<=?", "<=", "_operator_lessequal", "Less-than-or-Equal", OT_INFIX }, 51 { "?>=?", ">=", "_operator_greaterequal", "Greater-than-or-Equal", OT_INFIX }, 52 { "?==?", "==", "_operator_equal", "Equality", OT_INFIX }, 53 { "?!=?", "!=", "_operator_notequal", "Not-Equal", OT_INFIX }, 54 { "?&?", "&", "_operator_bitand", "Bitwise And", OT_INFIX }, 55 { "?^?", "^", "_operator_bitxor", "Bitwise Xor", OT_INFIX }, 56 { "?|?", "|", "_operator_bitor", "Bitwise Or", OT_INFIX }, 57 { "?=?", "=", "_operator_assign", "Assignment", OT_INFIXASSIGN }, 58 { "?\\=?", "\\=", "_operator_expassign", "Exponentiation Assignment", OT_INFIXASSIGN }, 59 { "?*=?", "*=", "_operator_multassign", "Multiplication Assignment", OT_INFIXASSIGN }, 60 { "?/=?", "/=", "_operator_divassign", "Division Assignment", OT_INFIXASSIGN }, 61 { "?%=?", "%=", "_operator_modassign", "Modulo Assignment", OT_INFIXASSIGN }, 62 { "?+=?", "+=", "_operator_addassign", "Addition Assignment", OT_INFIXASSIGN }, 63 { "?-=?", "-=", "_operator_subassign", "Substrction Assignment", OT_INFIXASSIGN }, 64 { "?<<=?", "<<=", "_operator_shiftleftassign", "Shift Left Assignment", OT_INFIXASSIGN }, 65 { "?>>=?", ">>=", "_operator_shiftrightassign", "Shift Right Assignment", OT_INFIXASSIGN }, 66 { "?&=?", "&=", "_operator_bitandassign", "Bitwise And Assignment", OT_INFIXASSIGN }, 67 { "?^=?", "^=", "_operator_bitxorassign", "Bitwise Xor Assignment", OT_INFIXASSIGN }, 68 { "?|=?", "|=", "_operator_bitorassign", "Bitwise Or Assignment", OT_INFIXASSIGN }, 69 }; // tableValues 69 70 70 const int numOps = sizeof( tableValues ) / sizeof( OperatorInfo );71 std::map< std::string, OperatorInfo > CodeGen::table; 71 72 72 std::map< std::string, OperatorInfo > table; 73 74 void initialize() { 75 for ( int i = 0; i < numOps; ++i ) { 76 table[ tableValues[i].inputName ] = tableValues[i]; 77 } // for 78 } 79 } // namespace 80 81 bool operatorLookup( const std::string & funcName, OperatorInfo & info ) { 82 static bool init = false; 83 if ( ! init ) { 84 initialize(); 85 } // if 86 87 std::map< std::string, OperatorInfo >::const_iterator i = table.find( funcName ); 88 if ( i == table.end() ) { 89 if ( isPrefix( funcName, "?`" ) ) { 90 // handle literal suffixes, which are user-defined postfix operators 91 info.inputName = funcName; 92 info.symbol = funcName.substr(2); 93 info.outputName = toString( "__operator_literal_", info.symbol ); 94 info.type = OT_POSTFIX; 95 return true; 96 } 97 return false; 98 } else { 99 info = i->second; 100 return true; 101 } // if 73 CodeGen::CodeGen() { 74 enum { numOps = sizeof( tableValues ) / sizeof( OperatorInfo ) }; 75 for ( int i = 0; i < numOps; i += 1 ) { 76 table[ tableValues[i].inputName ] = tableValues[i]; 77 } // for 102 78 } 103 79 104 bool isOperator( const std::string & funcName ) { 105 OperatorInfo info; 106 return operatorLookup( funcName, info ); 80 const OperatorInfo * operatorLookup( const string & funcName ) { 81 if ( funcName.find_first_of( "?^*+-!", 0, 1 ) == string::npos ) return nullptr; // prefilter 82 const OperatorInfo * ret = &CodeGen::table.find( funcName )->second; // must be in the table 83 assert( ret ); 84 return ret; 107 85 } 108 86 109 /// determines if a given function name is one of the operator types between [begin, end) 110 template<typename Iterator> 111 bool isOperatorType( const std::string & funcName, Iterator begin, Iterator end ) { 112 OperatorInfo info; 113 if ( operatorLookup( funcName, info ) ) { 114 return std::find( begin, end, info.type ) != end; 115 } 87 bool isOperator( const string & funcName ) { 88 return operatorLookup( funcName ) != nullptr; 89 } 90 91 string operatorFriendlyName( const string & funcName ) { 92 const OperatorInfo * info = operatorLookup( funcName ); 93 if ( info ) return info->friendlyName; 94 return ""; 95 } 96 97 bool isConstructor( const string & funcName ) { 98 const OperatorInfo * info = operatorLookup( funcName ); 99 if ( info ) return info->type == OT_CTOR; 116 100 return false; 117 101 } 118 102 119 bool isConstructor( const std::string & funcName ) { 120 static OperatorType types[] = { OT_CTOR }; 121 return isOperatorType( funcName, std::begin(types), std::end(types) ); 103 bool isDestructor( const string & funcName ) { 104 const OperatorInfo * info = operatorLookup( funcName ); 105 if ( info ) return info->type == OT_DTOR; 106 return false; 122 107 } 123 108 124 bool isDestructor( const std::string & funcName ) { 125 static OperatorType types[] = { OT_DTOR }; 126 return isOperatorType( funcName, std::begin(types), std::end(types) ); 109 bool isCtorDtor( const string & funcName ) { 110 const OperatorInfo * info = operatorLookup( funcName ); 111 if ( info ) return info->type <= OT_CONSTRUCTOR; 112 return false; 127 113 } 128 114 129 bool isAssignment( const std::string & funcName ) { 130 static OperatorType types[] = { OT_PREFIXASSIGN, OT_POSTFIXASSIGN, OT_INFIXASSIGN }; 131 return isOperatorType( funcName, std::begin(types), std::end(types) ); 115 bool isAssignment( const string & funcName ) { 116 const OperatorInfo * info = operatorLookup( funcName ); 117 if ( info ) return info->type > OT_CONSTRUCTOR && info->type <= OT_ASSIGNMENT; 118 return false; 132 119 } 133 120 134 bool isCtorDtor( const std::string & funcName ) { 135 static OperatorType types[] = { OT_CTOR, OT_DTOR }; 136 return isOperatorType( funcName, std::begin(types), std::end(types) ); 121 bool isCtorDtorAssign( const string & funcName ) { 122 const OperatorInfo * info = operatorLookup( funcName ); 123 if ( info ) return info->type <= OT_ASSIGNMENT; 124 return false; 137 125 } 138 126 139 bool isCtorDtorAssign( const std::string & funcName ) { 140 static OperatorType types[] = { OT_CTOR, OT_DTOR, OT_PREFIXASSIGN, OT_POSTFIXASSIGN, OT_INFIXASSIGN }; 141 return isOperatorType( funcName, std::begin(types), std::end(types) ); 142 } 127 CodeGen codegen; // initialize singleton package 143 128 } // namespace CodeGen 144 129 145 130 // Local Variables: // 146 131 // tab-width: 4 // 147 // mode: c++ //148 // compile-command: "make install" //149 132 // End: // -
src/CodeGen/OperatorTable.h
r41efd33 r04e6f93 10 10 // Created On : Mon May 18 07:44:20 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Jul 21 22:17:11 201713 // Update Count : 612 // Last Modified On : Sun Feb 16 08:13:34 2020 13 // Update Count : 26 14 14 // 15 15 … … 17 17 18 18 #include <string> 19 #include <map> 19 20 20 21 namespace CodeGen { 21 22 enum OperatorType { 22 OT_INDEX,23 23 OT_CTOR, 24 24 OT_DTOR, 25 OT_CALL, 26 OT_PREFIX, 27 OT_POSTFIX, 28 OT_INFIX, 25 OT_CONSTRUCTOR = OT_DTOR, 29 26 OT_PREFIXASSIGN, 30 27 OT_POSTFIXASSIGN, 31 28 OT_INFIXASSIGN, 29 OT_ASSIGNMENT = OT_INFIXASSIGN, 30 OT_CALL, 31 OT_PREFIX, 32 OT_INFIX, 33 OT_POSTFIX, 34 OT_INDEX, 32 35 OT_LABELADDRESS, 33 36 OT_CONSTANT … … 38 41 std::string symbol; 39 42 std::string outputName; 43 std::string friendlyName; 40 44 OperatorType type; 41 45 }; 42 46 47 class CodeGen { 48 friend const OperatorInfo * operatorLookup( const std::string & funcName ); 49 50 static const OperatorInfo tableValues[]; 51 static std::map< std::string, OperatorInfo > table; 52 public: 53 CodeGen(); 54 }; // CodeGen 55 43 56 bool isOperator( const std::string & funcName ); 44 bool operatorLookup( const std::string & funcName, OperatorInfo & info ); 57 const OperatorInfo * operatorLookup( const std::string & funcName ); 58 std::string operatorFriendlyName( const std::string & funcName ); 45 59 46 60 bool isConstructor( const std::string & ); -
src/CodeGen/Options.h
r41efd33 r04e6f93 9 9 // Author : Andrew Beach 10 10 // Created On : Tue Apr 30 11:36:00 2019 11 // Last Modified By : Andrew Beach12 // Last Modified On : Thr May 2 10:45:00 201913 // Update Count : 211 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Sat Feb 15 18:37:06 2020 13 // Update Count : 3 14 14 // 15 15 16 16 #pragma once 17 17 18 namespace CodeGen { 19 struct Options { 20 // External Options: Same thoughout a pass. 21 bool pretty; 22 bool genC; 23 bool lineMarks; 24 bool printExprTypes; 18 struct Options { 19 // External Options: Same thoughout a pass. 20 bool pretty; 21 bool genC; 22 bool lineMarks; 23 bool printExprTypes; 25 24 26 27 25 // Internal Options: Changed on some recurisive calls. 26 bool anonymousUnused = false; 28 27 29 30 28 Options(bool pretty, bool genC, bool lineMarks, bool printExprTypes) : 29 pretty(pretty), genC(genC), lineMarks(lineMarks), printExprTypes(printExprTypes) 31 30 {} 32 }; 33 } // namespace CodeGen 31 }; 34 32 35 33 // Local Variables: // -
src/CodeTools/ResolvProtoDump.cc
r41efd33 r04e6f93 9 9 // Author : Aaron Moss 10 10 // Created On : Tue Sep 11 09:04:00 2018 11 // Last Modified By : Aaron Moss12 // Last Modified On : Tue Sep 11 09:04:00 201813 // Update Count : 111 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Sat Feb 15 13:50:11 2020 13 // Update Count : 3 14 14 // 15 15 … … 182 182 183 183 // replace operator names 184 CodeGen::OperatorInfo info;185 if ( CodeGen::operatorLookup( name, info )) {184 const CodeGen::OperatorInfo * opInfo = CodeGen::operatorLookup( name ); 185 if ( opInfo ) { 186 186 ss << new_prefix(pre, ""); 187 op_name( info.outputName, ss );187 op_name( opInfo->outputName, ss ); 188 188 return; 189 189 } -
src/Common/SemanticError.h
r41efd33 r04e6f93 49 49 struct WarningData { 50 50 const char * const name; 51 const Severity default_severity; 51 52 const char * const message; 52 const Severity default_severity;53 53 }; 54 54 55 55 constexpr WarningData WarningFormats[] = { 56 {"self-assign" , "self assignment of expression: %s" , Severity::Warn}, 57 {"reference-conversion" , "rvalue to reference conversion of rvalue: %s" , Severity::Warn}, 58 {"qualifiers-zero_t-one_t", "questionable use of type qualifier %s with %s", Severity::Warn}, 59 {"aggregate-forward-decl" , "forward declaration of nested aggregate: %s" , Severity::Warn}, 60 {"superfluous-decl" , "declaration does not allocate storage: %s" , Severity::Warn}, 61 {"gcc-attributes" , "invalid attribute: %s" , Severity::Warn}, 56 {"self-assign" , Severity::Warn , "self assignment of expression: %s" }, 57 {"reference-conversion" , Severity::Warn , "rvalue to reference conversion of rvalue: %s" }, 58 {"qualifiers-zero_t-one_t", Severity::Warn , "questionable use of type qualifier %s with %s" }, 59 {"aggregate-forward-decl" , Severity::Warn , "forward declaration of nested aggregate: %s" }, 60 {"superfluous-decl" , Severity::Warn , "declaration does not allocate storage: %s" }, 61 {"gcc-attributes" , Severity::Warn , "invalid attribute: %s" }, 62 {"c++-like-copy" , Severity::Warn , "Constructor from reference is not a valid copy constructor" }, 62 63 }; 63 64 … … 69 70 SuperfluousDecl, 70 71 GccAttributes, 72 CppCopy, 71 73 NUMBER_OF_WARNINGS, // This MUST be the last warning 72 74 }; -
src/Common/utility.h
r41efd33 r04e6f93 10 10 // Created On : Mon May 18 07:44:20 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Wed Jul 24 14:28:19 201913 // Update Count : 4112 // Last Modified On : Tue Feb 11 13:00:36 2020 13 // Update Count : 50 14 14 // 15 15 … … 29 29 #include <utility> 30 30 #include <vector> 31 #include <cstring> // memcmp 31 32 32 33 #include "Common/Indenter.h" … … 264 265 } 265 266 266 // / determines if `pref` is a prefix of `str`267 static inline bool isPrefix( const std::string & str, const std::string & pref ) {267 // determines if pref is a prefix of str 268 static inline bool isPrefix( const std::string & str, const std::string & pref, unsigned int start = 0 ) { 268 269 if ( pref.size() > str.size() ) return false; 269 auto its = std::mismatch( pref.begin(), pref.end(), str.begin() );270 return its.first == pref.end();270 return 0 == memcmp( str.c_str() + start, pref.c_str(), pref.size() ); 271 // return prefix == full.substr(0, prefix.size()); // for future, requires c++17 271 272 } 272 273 -
src/Concurrency/Keywords.cc
r41efd33 r04e6f93 88 88 // int data; int data; 89 89 // a_struct_t more_data; a_struct_t more_data; 90 // => thread_desc__thrd_d;90 // => $thread __thrd_d; 91 91 // }; }; 92 // static inline thread_desc* get_thread( MyThread * this ) { return &this->__thrd_d; }92 // static inline $thread * get_thread( MyThread * this ) { return &this->__thrd_d; } 93 93 // 94 94 class ThreadKeyword final : public ConcurrentSueKeyword { … … 96 96 97 97 ThreadKeyword() : ConcurrentSueKeyword( 98 " thread_desc",98 "$thread", 99 99 "__thrd", 100 100 "get_thread", … … 120 120 // int data; int data; 121 121 // a_struct_t more_data; a_struct_t more_data; 122 // => coroutine_desc__cor_d;122 // => $coroutine __cor_d; 123 123 // }; }; 124 // static inline coroutine_desc* get_coroutine( MyCoroutine * this ) { return &this->__cor_d; }124 // static inline $coroutine * get_coroutine( MyCoroutine * this ) { return &this->__cor_d; } 125 125 // 126 126 class CoroutineKeyword final : public ConcurrentSueKeyword { … … 128 128 129 129 CoroutineKeyword() : ConcurrentSueKeyword( 130 " coroutine_desc",130 "$coroutine", 131 131 "__cor", 132 132 "get_coroutine", … … 152 152 // int data; int data; 153 153 // a_struct_t more_data; a_struct_t more_data; 154 // => monitor_desc__mon_d;154 // => $monitor __mon_d; 155 155 // }; }; 156 // static inline monitor_desc* get_coroutine( MyMonitor * this ) { return &this->__cor_d; }156 // static inline $monitor * get_coroutine( MyMonitor * this ) { return &this->__cor_d; } 157 157 // 158 158 class MonitorKeyword final : public ConcurrentSueKeyword { … … 160 160 161 161 MonitorKeyword() : ConcurrentSueKeyword( 162 " monitor_desc",162 "$monitor", 163 163 "__mon", 164 164 "get_monitor", … … 182 182 //Handles mutex routines definitions : 183 183 // void foo( A * mutex a, B * mutex b, int i ) { void foo( A * a, B * b, int i ) { 184 // monitor_desc* __monitors[] = { get_monitor(a), get_monitor(b) };184 // $monitor * __monitors[] = { get_monitor(a), get_monitor(b) }; 185 185 // monitor_guard_t __guard = { __monitors, 2 }; 186 186 // /*Some code*/ => /*Some code*/ … … 221 221 //Handles mutex routines definitions : 222 222 // void foo( A * mutex a, B * mutex b, int i ) { void foo( A * a, B * b, int i ) { 223 // monitor_desc* __monitors[] = { get_monitor(a), get_monitor(b) };223 // $monitor * __monitors[] = { get_monitor(a), get_monitor(b) }; 224 224 // monitor_guard_t __guard = { __monitors, 2 }; 225 225 // /*Some code*/ => /*Some code*/ … … 306 306 Expression * ConcurrentSueKeyword::postmutate( KeywordCastExpr * cast ) { 307 307 if ( cast_target == cast->target ) { 308 // convert (thread &)t to ( thread_desc&)*get_thread(t), etc.308 // convert (thread &)t to ($thread &)*get_thread(t), etc. 309 309 if( !type_decl ) SemanticError( cast, context_error ); 310 310 if( !dtor_decl ) SemanticError( cast, context_error ); … … 377 377 get_type, 378 378 nullptr, 379 noAttributes,379 { new Attribute("const") }, 380 380 Type::Inline 381 381 ); … … 516 516 void MutexKeyword::postvisit(StructDecl* decl) { 517 517 518 if( decl->name == " monitor_desc" && decl->body ) {518 if( decl->name == "$monitor" && decl->body ) { 519 519 assert( !monitor_decl ); 520 520 monitor_decl = decl; … … 612 612 ); 613 613 614 // monitor_desc* __monitors[] = { get_monitor(a), get_monitor(b) };614 //$monitor * __monitors[] = { get_monitor(a), get_monitor(b) }; 615 615 body->push_front( new DeclStmt( monitors) ); 616 616 } … … 673 673 ); 674 674 675 // monitor_desc* __monitors[] = { get_monitor(a), get_monitor(b) };675 //$monitor * __monitors[] = { get_monitor(a), get_monitor(b) }; 676 676 body->push_front( new DeclStmt( monitors) ); 677 677 } … … 681 681 //============================================================================================= 682 682 void ThreadStarter::previsit( StructDecl * decl ) { 683 if( decl->name == " thread_desc" && decl->body ) {683 if( decl->name == "$thread" && decl->body ) { 684 684 assert( !thread_decl ); 685 685 thread_decl = decl; -
src/Concurrency/Waitfor.cc
r41efd33 r04e6f93 244 244 decl_mask = decl; 245 245 } 246 else if( decl->name == " monitor_desc" ) {246 else if( decl->name == "$monitor" ) { 247 247 assert( !decl_monitor ); 248 248 decl_monitor = decl; -
src/ControlStruct/Mutate.cc
r41efd33 r04e6f93 10 10 // Created On : Mon May 18 07:44:20 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Thu Aug 4 11:39:08 201613 // Update Count : 912 // Last Modified On : Sun Feb 16 03:22:07 2020 13 // Update Count : 10 14 14 // 15 15 … … 37 37 mutateAll( translationUnit, formut ); 38 38 } 39 } // namespace Co deGen39 } // namespace ControlStruct 40 40 41 41 // Local Variables: // -
src/InitTweak/FixInit.cc
r41efd33 r04e6f93 10 10 // Created On : Wed Jan 13 16:29:30 2016 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Dec 13 23:41:27 201913 // Update Count : 7712 // Last Modified On : Sun Feb 16 04:17:07 2020 13 // Update Count : 82 14 14 // 15 15 #include "FixInit.h" … … 745 745 } 746 746 747 // to prevent warnings ( ‘_unq0’may be used uninitialized in this function),747 // to prevent warnings ('_unq0' may be used uninitialized in this function), 748 748 // insert an appropriate zero initializer for UniqueExpr temporaries. 749 749 Initializer * makeInit( Type * t ) { -
src/InitTweak/FixInit.h
r41efd33 r04e6f93 10 10 // Created On : Wed Jan 13 16:29:30 2016 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : S at Jul 22 09:31:06 201713 // Update Count : 612 // Last Modified On : Sun Feb 16 07:54:50 2020 13 // Update Count : 8 14 14 // 15 15 … … 22 22 23 23 namespace InitTweak { 24 /// replace constructor initializers with expression statements 25 /// and unwrap basic C-style initializers 24 /// replace constructor initializers with expression statements and unwrap basic C-style initializers 26 25 void fix( std::list< Declaration * > & translationUnit, bool inLibrary ); 27 26 } // namespace -
src/MakeLibCfa.cc
r41efd33 r04e6f93 10 10 // Created On : Sat May 16 10:33:33 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Dec 13 23:41:40 201913 // Update Count : 4 212 // Last Modified On : Sun Feb 16 03:49:49 2020 13 // Update Count : 45 14 14 // 15 15 … … 96 96 97 97 FunctionDecl *funcDecl = origFuncDecl->clone(); 98 CodeGen::OperatorInfoopInfo;99 bool lookResult = CodeGen::operatorLookup( funcDecl->get_name(), opInfo);100 assert( lookResult);98 const CodeGen::OperatorInfo * opInfo; 99 opInfo = CodeGen::operatorLookup( funcDecl->get_name() ); 100 assert( opInfo ); 101 101 assert( ! funcDecl->get_statements() ); 102 102 // build a recursive call - this is okay, as the call will actually be codegen'd using operator syntax … … 120 120 121 121 Statement * stmt = nullptr; 122 switch ( opInfo .type ) {122 switch ( opInfo->type ) { 123 123 case CodeGen::OT_INDEX: 124 124 case CodeGen::OT_CALL: -
src/Parser/ParserTypes.h
r41efd33 r04e6f93 10 10 // Created On : Sat Sep 22 08:58:10 2001 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Sat Jul 22 09:33:28 201713 // Update Count : 35 012 // Last Modified On : Sat Feb 15 11:04:40 2020 13 // Update Count : 351 14 14 // 15 15 … … 27 27 // current location in the input 28 28 extern int yylineno; 29 extern char * yyfilename;29 extern char * yyfilename; 30 30 31 31 struct Location { 32 char * file;32 char * file; 33 33 int line; 34 34 }; // Location 35 35 36 36 struct Token { 37 std::string * str; // must be pointer as used in union37 std::string * str; // must be pointer as used in union 38 38 Location loc; 39 39 -
src/Parser/TypedefTable.cc
r41efd33 r04e6f93 10 10 // Created On : Sat May 16 15:20:13 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Wed Jul 25 15:32:35 201813 // Update Count : 25 812 // Last Modified On : Sat Feb 15 08:06:36 2020 13 // Update Count : 259 14 14 // 15 15 … … 47 47 } // TypedefTable::~TypedefTable 48 48 49 bool TypedefTable::exists( const string & identifier ) {49 bool TypedefTable::exists( const string & identifier ) const { 50 50 return kindTable.find( identifier ) != kindTable.end(); 51 51 } // TypedefTable::exists 52 52 53 bool TypedefTable::existsCurr( const string & identifier ) {53 bool TypedefTable::existsCurr( const string & identifier ) const { 54 54 return kindTable.findAt( kindTable.currentScope() - 1, identifier ) != kindTable.end(); 55 55 } // TypedefTable::exists -
src/Parser/TypedefTable.h
r41efd33 r04e6f93 10 10 // Created On : Sat May 16 15:24:36 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Wed Jul 25 15:33:55 201813 // Update Count : 11 412 // Last Modified On : Sat Feb 15 08:06:37 2020 13 // Update Count : 117 14 14 // 15 15 … … 30 30 ~TypedefTable(); 31 31 32 bool exists( const std::string & identifier ) ;33 bool existsCurr( const std::string & identifier ) ;32 bool exists( const std::string & identifier ) const; 33 bool existsCurr( const std::string & identifier ) const; 34 34 int isKind( const std::string & identifier ) const; 35 35 void makeTypedef( const std::string & name, int kind = TYPEDEFname ); -
src/Parser/lex.ll
r41efd33 r04e6f93 10 10 * Created On : Sat Sep 22 08:58:10 2001 11 11 * Last Modified By : Peter A. Buhr 12 * Last Modified On : Fri Feb 7 19:02:43202013 * Update Count : 7 2512 * Last Modified On : Sat Feb 15 11:05:50 2020 13 * Update Count : 737 14 14 */ 15 15 … … 42 42 #include "ParseNode.h" 43 43 #include "TypedefTable.h" 44 45 string * build_postfix_name( string * name ); 44 46 45 47 char *yyfilename; … … 432 434 "?"({op_unary_pre_post}|"()"|"[?]"|"{}") { IDENTIFIER_RETURN(); } 433 435 "^?{}" { IDENTIFIER_RETURN(); } 434 "?`"{identifier} { IDENTIFIER_RETURN(); } // postfix operator 436 "?`"{identifier} { // postfix operator 437 yylval.tok.str = new string( &yytext[2] ); // remove ?` 438 yylval.tok.str = build_postfix_name( yylval.tok.str ); // add prefix 439 RETURN_LOCN( typedefTable.isKind( *yylval.tok.str ) ); 440 } 435 441 "?"{op_binary_over}"?" { IDENTIFIER_RETURN(); } // binary 436 442 /* -
src/Parser/parser.yy
r41efd33 r04e6f93 10 10 // Created On : Sat Sep 1 20:22:55 2001 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Sat Feb 1 10:04:40202013 // Update Count : 44 4012 // Last Modified On : Wed Feb 26 14:27:39 2020 13 // Update Count : 4472 14 14 // 15 15 … … 166 166 } // rebindForall 167 167 168 NameExpr * build_postfix_name( const string * name ) { 169 NameExpr * new_name = build_varref( new string( "?`" + *name ) ); 170 delete name; 171 return new_name; 168 string * build_postfix_name( string * name ) { 169 *name = string("__postfix_func_") + *name; 170 return name; 172 171 } // build_postfix_name 173 172 … … 633 632 { $$ = new ExpressionNode( build_func( $1, $3 ) ); } 634 633 | postfix_expression '`' identifier // CFA, postfix call 635 { $$ = new ExpressionNode( build_func( new ExpressionNode( build_ postfix_name( $3) ), $1 ) ); }634 { $$ = new ExpressionNode( build_func( new ExpressionNode( build_varref( build_postfix_name( $3 ) ) ), $1 ) ); } 636 635 | constant '`' identifier // CFA, postfix call 637 { $$ = new ExpressionNode( build_func( new ExpressionNode( build_ postfix_name( $3) ), $1 ) ); }636 { $$ = new ExpressionNode( build_func( new ExpressionNode( build_varref( build_postfix_name( $3 ) ) ), $1 ) ); } 638 637 | string_literal '`' identifier // CFA, postfix call 639 { $$ = new ExpressionNode( build_func( new ExpressionNode( build_ postfix_name( $3) ), new ExpressionNode( $1 ) ) ); }638 { $$ = new ExpressionNode( build_func( new ExpressionNode( build_varref( build_postfix_name( $3 ) ) ), new ExpressionNode( $1 ) ) ); } 640 639 | postfix_expression '.' identifier 641 640 { $$ = new ExpressionNode( build_fieldSel( $1, build_varref( $3 ) ) ); } … … 1590 1589 // type_specifier can resolve to just TYPEDEFname (e.g., typedef int T; int f( T );). Therefore this must be 1591 1590 // flattened to allow lookahead to the '(' without having to reduce identifier_or_type_name. 1592 cfa_abstract_tuple identifier_or_type_name '(' push cfa_parameter_ellipsis_list_opt pop ')' 1591 cfa_abstract_tuple identifier_or_type_name '(' push cfa_parameter_ellipsis_list_opt pop ')' attribute_list_opt 1593 1592 // To obtain LR(1 ), this rule must be factored out from function return type (see cfa_abstract_declarator). 1594 { $$ = DeclarationNode::newFunction( $2, $1, $5, 0 ) ; }1595 | cfa_function_return identifier_or_type_name '(' push cfa_parameter_ellipsis_list_opt pop ')' 1596 { $$ = DeclarationNode::newFunction( $2, $1, $5, 0 ) ; }1593 { $$ = DeclarationNode::newFunction( $2, $1, $5, 0 )->addQualifiers( $8 ); } 1594 | cfa_function_return identifier_or_type_name '(' push cfa_parameter_ellipsis_list_opt pop ')' attribute_list_opt 1595 { $$ = DeclarationNode::newFunction( $2, $1, $5, 0 )->addQualifiers( $8 ); } 1597 1596 ; 1598 1597 … … 2078 2077 aggregate_control: // CFA 2079 2078 GENERATOR 2080 { yyy = true; $$ = AggregateDecl::Coroutine; } 2079 { SemanticError( yylloc, "generator is currently unimplemented." ); $$ = AggregateDecl::NoAggregate; } 2080 | MONITOR GENERATOR 2081 { SemanticError( yylloc, "monitor generator is currently unimplemented." ); $$ = AggregateDecl::NoAggregate; } 2081 2082 | COROUTINE 2082 2083 { yyy = true; $$ = AggregateDecl::Coroutine; } 2083 2084 | MONITOR 2084 2085 { yyy = true; $$ = AggregateDecl::Monitor; } 2086 | MONITOR COROUTINE 2087 { SemanticError( yylloc, "monitor coroutine is currently unimplemented." ); $$ = AggregateDecl::NoAggregate; } 2085 2088 | THREAD 2086 2089 { yyy = true; $$ = AggregateDecl::Thread; } 2090 | MONITOR THREAD 2091 { SemanticError( yylloc, "monitor thread is currently unimplemented." ); $$ = AggregateDecl::NoAggregate; } 2087 2092 ; 2088 2093 -
src/ResolvExpr/AlternativeFinder.cc
r41efd33 r04e6f93 1292 1292 1293 1293 try { 1294 // Attempt 1 : turn (thread&)X into ( thread_desc&)X.__thrd1294 // Attempt 1 : turn (thread&)X into ($thread&)X.__thrd 1295 1295 // Clone is purely for memory management 1296 1296 std::unique_ptr<Expression> tech1 { new UntypedMemberExpr(new NameExpr(castExpr->concrete_target.field), castExpr->arg->clone()) }; … … 1303 1303 } catch(SemanticErrorException & ) {} 1304 1304 1305 // Fallback : turn (thread&)X into ( thread_desc&)get_thread(X)1305 // Fallback : turn (thread&)X into ($thread&)get_thread(X) 1306 1306 std::unique_ptr<Expression> fallback { UntypedExpr::createDeref( new UntypedExpr(new NameExpr(castExpr->concrete_target.getter), { castExpr->arg->clone() })) }; 1307 1307 // don't prune here, since it's guaranteed all alternatives will have the same type -
src/ResolvExpr/Resolver.cc
r41efd33 r04e6f93 84 84 void previsit( ThrowStmt * throwStmt ); 85 85 void previsit( CatchStmt * catchStmt ); 86 void postvisit( CatchStmt * catchStmt ); 86 87 void previsit( WaitForStmt * stmt ); 87 88 … … 567 568 568 569 void Resolver_old::previsit( CatchStmt * catchStmt ) { 570 // Until we are very sure this invarent (ifs that move between passes have thenPart) 571 // holds, check it. This allows a check for when to decode the mangling. 572 if ( IfStmt * ifStmt = dynamic_cast<IfStmt *>( catchStmt->body ) ) { 573 assert( ifStmt->thenPart ); 574 } 575 // Encode the catchStmt so the condition can see the declaration. 569 576 if ( catchStmt->cond ) { 570 findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer ); 577 IfStmt * ifStmt = new IfStmt( catchStmt->cond, nullptr, catchStmt->body ); 578 catchStmt->cond = nullptr; 579 catchStmt->body = ifStmt; 580 } 581 } 582 583 void Resolver_old::postvisit( CatchStmt * catchStmt ) { 584 // Decode the catchStmt so everything is stored properly. 585 IfStmt * ifStmt = dynamic_cast<IfStmt *>( catchStmt->body ); 586 if ( nullptr != ifStmt && nullptr == ifStmt->thenPart ) { 587 assert( ifStmt->condition ); 588 assert( ifStmt->elsePart ); 589 catchStmt->cond = ifStmt->condition; 590 catchStmt->body = ifStmt->elsePart; 591 ifStmt->condition = nullptr; 592 ifStmt->elsePart = nullptr; 593 delete ifStmt; 571 594 } 572 595 } … … 1466 1489 1467 1490 const ast::CatchStmt * Resolver_new::previsit( const ast::CatchStmt * catchStmt ) { 1491 // TODO: This will need a fix for the decl/cond scoping problem. 1468 1492 if ( catchStmt->cond ) { 1469 1493 ast::ptr< ast::Type > boolType = new ast::BasicType{ ast::BasicType::Bool }; -
src/SymTab/Demangle.cc
r41efd33 r04e6f93 10 10 // Created On : Thu Jul 19 12:52:41 2018 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Dec 13 14:54:15 201913 // Update Count : 412 // Last Modified On : Tue Feb 11 15:09:18 2020 13 // Update Count : 10 14 14 // 15 15 … … 19 19 #include "CodeGen/GenType.h" 20 20 #include "Common/PassVisitor.h" 21 #include "Common/utility.h" // isPrefix 21 22 #include "Mangler.h" 22 23 #include "SynTree/Type.h" … … 416 417 417 418 bool StringView::isPrefix(const std::string & pref) { 418 if ( pref.size() > str.size()-idx ) return false; 419 auto its = std::mismatch( pref.begin(), pref.end(), std::next(str.begin(), idx) ); 420 if (its.first == pref.end()) { 419 // if ( pref.size() > str.size()-idx ) return false; 420 // auto its = std::mismatch( pref.begin(), pref.end(), std::next(str.begin(), idx) ); 421 // if (its.first == pref.end()) { 422 // idx += pref.size(); 423 // return true; 424 // } 425 426 // This update is untested because there are no tests for this code. 427 if ( ::isPrefix( str, pref, idx ) ) { 421 428 idx += pref.size(); 422 429 return true; … … 429 436 PRINT( std::cerr << "====== " << str.size() << " " << str << std::endl; ) 430 437 if (str.size() < 2+Encoding::manglePrefix.size()) return false; // +2 for at least _1 suffix 431 if ( ! isPrefix(Encoding::manglePrefix) || ! isdigit(str.back())) return false;438 if ( ! isPrefix(Encoding::manglePrefix) || ! isdigit(str.back() ) ) return false; 432 439 433 440 // get name -
src/SymTab/Mangler.cc
r41efd33 r04e6f93 10 10 // Created On : Sun May 17 21:40:29 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Dec 13 23:43:49 201913 // Update Count : 2812 // Last Modified On : Sat Feb 15 13:55:12 2020 13 // Update Count : 33 14 14 // 15 15 #include "Mangler.h" … … 128 128 } // if 129 129 mangleName << Encoding::manglePrefix; 130 CodeGen::OperatorInfo opInfo;131 if ( op eratorLookup( declaration->get_name(), opInfo )) {132 mangleName << opInfo .outputName.size() << opInfo.outputName;130 const CodeGen::OperatorInfo * opInfo = CodeGen::operatorLookup( declaration->get_name() ); 131 if ( opInfo ) { 132 mangleName << opInfo->outputName.size() << opInfo->outputName; 133 133 } else { 134 134 mangleName << declaration->name.size() << declaration->name; … … 471 471 } // if 472 472 mangleName << Encoding::manglePrefix; 473 CodeGen::OperatorInfo opInfo;474 if ( op eratorLookup( decl->name, opInfo )) {475 mangleName << opInfo .outputName.size() << opInfo.outputName;473 const CodeGen::OperatorInfo * opInfo = CodeGen::operatorLookup( decl->name ); 474 if ( opInfo ) { 475 mangleName << opInfo->outputName.size() << opInfo->outputName; 476 476 } else { 477 477 mangleName << decl->name.size() << decl->name; -
src/SymTab/Validate.cc
r41efd33 r04e6f93 311 311 Stats::Heap::newPass("validate-A"); 312 312 Stats::Time::BlockGuard guard("validate-A"); 313 VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors 313 314 acceptAll( translationUnit, hoistDecls ); 314 315 ReplaceTypedef::replaceTypedef( translationUnit ); … … 336 337 Stats::Time::BlockGuard guard("validate-C"); 337 338 acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes_old 338 VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors339 339 ReturnChecker::checkFunctionReturns( translationUnit ); 340 340 InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen … … 1182 1182 if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc. 1183 1183 if ( params.size() == 0 ) { 1184 SemanticError( funcDecl , "Constructors, destructors, and assignment functions require at least one parameter" );1184 SemanticError( funcDecl->location, "Constructors, destructors, and assignment functions require at least one parameter." ); 1185 1185 } 1186 1186 ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() ); 1187 1187 if ( ! refType ) { 1188 SemanticError( funcDecl , "First parameter of a constructor, destructor, or assignment function must be a reference" );1188 SemanticError( funcDecl->location, "First parameter of a constructor, destructor, or assignment function must be a reference." ); 1189 1189 } 1190 1190 if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) { 1191 SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " ); 1191 if(!returnVals.front()->get_type()->isVoid()) { 1192 SemanticError( funcDecl->location, "Constructors and destructors cannot have explicit return values." ); 1193 } 1192 1194 } 1193 1195 } -
src/SynTree/Attribute.h
r41efd33 r04e6f93 10 10 // Created On : Mon May 18 07:44:20 2015 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Sat Jul 22 09:54:14 201713 // Update Count : 3912 // Last Modified On : Thu Feb 13 21:34:08 2020 13 // Update Count : 40 14 14 // 15 15 … … 38 38 virtual ~Attribute(); 39 39 40 std::stringget_name() const { return name; }40 const std::string & get_name() const { return name; } 41 41 void set_name( const std::string & newValue ) { name = newValue; } 42 42 std::list< Expression * > & get_parameters() { return parameters; } -
src/cfa.make
r41efd33 r04e6f93 32 32 am__v_GOC_1 = 33 33 34 AM_V_PY = $(am__v_PY_@AM_V@) 35 am__v_PY_ = $(am__v_PY_@AM_DEFAULT_V@) 36 am__v_PY_0 = @echo " PYTHON " $@; 37 am__v_PY_1 = 38 34 39 AM_V_RUST = $(am__v_RUST_@AM_V@) 35 40 am__v_RUST_ = $(am__v_RUST_@AM_DEFAULT_V@) 36 am__v_RUST_0 = @echo " RUST 41 am__v_RUST_0 = @echo " RUST " $@; 37 42 am__v_RUST_1 = 38 43 39 44 AM_V_NODEJS = $(am__v_NODEJS_@AM_V@) 40 45 am__v_NODEJS_ = $(am__v_NODEJS_@AM_DEFAULT_V@) 41 am__v_NODEJS_0 = @echo " NODEJS 46 am__v_NODEJS_0 = @echo " NODEJS " $@; 42 47 am__v_NODEJS_1 = 43 48 -
tests/.expect/alloc-ERROR.txt
r41efd33 r04e6f93 1 alloc.cfa:31 1:1 error: No reasonable alternatives for expression Applying untyped:1 alloc.cfa:310:1 error: No reasonable alternatives for expression Applying untyped: 2 2 Name: ?=? 3 3 ...to: … … 19 19 20 20 21 alloc.cfa:31 2:1 error: No reasonable alternatives for expression Applying untyped:21 alloc.cfa:311:1 error: No reasonable alternatives for expression Applying untyped: 22 22 Name: ?=? 23 23 ...to: … … 39 39 40 40 41 alloc.cfa:31 3:1 error: No reasonable alternatives for expression Applying untyped:41 alloc.cfa:312:1 error: No reasonable alternatives for expression Applying untyped: 42 42 Name: ?=? 43 43 ...to: … … 50 50 51 51 52 alloc.cfa:31 4:1 error: No reasonable alternatives for expression Applying untyped:52 alloc.cfa:313:1 error: No reasonable alternatives for expression Applying untyped: 53 53 Name: ?=? 54 54 ...to: -
tests/.expect/alloc.txt
r41efd33 r04e6f93 2 2 CFA malloc 0xdeadbeef 3 3 CFA alloc 0xdeadbeef 4 CFA array alloc, fill 0xde5 4 CFA alloc, fill dededede 6 5 CFA alloc, fill 3 -
tests/.expect/nested-types-ERR1.txt
r41efd33 r04e6f93 1 nested-types.cfa: 70:1 error: Use of undefined type T1 nested-types.cfa:83:1 error: Use of undefined type T -
tests/.expect/nested-types-ERR2.txt
r41efd33 r04e6f93 1 nested-types.cfa: 73:1 error: Use of undefined global type Z2 nested-types.cfa: 74:1 error: Qualified type requires an aggregate on the left, but has: signed int3 nested-types.cfa: 75:1 error: Undefined type in qualified type: Qualified Type:1 nested-types.cfa:86:1 error: Use of undefined global type Z 2 nested-types.cfa:87:1 error: Qualified type requires an aggregate on the left, but has: signed int 3 nested-types.cfa:88:1 error: Undefined type in qualified type: Qualified Type: 4 4 instance of struct S with body 1 5 5 instance of type Z (not function type) -
tests/Makefile.in
r41efd33 r04e6f93 374 374 am__v_GOC_0 = @echo " GOC " $@; 375 375 am__v_GOC_1 = 376 AM_V_PY = $(am__v_PY_@AM_V@) 377 am__v_PY_ = $(am__v_PY_@AM_DEFAULT_V@) 378 am__v_PY_0 = @echo " PYTHON " $@; 379 am__v_PY_1 = 376 380 AM_V_RUST = $(am__v_RUST_@AM_V@) 377 381 am__v_RUST_ = $(am__v_RUST_@AM_DEFAULT_V@) 378 am__v_RUST_0 = @echo " RUST 382 am__v_RUST_0 = @echo " RUST " $@; 379 383 am__v_RUST_1 = 380 384 AM_V_NODEJS = $(am__v_NODEJS_@AM_V@) 381 385 am__v_NODEJS_ = $(am__v_NODEJS_@AM_DEFAULT_V@) 382 am__v_NODEJS_0 = @echo " NODEJS 386 am__v_NODEJS_0 = @echo " NODEJS " $@; 383 387 am__v_NODEJS_1 = 384 388 AM_V_JAVAC = $(am__v_JAVAC_@AM_V@) -
tests/alloc.cfa
r41efd33 r04e6f93 10 10 // Created On : Wed Feb 3 07:56:22 2016 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Fri Nov 22 15:34:19 201913 // Update Count : 40 412 // Last Modified On : Sun Feb 16 09:21:13 2020 13 // Update Count : 405 14 14 // 15 15 … … 48 48 49 49 p = alloc_set( fill ); // CFA alloc, fill 50 printf( "CFA array alloc, fill %#hhx\n", fill );51 50 printf( "CFA alloc, fill %08x\n", *p ); 52 51 free( p ); -
tests/concurrent/examples/.expect/datingService.txt
r41efd33 r04e6f93 1 Girl:17 is dating Boy at 2 with ccode 172 Boy:2 is dating Girl 17 with ccode 173 Boy:14 is dating Girl 5 with ccode 54 Girl:5 is dating Boy at 14 with ccode 55 Boy:9 is dating Girl 10 with ccode 106 Girl:10 is dating Boy at 9 with ccode 107 Boy:1 is dating Girl 18 with ccode 188 Girl:18 is dating Boy at 1 with ccode 189 Boy:16 is dating Girl 3 with ccode 310 Girl:3 is dating Boy at 16 with ccode 311 Boy:5 is dating Girl 14 with ccode 1412 Girl:14 is dating Boy at 5 with ccode 1413 Boy:15 is dating Girl 4 with ccode 414 Girl:4 is dating Boy at 15 with ccode 415 Girl:0 is dating Boy at 19 with ccode 016 Boy:19 is dating Girl 0 with ccode 017 Girl:9 is dating Boy at 10 with ccode 918 Boy:10 is dating Girl 9 with ccode 919 Girl:11 is dating Boy at 8 with ccode 1120 Boy:8 is dating Girl 11 with ccode 1121 Boy:12 is dating Girl 7 with ccode 722 Girl:7 is dating Boy at 12 with ccode 723 Boy:11 is dating Girl 8 with ccode 824 Girl:8 is dating Boy at 11 with ccode 825 Girl:16 is dating Boy at 3 with ccode 1626 Boy:3 is dating Girl 16 with ccode 1627 Girl:15 is dating Boy at 4 with ccode 1528 Boy:4 is dating Girl 15 with ccode 1529 Girl:19 is dating Boy at 0 with ccode 1930 Boy:0 is dating Girl 19 with ccode 1931 Girl:2 is dating Boy at 17 with ccode 232 Boy:17 is dating Girl 2 with ccode 233 Boy:13 is dating Girl 6 with ccode 634 Girl:6 is dating Boy at 13 with ccode 635 Boy:7 is dating Girl 12 with ccode 1236 Girl:12 is dating Boy at 7 with ccode 1237 Girl:13 is dating Boy at 6 with ccode 1338 Boy:6 is dating Girl 13 with ccode 1339 Girl:1 is dating Boy at 18 with ccode 140 Boy:18 is dating Girl 1 with ccode 1 -
tests/concurrent/examples/datingService.cfa
r41efd33 r04e6f93 1 1 // 2 2 // Cforall Version 1.0.0 Copyright (C) 2017 University of Waterloo 3 // 3 // 4 4 // The contents of this file are covered under the licence agreement in the 5 5 // file "LICENCE" distributed with Cforall. … … 35 35 signal_block( Boys[ccode] ); // restart boy to set phone number 36 36 } // if 37 sout | "Girl:" | PhoneNo | "is dating Boy at" | BoyPhoneNo | "with ccode" | ccode;37 //sout | "Girl:" | PhoneNo | "is dating Boy at" | BoyPhoneNo | "with ccode" | ccode; 38 38 return BoyPhoneNo; 39 39 } // DatingService girl … … 47 47 signal_block( Girls[ccode] ); // restart girl to set phone number 48 48 } // if 49 sout | " Boy:" | PhoneNo | "is dating Girl" | GirlPhoneNo | "with ccode" | ccode;49 //sout | " Boy:" | PhoneNo | "is dating Girl" | GirlPhoneNo | "with ccode" | ccode; 50 50 return GirlPhoneNo; 51 51 } // DatingService boy -
tests/concurrent/examples/quickSort.cfa
r41efd33 r04e6f93 11 11 // Created On : Wed Dec 6 12:15:52 2017 12 12 // Last Modified By : Peter A. Buhr 13 // Last Modified On : Thu Oct 10 13:58:18 201914 // Update Count : 17 613 // Last Modified On : Wed Feb 12 18:24:47 2020 14 // Update Count : 177 15 15 // 16 16 … … 27 27 28 28 void ?{}( Quicksort & qs, int values[], int size, int depth ) { 29 qs. values = values; qs.low = 0; qs.high = size; qs.depth = depth;29 qs.[values, low, high, depth] = [values, 0, size, depth]; 30 30 } // Quicksort 31 31 … … 167 167 values[counter] = size - counter; // descending values 168 168 } // for 169 for ( i nt i = 0; i < 200; i +=1 ) {// random shuffle a few values169 for ( i; 200 ) { // random shuffle a few values 170 170 swap( values[rand() % size], values[rand() % size] ); 171 171 } // for -
tests/concurrent/multi-monitor.cfa
r41efd33 r04e6f93 11 11 12 12 void increment( monitor_t & mutex p1, monitor_t & mutex p2, int & value ) { 13 assert(active_thread() == get_monitor(p1)->owner); 14 assert(active_thread() == get_monitor(p2)->owner); 13 15 value += 1; 16 assert(active_thread() == get_monitor(p1)->owner); 17 assert(active_thread() == get_monitor(p2)->owner); 14 18 } 15 19 -
tests/concurrent/signal/block.cfa
r41efd33 r04e6f93 33 33 34 34 monitor global_data_t { 35 thread_desc* last_thread;36 thread_desc* last_signaller;35 $thread * last_thread; 36 $thread * last_signaller; 37 37 }; 38 38 … … 82 82 if( !is_empty( cond ) ) { 83 83 84 thread_desc* next = front( cond );84 $thread * next = front( cond ); 85 85 86 86 if( ! signal_block( cond ) ) { -
tests/errors/.expect/completeType.txt
r41efd33 r04e6f93 1 completeTypeError.cfa:34:1 error: Cannot choose between 2 alternatives for expression1 errors/completeType.cfa:34:1 error: Cannot choose between 2 alternatives for expression 2 2 Generated Cast of: 3 3 Applying untyped: … … 54 54 55 55 56 completeTypeError.cfa:35:1 error: No reasonable alternatives for expression Applying untyped:56 errors/completeType.cfa:35:1 error: No reasonable alternatives for expression Applying untyped: 57 57 Name: foo 58 58 ...to: 59 59 Name: v 60 60 61 completeTypeError.cfa:36:1 error: No reasonable alternatives for expression Applying untyped:61 errors/completeType.cfa:36:1 error: No reasonable alternatives for expression Applying untyped: 62 62 Name: baz 63 63 ...to: 64 64 Name: v 65 65 66 completeTypeError.cfa:37:1 error: No reasonable alternatives for expression Applying untyped:66 errors/completeType.cfa:37:1 error: No reasonable alternatives for expression Applying untyped: 67 67 Name: quux 68 68 ...to: 69 69 Name: v 70 70 71 completeTypeError.cfa:59:1 error: No reasonable alternatives for expression Applying untyped:71 errors/completeType.cfa:59:1 error: No reasonable alternatives for expression Applying untyped: 72 72 Name: baz 73 73 ...to: 74 74 Name: y 75 75 76 completeTypeError.cfa:60:1 error: No reasonable alternatives for expression Applying untyped:76 errors/completeType.cfa:60:1 error: No reasonable alternatives for expression Applying untyped: 77 77 Name: quux 78 78 ...to: 79 79 Name: y 80 80 81 completeTypeError.cfa:72:1 error: No alternatives with satisfiable assertions for Applying untyped:81 errors/completeType.cfa:72:1 error: No alternatives with satisfiable assertions for Applying untyped: 82 82 Name: baz 83 83 ...to: -
tests/exceptions/except-0.cfa
r41efd33 r04e6f93 19 19 }; 20 20 21 void ?{}(signal_exit *this, const char * area) {22 this ->area = area;23 } 24 25 void ^?{}(signal_exit *this) {26 printf("Exiting: %s\n", this ->area);21 void ?{}(signal_exit & this, const char * area) { 22 this.area = area; 23 } 24 25 void ^?{}(signal_exit & this) { 26 printf("Exiting: %s\n", this.area); 27 27 // sout | "Exiting:" | this->area; 28 28 } … … 242 242 243 243 // Uncaught termination test. 244 /* Removed due to non-deterministic output. 244 245 printf("Throw uncaught.\n"); 245 246 yang z; 246 247 terminate(&z); 247 } 248 */ 249 } -
tests/exceptions/except-2.cfa
r41efd33 r04e6f93 12 12 struct TABLE(BASE_EXCEPT) const * parent; 13 13 size_t size; 14 void (*copy)(num_error *this, num_error *other);15 void (*free)(num_error *this);14 void (*copy)(num_error &this, num_error & other); 15 void (*free)(num_error &this); 16 16 const char * (*msg)(num_error *this); 17 17 int (*code)(num_error *this); … … 28 28 if ( ! this->msg ) { 29 29 static const char * base = "Num Error with code: X"; 30 this->msg = malloc(22);30 this->msg = (char *)malloc(22); 31 31 for (int i = 0 ; (this->msg[i] = base[i]) ; ++i); 32 32 } … … 34 34 return this->msg; 35 35 } 36 void ?{}(num_error *this, int num) {37 this ->virtual_table = &INSTANCE(num_error);38 this ->msg = 0;39 this ->num = num;36 void ?{}(num_error & this, int num) { 37 this.virtual_table = &INSTANCE(num_error); 38 this.msg = 0; 39 this.num = num; 40 40 } 41 void ?{}(num_error * this, num_error *other) {42 this ->virtual_table = other->virtual_table;43 this ->msg = 0;44 this ->num = other->num;41 void ?{}(num_error & this, num_error & other) { 42 this.virtual_table = other.virtual_table; 43 this.msg = 0; 44 this.num = other.num; 45 45 } 46 void ^?{}(num_error *this) {47 if( this ->msg ) free( this->msg );46 void ^?{}(num_error & this) { 47 if( this.msg ) free( this.msg ); 48 48 } 49 49 int num_error_code( num_error * this ) { -
tests/nested-types.cfa
r41efd33 r04e6f93 10 10 // Created On : Mon Jul 9 10:20:03 2018 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Tue Nov 6 17:59:40 201813 // Update Count : 212 // Last Modified On : Wed Feb 12 18:21:15 2020 13 // Update Count : 3 14 14 // 15 15 … … 50 50 // double d; 51 51 // }; 52 53 // struct S { 54 // enum C { R, G, B }; 55 // int i; 56 // struct T { 57 // int i; 58 // }; 59 // T t; 60 // }; 61 62 // S s; 63 // S.C c; 64 // S.T t; 52 65 53 66 int main() { -
tests/test.py
r41efd33 r04e6f93 152 152 # run everything in a temp directory to make sure core file are handled properly 153 153 with tempdir(): 154 # if the make command succe ds continue otherwise skip to diff154 # if the make command succeeds continue otherwise skip to diff 155 155 if success(make_ret): 156 156 with Timed() as run_dur: -
tests/userLiterals.cfa
r41efd33 r04e6f93 5 5 // file "LICENCE" distributed with Cforall. 6 6 // 7 // user _literals.cfa --7 // userLiterals.cfa -- 8 8 // 9 9 // Author : Peter A. Buhr 10 10 // Created On : Wed Sep 6 21:40:50 2017 11 11 // Last Modified By : Peter A. Buhr 12 // Last Modified On : Tue Dec 4 22:03:10 201813 // Update Count : 5612 // Last Modified On : Wed Feb 19 07:48:45 2020 13 // Update Count : 74 14 14 // 15 15 … … 24 24 int ?`__thingy_( int x ) { sout | "_thingy_" | x; return x; } 25 25 26 int ?`s( const char * s ) { sout | "s ecs" | s; return 0; }27 int ?`m( const char16_t * m ) { sout | "m ins" | m; return 0;}28 int ?`h( const char32_t * h ) { sout | "h ours" | h; return 0; }26 int ?`s( const char * s ) { sout | "s" | s; return 0; } 27 int ?`m( const char16_t * m ) { sout | "m" | m; return 0;} 28 int ?`h( const char32_t * h ) { sout | "h" | h; return 0; } 29 29 int ?`_A_( const wchar_t * str ) { sout | "_A_" | str; return 0; } 30 30 int ?`__thingy_( const char * str ) { sout | "_thingy_" | str; return 0; } … … 37 37 return (Weight){ l.stones + r.stones }; 38 38 } 39 ofstream & ?|?( ofstream & os, Weight w ) { return os | w.stones; } 39 ofstream & ?|?( ofstream & os, Weight w ) { return os | wd(1,1, w.stones); } 40 void ?|?( ofstream & os, Weight w ) { (ofstream)(os | w); ends( os ); } 40 41 41 42 Weight ?`st( double w ) { return (Weight){ w }; } // backquote for user literals … … 60 61 sout | w; 61 62 62 // 0`secs;63 0`s; 63 64 1`s; 64 65 23`s; … … 82 83 83 84 "abc"`s; 84 // u"abc"`m; 85 // U_"abc"`h; 86 // L"abc"`_A_; 85 // FIX ME: requires char16_t, char32_t, and wchar_t be unique types 86 // u"abc"`m; 87 // U_"abc"`h; 88 // L"abc"`_A_; 87 89 u8_"abc"`__thingy_; 88 90 } // main … … 90 92 // Local Variables: // 91 93 // tab-width: 4 // 92 // compile-command: "cfa user _literals.cfa" //94 // compile-command: "cfa userLiterals.cfa" // 93 95 // End: //
Note:
See TracChangeset
for help on using the changeset viewer.