% ====================================================================== % ====================================================================== \chapter{Basics} % ====================================================================== % ====================================================================== Before any detailed discussion of the concurrency and parallelism in \CFA, it is important to describe the basics of concurrency and how they are expressed in \CFA user code. \section{Basics of concurrency} At its core, concurrency is based on having call-stacks and potentially multiple threads of execution for these stacks. Concurrency without parallelism only requires having multiple call stacks (or contexts) for a single thread of execution, and switching between these call stacks on a regular basis. A minimal concurrency product can be achieved by creating coroutines, which instead of context switching between each other, always ask an oracle where to context switch next. While coroutines do not technically require a stack, stackfull coroutines are the closest abstraction to a practical "naked"" call stack. When writing concurrency in terms of coroutines, the oracle effectively becomes a scheduler and the whole system now follows a cooperative threading-model \cit. The oracle/scheduler can either be a stackless or stackfull entity and correspondingly require one or two context switches to run a different coroutine. In any case, a subset of concurrency related challenges start to appear. For the complete set of concurrency challenges to occur, the only feature missing is preemption. Indeed, concurrency challenges appear with non-determinism. Guaranteeing mutual-exclusion or synchronisation are simply ways of limiting the lack of determinism in a system. A scheduler introduces order of execution uncertainty, while preemption introduces incertainty about where context-switches occur. Now it is important to understand that uncertainty is not necessarily undesireable; uncertainty can often be used by systems to significantly increase performance and is often the basis of giving a user the illusion that tasks are running in parallel. Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows\cit. \section{\protect\CFA 's Thread Building Blocks} One of the important features that is missing in C is threading. On modern architectures, a lack of threading is becoming less and less forgivable\cite{Sutter05, Sutter05b}, and therefore modern programming languages must have the proper tools to allow users to write performant concurrent and/or parallel programs. As an extension of C, \CFA needs to express these concepts in a way that is as natural as possible to programmers used to imperative languages. And being a system-level language means programmers expect to choose precisely which features they need and which cost they are willing to pay. \section{Coroutines: A stepping stone}\label{coroutine} While the main focus of this proposal is concurrency and parallelism, as mentionned above it is important to adress coroutines, which are actually a significant underlying aspect of a concurrency system. Indeed, while having nothing todo with parallelism and arguably little to do with concurrency, coroutines need to deal with context-switchs and and other context-management operations. Therefore, this proposal includes coroutines both as an intermediate step for the implementation of threads, and a first class feature of \CFA. Furthermore, many design challenges of threads are at least partially present in designing coroutines, which makes the design effort that much more relevant. The core API of coroutines revolve around two features: independent call stacks and \code{suspend}/\code{resume}. Here is an example of a solution to the fibonnaci problem using \CFA coroutines: \begin{cfacode} coroutine Fibonacci { int fn; // used for communication }; void ?{}(Fibonacci* this) { // constructor this->fn = 0; } // main automacically called on first resume void main(Fibonacci* this) { int fn1, fn2; // retained between resumes this->fn = 0; fn1 = this->fn; suspend(this); // return to last resume this->fn = 1; fn2 = fn1; fn1 = this->fn; suspend(this); // return to last resume for ( ;; ) { this->fn = fn1 + fn2; fn2 = fn1; fn1 = this->fn; suspend(this); // return to last resume } } int next(Fibonacci* this) { resume(this); // transfer to last suspend return this.fn; } void main() { // regular program main Fibonacci f1, f2; for ( int i = 1; i <= 10; i += 1 ) { sout | next(&f1) | next(&f2) | endl; } } \end{cfacode} \subsection{Construction} One important design challenge for coroutines and threads (shown in section \ref{threads}) is that the runtime system needs to run code after the user-constructor runs. In the case of coroutines, this challenge is simpler since there is no non-determinism from preemption or scheduling. However, the underlying challenge remains the same for coroutines and threads. The runtime system needs to create the coroutine's stack and more importantly prepare it for the first resumption. The timing of the creation is non-trivial since users both expect to have fully constructed objects once execution enters the coroutine main and to be able to resume the coroutine from the constructor. Like for regular objects, constructors can still leak coroutines before they are ready. There are several solutions to this problem but the chosen options effectively forces the design of the coroutine. Furthermore, \CFA faces an extra challenge as polymorphic routines create invisible thunks when casted to non-polymorphic routines and these thunks have function scope. For example, the following code, while looking benign, can run into undefined behaviour because of thunks: \begin{cfacode} //async: Runs function asynchronously on another thread forall(otype T) extern void async(void (*func)(T*), T* obj); forall(otype T) void noop(T *) {} void bar() { int a; async(noop, &a); } \end{cfacode} The generated C code\footnote{Code trimmed down for brevity} creates a local thunk to hold type information: \begin{ccode} extern void async(/* omitted */, void (*func)(void *), void *obj); void noop(/* omitted */, void *obj){} void bar(){ int a; void _thunk0(int *_p0){ /* omitted */ noop(/* omitted */, _p0); } /* omitted */ async(/* omitted */, ((void (*)(void *))(&_thunk0)), (&a)); } \end{ccode} The problem in this example is a race condition between the start of the execution of \code{noop} on the other thread and the stack frame of \code{bar} being destroyed. This extra challenge limits which solutions are viable because storing the function pointer for too long only increases the chances that the race will end in undefined behavior; i.e. the stack based thunk being destroyed before it was used. This challenge is an extension of challenges that come with second-class routines. Indeed, GCC nested routines also have the limitation that the routines cannot be passed outside of the scope of the functions these were declared in. The case of coroutines and threads is simply an extension of this problem to multiple call-stacks. \subsection{Alternative: Composition} One solution to this challenge would be to use composition/containement, \begin{cfacode} struct Fibonacci { int fn; // used for communication coroutine c; //composition }; void ?{}(Fibonacci* this) { this->fn = 0; (&this->c){}; } \end{cfacode} There are two downsides to this approach. The first, which is relatively minor, is that the base class needs to be made aware of the main routine pointer, regardless of whether a parameter or a virtual pointer is used, this means the coroutine data must be made larger to store a value that is actually a compile time constant (address of the main routine). The second problem, which is both subtle and significant, is that now users can get the initialisation order of there coroutines wrong. Indeed, every field of a \CFA struct is constructed but in declaration order, unless users explicitly write otherwise. This semantics means that users who forget to initialize a the coroutine may resume the coroutine with an uninitilized object. For coroutines, this is unlikely to be a problem, for threads however, this is a significant problem. \subsection{Alternative: Reserved keyword} The next alternative is to use language support to annotate coroutines as follows: \begin{cfacode} coroutine Fibonacci { int fn; // used for communication }; \end{cfacode} This mean the compiler can solve problems by injecting code where needed. The downside of this approach is that it makes coroutine a special case in the language. Users who would want to extend coroutines or build their own for various reasons can only do so in ways offered by the language. Furthermore, implementing coroutines without language supports also displays the power of \CFA. While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can both be constructed by users without using the language support. The reserved keywords are only present to improve ease of use for the common cases. \subsection{Alternative: Lamda Objects} For coroutines as for threads, many implementations are based on routine pointers or function objects\cit. For example, Boost implements coroutines in terms of four functor object types: \begin{cfacode} asymmetric_coroutine<>::pull_type asymmetric_coroutine<>::push_type symmetric_coroutine<>::call_type symmetric_coroutine<>::yield_type \end{cfacode} Often, the canonical threading paradigm in languages is based on function pointers, pthread being one of the most well known examples. The main problem of this approach is that the thread usage is limited to a generic handle that must otherwise be wrapped in a custom type. Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda based coroutines adds very little. A variation of this would be to use an simple function pointer in the same way pthread does for threads : \begin{cfacode} void foo( coroutine_t cid, void * arg ) { int * value = (int *)arg; //Coroutine body } int main() { int value = 0; coroutine_t cid = coroutine_create( &foo, (void*)&value ); coroutine_resume( &cid ); } \end{cfacode} This semantic is more common for thread interfaces than coroutines but would work equally well. As discussed in section \ref{threads}, this approach is superseeded by static approaches in terms of expressivity. \subsection{Alternative: Trait-based coroutines} Finally the underlying approach, which is the one closest to \CFA idioms, is to use trait-based lazy coroutines. This approach defines a coroutine as anything that satisfies the trait \code{is_coroutine} and is used as a coroutine is a coroutine. \begin{cfacode} trait is_coroutine(dtype T) { void main(T * this); coroutine_desc * get_coroutine(T * this); }; \end{cfacode} This ensures an object is not a coroutine until \code{resume} (or \code{prime}) is called on the object. Correspondingly, any object that is passed to \code{resume} is a coroutine since it must satisfy the \code{is_coroutine} trait to compile. The advantage of this approach is that users can easily create different types of coroutines, for example, changing the memory foot print of a coroutine is trivial when implementing the \code{get_coroutine} routine. The \CFA keyword \code{coroutine} only has the effect of implementing the getter and forward declarations required for users to only have to implement the main routine. \begin{center} \begin{tabular}{c c c} \begin{cfacode}[tabsize=3] coroutine MyCoroutine { int someValue; }; \end{cfacode} & == & \begin{cfacode}[tabsize=3] struct MyCoroutine { int someValue; coroutine_desc __cor; }; static inline coroutine_desc * get_coroutine( struct MyCoroutine * this ) { return &this->__cor; } void main(struct MyCoroutine * this); \end{cfacode} \end{tabular} \end{center} \section{Thread Interface}\label{threads} The basic building blocks of multi-threading in \CFA are \glspl{cfathread}. Both use and kernel threads are supported, where user threads are the concurrency mechanism and kernel threads are the parallel mechanism. User threads offer a flexible and lightweight interface. A thread can be declared using a struct declaration \code{thread} as follows: \begin{cfacode} thread foo {}; \end{cfacode} As for coroutines, the keyword is a thin wrapper arount a \CFA trait: \begin{cfacode} trait is_thread(dtype T) { void ^?{}(T* mutex this); void main(T* this); thread_desc* get_thread(T* this); }; \end{cfacode} Obviously, for this thread implementation to be usefull it must run some user code. Several other threading interfaces use a function-pointer representation as the interface of threads (for example \Csharp~\cite{Csharp} and Scala~\cite{Scala}). However, this proposal considers that statically tying a \code{main} routine to a thread superseeds this approach. Since the \code{main} routine is already a special routine in \CFA (where the program begins), it is possible naturally extend the semantics using overloading to declare mains for different threads (the normal main being the main of the initial thread). As such the \code{main} routine of a thread can be defined as \begin{cfacode} thread foo {}; void main(foo* this) { sout | "Hello World!" | endl; } \end{cfacode} In this example, threads of type \code{foo} start execution in the \code{void main(foo*)} routine which prints \code{"Hello World!"}. While this proposoal encourages this approach to enforce strongly-typed programming, users may prefer to use the routine based thread semantics for the sake of simplicity. With these semantics it is trivial to write a thread type that takes a function pointer as parameter and executes it on its stack asynchronously \begin{cfacode} typedef void (*voidFunc)(void); thread FuncRunner { voidFunc func; }; //ctor void ?{}(FuncRunner* this, voidFunc inFunc) { func = inFunc; } //main void main(FuncRunner* this) { this->func(); } \end{cfacode} An advantage of the overloading approach to main is to clearly highlight where and what memory is required to pass parameters and return values to/from a thread. Of course for threads to be useful, it must be possible to start and stop threads and wait for them to complete execution. While using an \acrshort{api} such as \code{fork} and \code{join} is relatively common in the literature, such an interface is unnecessary. Indeed, the simplest approach is to use \acrshort{raii} principles and have threads \code{fork} once the constructor has completed and \code{join} before the destructor runs. \begin{cfacode} thread World; void main(thread World* this) { sout | "World!" | endl; } void main() { World w; //Thread forks here //Printing "Hello " and "World!" are run concurrently sout | "Hello " | endl; //Implicit join at end of scope } \end{cfacode} This semantic has several advantages over explicit semantics typesafety is guaranteed, a thread is always started and stopped exaclty once and users cannot make any progamming errors. Another advantage of this semantic is that it naturally scale to multiple threads meaning basic synchronisation is very simple \begin{cfacode} thread MyThread { //... }; //main void main(MyThread* this) { //... } void foo() { MyThread thrds[10]; //Start 10 threads at the beginning of the scope DoStuff(); //Wait for the 10 threads to finish } \end{cfacode} However, one of the apparent drawbacks of this system is that threads now always form a lattice, that is they are always destroyed in opposite order of construction because of block structure. However, storage allocation os not limited to blocks; dynamic allocation can create threads that outlive the scope in which the thread is created much like dynamically allocating memory lets objects outlive the scope in which they are created \begin{cfacode} thread MyThread { //... }; //main void main(MyThread* this) { //... } void foo() { MyThread* long_lived; { MyThread short_lived; //Start a thread at the beginning of the scope DoStuff(); //create another thread that will outlive the thread in this scope long_lived = new MyThread; //Wait for the thread short_lived to finish } DoMoreStuff(); //Now wait for the short_lived to finish delete long_lived; } \end{cfacode}