% ======================================================================
% ======================================================================
\chapter{Concurrency Basics}\label{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 multiple call-stacks and scheduling among threads of execution executing on these stacks. Concurrency without parallelism only requires having multiple call stacks (or contexts) for a single thread of execution.

Execution with a single thread and multiple stacks where the thread is self-scheduling deterministically across the stacks is called coroutining. Execution with a single and multiple stacks but where the thread is scheduled by an oracle (non-deterministic from the thread's perspective) across the stacks is called concurrency.

Therefore, a minimal concurrency system can be achieved by creating coroutines (see Section \ref{coroutine}), which instead of context-switching among each other, always ask an oracle where to context-switch next. While coroutines can execute on the caller's stack-frame, stack-full coroutines allow full generality and are sufficient as the basis for concurrency. The aforementioned oracle is a scheduler and the whole system now follows a cooperative threading-model (a.k.a., non-preemptive scheduling). The oracle/scheduler can either be a stack-less or stack-full entity and correspondingly require one or two context-switches to run a different coroutine. In any case, a subset of concurrency related challenges start to appear. For the complete set of concurrency challenges to occur, the only feature missing is preemption.

A scheduler introduces order of execution uncertainty, while preemption introduces uncertainty about where context switches occur. Mutual exclusion and synchronization are ways of limiting non-determinism in a concurrent system. Now it is important to understand that uncertainty is desirable; uncertainty can be used by runtime systems to significantly increase performance and is often the basis of giving a user the illusion that tasks are running in parallel. Optimal performance in concurrent applications is often obtained by having as much non-determinism as correctness allows.

\section{\protect\CFA's Thread Building Blocks}
One of the important features that are missing in C is threading\footnote{While the C11 standard defines a ``threads.h'' header, it is minimal and defined as optional. As such, library support for threading is far from widespread. At the time of writing the thesis, neither \texttt{gcc} nor \texttt{clang} support ``threads.h'' in their respective standard libraries.}. On modern architectures, a lack of threading is unacceptable~\cite{Sutter05, Sutter05b}, and therefore modern programming languages must have the proper tools to allow users to write efficient concurrent programs to take advantage of parallelism. As an extension of C, \CFA needs to express these concepts in a way that is as natural as possible to programmers familiar with imperative languages. And being a system-level language means programmers expect to choose precisely which features they need and which cost they are willing to pay.

\section{Coroutines: A Stepping Stone}\label{coroutine}
While the main focus of this proposal is concurrency and parallelism, it is important to address coroutines, which are actually a significant building block of a concurrency system. \textbf{Coroutine}s are generalized routines which have predefined points where execution is suspended and can be resumed at a later time. Therefore, they need to deal with context switches and other context-management operations. This proposal includes coroutines both as an intermediate step for the implementation of threads, and a first-class feature of \CFA. Furthermore, many design challenges of threads are at least partially present in designing coroutines, which makes the design effort that much more relevant. The core \acrshort{api} of coroutines revolves around two features: independent call-stacks and \code{suspend}/\code{resume}.

\begin{table}
\begin{center}
\begin{tabular}{c @{\hskip 0.025in}|@{\hskip 0.025in} c @{\hskip 0.025in}|@{\hskip 0.025in} c}
\begin{ccode}[tabsize=2]
//Using callbacks
void fibonacci_func(
	int n,
	void (*callback)(int)
) {
	int first = 0;
	int second = 1;
	int next, i;
	for(i = 0; i < n; i++)
	{
		if(i <= 1)
			next = i;
		else {
			next = f1 + f2;
			f1 = f2;
			f2 = next;
		}
		callback(next);
	}
}

int main() {
	void print_fib(int n) {
		printf("%d\n", n);
	}

	fibonacci_func(
		10, print_fib
	);



}
\end{ccode}&\begin{ccode}[tabsize=2]
//Using output array
void fibonacci_array(
	int n,
	int* array
) {
	int f1 = 0; int f2 = 1;
	int next, i;
	for(i = 0; i < n; i++)
	{
		if(i <= 1)
			next = i;
		else {
			next = f1 + f2;
			f1 = f2;
			f2 = next;
		}
		array[i] = next;
	}
}


int main() {
	int a[10];

	fibonacci_func(
		10, a
	);

	for(int i=0;i<10;i++){
		printf("%d\n", a[i]);
	}

}
\end{ccode}&\begin{ccode}[tabsize=2]
//Using external state
typedef struct {
	int f1, f2;
} Iterator_t;

int fibonacci_state(
	Iterator_t* it
) {
	int f;
	f = it->f1 + it->f2;
	it->f2 = it->f1;
	it->f1 = max(f,1);
	return f;
}







int main() {
	Iterator_t it={0,0};

	for(int i=0;i<10;i++){
		printf("%d\n",
			fibonacci_state(
				&it
			);
		);
	}

}
\end{ccode}
\end{tabular}
\end{center}
\caption{Different implementations of a Fibonacci sequence generator in C.}
\label{lst:fibonacci-c}
\end{table}

A good example of a problem made easier with coroutines is generators, e.g., generating the Fibonacci sequence. This problem comes with the challenge of decoupling how a sequence is generated and how it is used. Listing \ref{lst:fibonacci-c} shows conventional approaches to writing generators in C. All three of these approach suffer from strong coupling. The left and centre approaches require that the generator have knowledge of how the sequence is used, while the rightmost approach requires holding internal state between calls on behalf of the generator and makes it much harder to handle corner cases like the Fibonacci seed.

Listing \ref{lst:fibonacci-cfa} is an example of a solution to the Fibonacci problem using \CFA coroutines, where the coroutine stack holds sufficient state for the next generation. This solution has the advantage of having very strong decoupling between how the sequence is generated and how it is used. Indeed, this version is as easy to use as the \code{fibonacci_state} solution, while the implementation is very similar to the \code{fibonacci_func} example.

\begin{figure}
\begin{cfacode}[caption={Implementation of Fibonacci using coroutines},label={lst:fibonacci-cfa}]
coroutine Fibonacci {
	int fn; //used for communication
};

void ?{}(Fibonacci& this) { //constructor
	this.fn = 0;
}

//main automatically called on first resume
void main(Fibonacci& this) with (this) {
	int fn1, fn2; 		//retained between resumes
	fn  = 0;
	fn1 = fn;
	suspend(this); 		//return to last resume

	fn  = 1;
	fn2 = fn1;
	fn1 = fn;
	suspend(this); 		//return to last resume

	for ( ;; ) {
		fn  = fn1 + fn2;
		fn2 = fn1;
		fn1 = 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}
\end{figure}

Listing \ref{lst:fmt-line} shows the \code{Format} coroutine for restructuring text into groups of character blocks of fixed size. The example takes advantage of resuming coroutines in the constructor to simplify the code and highlights the idea that interesting control flow can occur in the constructor.

\begin{figure}
\begin{cfacode}[tabsize=3,caption={Formatting text into lines of 5 blocks of 4 characters.},label={lst:fmt-line}]
//format characters into blocks of 4 and groups of 5 blocks per line
coroutine Format {
	char ch;									//used for communication
	int g, b;								//global because used in destructor
};

void  ?{}(Format& fmt) {
	resume( fmt );  						//prime (start) coroutine
}

void ^?{}(Format& fmt) with fmt {
	if ( fmt.g != 0 || fmt.b != 0 )
	sout | endl;
}

void main(Format& fmt) with fmt {
	for ( ;; ) {							//for as many characters
		for(g = 0; g < 5; g++) {		//groups of 5 blocks
			for(b = 0; b < 4; fb++) {	//blocks of 4 characters
				suspend();
				sout | ch;					//print character
			}
			sout | "  ";					//print block separator
		}
		sout | endl;						//print group separator
	}
}

void prt(Format & fmt, char ch) {
	fmt.ch = ch;
	resume(fmt);
}

int main() {
	Format fmt;
	char ch;
	Eof: for ( ;; ) {						//read until end of file
		sin | ch;							//read one character
		if(eof(sin)) break Eof;			//eof ?
		prt(fmt, ch);						//push character for formatting
	}
}
\end{cfacode}
\end{figure}

\subsection{Construction}
One important design challenge for implementing coroutines and threads (shown in section \ref{threads}) is that the runtime system needs to run code after the user-constructor runs to connect the fully constructed object into the system. In the case of coroutines, this challenge is simpler since there is no non-determinism from preemption or scheduling. However, the underlying challenge remains the same for coroutines and threads.

The runtime system needs to create the coroutine's stack and, more importantly, prepare it for the first resumption. The timing of the creation is non-trivial since users expect both to have fully constructed objects once execution enters the coroutine main and to be able to resume the coroutine from the constructor. There are several solutions to this problem but the chosen option effectively forces the design of the coroutine.

Furthermore, \CFA faces an extra challenge as polymorphic routines create invisible thunks when cast to non-polymorphic routines and these thunks have function scope. For example, the following code, while looking benign, can run into undefined behaviour because of thunks:

\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); //start thread running noop with argument 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 storage management issue, the function pointer \code{_thunk0} is only valid until the end of the block, which limits the viable solutions because storing the function pointer for too long causes undefined behaviour; i.e., the stack-based thunk being destroyed before it can be used. This challenge is an extension of challenges that come with second-class routines. Indeed, GCC nested routines also have the limitation that nested routine cannot be passed outside of the declaration scope. The case of coroutines and threads is simply an extension of this problem to multiple call stacks.

\subsection{Alternative: Composition}
One solution to this challenge is to use composition/containment, where coroutine fields are added to manage the coroutine.

\begin{cfacode}
struct Fibonacci {
	int fn; //used for communication
	coroutine c; //composition
};

void FibMain(void*) {
	//...
}

void ?{}(Fibonacci& this) {
	this.fn = 0;
	//Call constructor to initialize coroutine
	(this.c){myMain};
}
\end{cfacode}
The downside of this approach is that users need to correctly construct the coroutine handle before using it. Like any other objects, the user must carefully choose construction order to prevent usage of objects not yet constructed. However, in the case of coroutines, users must also pass to the coroutine information about the coroutine main, like in the previous example. This opens the door for user errors and requires extra runtime storage to pass at runtime information that can be known statically.

\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}
The \code{coroutine} keyword means the compiler can find and inject code where needed. The downside of this approach is that it makes coroutine a special case in the language. Users wanting to extend coroutines or build their own for various reasons can only do so in ways offered by the language. Furthermore, implementing coroutines without language supports also displays the power of the programming language used. While this is ultimately the option used for idiomatic \CFA code, coroutines and threads can still be constructed by users without using the language support. The reserved keywords are only present to improve ease of use for the common cases.

\subsection{Alternative: Lambda Objects}

For coroutines as for threads, many implementations are based on routine pointers or function objects~\cite{Butenhof97, ANSI14:C++, MS:VisualC++, BoostCoroutines15}. For example, Boost implements coroutines in terms of four functor object types:
\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, \texttt{pthread} being one of the most well-known examples. The main problem of this approach is that the thread usage is limited to a generic handle that must otherwise be wrapped in a custom type. Since the custom type is simple to write in \CFA and solves several issues, added support for routine/lambda based coroutines adds very little.

A variation of this would be to use a simple function pointer in the same way \texttt{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 semantics is more common for thread interfaces but coroutines work equally well. As discussed in section \ref{threads}, this approach is superseded by static approaches in terms of expressivity.

\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} (as defined below) and is used as a coroutine.

\begin{cfacode}
trait is_coroutine(dtype T) {
      void main(T& this);
      coroutine_desc* get_coroutine(T& this);
};

forall( dtype T | is_coroutine(T) ) void suspend(T&);
forall( dtype T | is_coroutine(T) ) void resume (T&);
\end{cfacode}
This ensures that an object is not a coroutine until \code{resume} is called on the object. Correspondingly, any object that is passed to \code{resume} is a coroutine since it must satisfy the \code{is_coroutine} trait to compile. The advantage of this approach is that users can easily create different types of coroutines, for example, changing the memory layout of a coroutine is trivial when implementing the \code{get_coroutine} routine. The \CFA keyword \code{coroutine} simply has the effect of implementing the getter and forward declarations required for users to implement the main routine.

\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}

The combination of these two approaches allows users new to coroutining and concurrency to have an easy and concise specification, while more advanced users have tighter control on memory layout and initialization.

\section{Thread Interface}\label{threads}
The basic building blocks of multithreading in \CFA are \glspl{cfathread}. Both user and kernel threads are supported, where user threads are the concurrency mechanism and kernel threads are the parallel mechanism. User threads offer a flexible and lightweight interface. A thread can be declared using a struct declaration \code{thread} as follows:

\begin{cfacode}
thread foo {};
\end{cfacode}

As for coroutines, the keyword is a thin wrapper around 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 useful it must run some user code. Several other threading interfaces use a function-pointer representation as the interface of threads (for example \Csharp~\cite{Csharp} and Scala~\cite{Scala}). However, this proposal considers that statically tying a \code{main} routine to a thread supersedes this approach. Since the \code{main} routine is already a special routine in \CFA (where the program begins), it is a natural extension of the semantics to use overloading to declare mains for different threads (the normal main being the main of the initial thread). As such the \code{main} routine of a thread can be defined as
\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 thesis encourages this approach to enforce strongly typed programming, users may prefer to use the routine-based thread semantics for the sake of simplicity. With the static semantics it is trivial to write a thread type that takes a function pointer as a parameter and executes it on its stack asynchronously.
\begin{cfacode}
typedef void (*voidFunc)(int);

thread FuncRunner {
	voidFunc func;
	int arg;
};

void ?{}(FuncRunner & this, voidFunc inFunc, int arg) {
	this.func = inFunc;
	this.arg  = arg;
}

void main(FuncRunner & this) {
	//thread starts here and runs the function
	this.func( this.arg );
}

void hello(/*unused*/ int) {
	sout | "Hello World!" | endl;
}

int main() {
	FuncRunner f = {hello, 42};
	return 0?
}
\end{cfacode}

A consequence of the strongly typed approach to main is that memory layout of parameters and return values to/from a thread are now explicitly specified in the \acrshort{api}.

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} after the constructor has completed and \code{join} before the destructor runs.
\begin{cfacode}
thread World;

void main(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: a thread is always started and stopped exactly once, users cannot make any programming errors, and it naturally scales to multiple threads meaning basic synchronization is very simple.

\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 drawbacks of this approach is that threads always form a tree where nodes must always outlive their children, i.e., they are always destroyed in the opposite order of construction because of C scoping rules. This restriction is relaxed by using dynamic allocation, so threads can outlive the scope in which they are created, much like dynamically allocating memory lets objects outlive the scope in which they are created.

\begin{cfacode}
thread MyThread {
	//...
};

void main(MyThread& this) {
	//...
}

void foo() {
	MyThread* long_lived;
	{
		//Start a thread at the beginning of the scope
		MyThread short_lived;

		//create another thread that will outlive the thread in this scope
		long_lived = new MyThread;

		DoStuff();

		//Wait for the thread short_lived to finish
	}
	DoMoreStuff();

	//Now wait for the long_lived to finish
	delete long_lived;
}
\end{cfacode}
