[SPCA] Finish unorthodox control flow

This commit is contained in:
2026-01-16 08:19:39 +01:00
parent 8ca91096af
commit ad5098bb07
9 changed files with 135 additions and 1 deletions

View File

@@ -75,4 +75,3 @@ A more complex example, passing addresses as arguments: \\
This function swaps 2 array elements (using a \texttt{swap} function) and adds the first value to an accumulator.
\inputcodewithfilename{gas}{code-examples/01_asm/}{07_swap_and_sum.s}

View File

@@ -0,0 +1,19 @@
\newpage
\subsection{Unorthodox Control Flow}
In \lC, the \texttt{setjmp.h} header file can be included, which gives us access to \texttt{setjmp} and \texttt{longjmp}.
To use them, we first need to declare a \texttt{jmp\_buf} somewhere, usually as a static variable.
The \texttt{setjmp( jmp\_buf env } function stores the current stack / environment in the \texttt{jmp\_buf} and returns 0.
The \texttt{longjmp( jmp\_buf env, int val )} function causes a second return, which returns \texttt{val},
to the \texttt{setjmp} invocation and jumps back to that place.
\inputcodewithfilename{c}{code-examples/01_asm/}{08_unorthodox-controlflow.c}
What the above code outputs is: \texttt{second} followed by \texttt{main}.
\newpage
They are implemented in Assembly as follows. Nothing really surprising for the implementation there.
The assembly code is from the Musl \lC\ library
\inputcodewithfilename{gas}{code-examples/01_asm/}{09_setjmp-longjmp.s}

View File

@@ -0,0 +1,12 @@
\newpage
\subsection{Coroutines}
Coroutines are functions that call each other when they are done or they need new data to work on.
An example is a decompresser that calls a parser when it has finished compressing parts of the file and that parser then again calls the decompresser when it has finished parsing.
We can implement that either by rewriting the functions into a single function, which often is a bit clumsy.
A way around this is to use \bi{Continuations}, where the first function saves its state and the context is switched to the other function.
That function can then load its state and continue where it left off, runs until it finishes its task, then saves its state and the context switches back to the original function.
\inputcodewithfilename{c}{code-examples/01_asm/}{10_coroutine.h}
\inputcodewithfilename{c}{code-examples/01_asm/}{10_coroutine.c}
As you can see, the \texttt{setjmp.h} functions are the foundation of all concurrent programming.