d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

Adding Coroutine Feature To C Language

Prerequisites

If you are an absolute beginner, you can go through all of the below pre-requisites. And if you are not a beginner, you better know what to skip!

Coroutine Basics

What Is Coroutine?

  • A coroutine is a function/sub-routine(co-operative sub-routine to be precise) that can be suspended and resumed.
  • In other words, you can think of coroutine as the in-between solution of normal function & thread. Because, once function/sub-routine called, it executes until the end. On the other hand, the thread can be blocked by synchronization primitives (like mutex, semaphores, etc) or suspended by the OS scheduler. But again, you can not decide on suspension & resumption on it (as it is done by the OS scheduler).
  • With coroutine, it can be suspended on a pre-defined point & resumed later on a need basis by the programmer. So here programmer will be having complete control of execution flow. That too with minimal overhead as compared to thread.
  • A coroutine is also known as native threads, fibers (in windows), lightweight threads, green threads (in java), etc.

Why Do We Need Coroutine?

As I usually do, before learning anything new, you should be asking this question to yourself. But, let me answer it:

  • Coroutines can provide a very high level of concurrency with very little overhead, as it doesn’t need OS intervention in scheduling. While in a threaded environment, you have to bear the OS scheduling overhead.
  • A coroutine can suspend on pre-determined points, so you can also avoid locking on shared data structures. Because you would never tell your code to switch to another coroutine in the middle of a critical section.
  • With the threads, each thread needs its own stack with thread local storage & other things. So your memory usage grows linearly with the number of threads you have. While with co-routines, the number of routines you have doesn’t have a direct relationship with your memory usage.
  • For most use cases, a coroutine is a more optimal choice as it is faster as compared to a thread.
  • And if you are still not convinced then wait for my C++ Coroutine post.

To-the-point Context Switching API Theory

  • Before we dive into a coroutine, we need to understand the below foundation functions/APIs for context switching. Off-course, as we do, with less, to-the-point theory, and with more code examples.

    1. setcontext
    2. getcontext
    3. makecontext
    4. swapcontext
  • If you are already familiar with setjmp/longjmp, then you might have ease in understanding these functions. You can consider these functions as an advanced version of setjmp/longjmp.
  • The only difference is setjmp/longjmp allows only a single non-local jump up the stack. Whereas, these APIs allow the creation of multiple cooperative threads of control, each with its own stack or entry point.

Data Structure e To Store Execution Context

  • ucontext_t type structure defined below is used to store the execution context.
  • All four (setcontext, getcontext, makecontext & swapcontext) control flow functions operate on this structure.
  • uc_link points to the context which will be resumed when the current context exits, if the context was created with makecontext (a secondary context).
  • uc_stack is the stack used by the context.
  • uc_mcontext stores execution state, including all registers and CPU flags, frame/base pointer(i.e. indicates current execution frame), instruction pointer(i.e. program counter), link register(i.e. stores return address) and the stack pointer(i.e. indicates current stack limit or end of current frame). mcontext_t is an opaque type.
  • uc_sigmask is used to store the set of signals blocked in the context. Which isn’t the focus for today.

int setcontext(const ucontext_t *ucp)

  • This function transfers control to the context in ucp. Execution continues from the point at which the context was stored in ucp. setcontext does not return.

int getcontext(ucontext_t *ucp)

  • Saves current context into ucp. This function returns in two possible cases:
    1. after the initial call,
    2. or when a thread switches to the context in ucp via setcontext or swapcontext.
  • The getcontext function does not provide a return value to distinguish the cases (its return value is used solely to signal error), so the programmer must use an explicit flag variable, which must not be a register variable and must be declared volatile to avoid constant propagation or other compiler optimizations.

void makecontext(ucontext_t *ucp, void (*func)(), int argc, ...)

  • The makecontext function sets up an alternate thread of control in ucp , which has previously been initialized using getcontext.
  • The ucp.uc_stack member should be pointed to an appropriately sized stack; the constant SIGSTKSZ or MINSIGSTKSZ is commonly used.
  • When ucp is jumped to using setcontext or swapcontext, execution will begin at the entry point to the function pointed to by func, with argc arguments as specified. When func terminates, control is returned to the context specified in ucp.uc_link.

int swapcontext(ucontext_t *oucp, ucontext_t *ucp)

  • Saves the current execution state into oucp and then transfers the execution control to ucp.

[Example 1]: Understanding Context Switching With setcontext & getcontext Functions

  • Now, that we have read lot of theory. Let’s create meaning out of it.
  • Consider the below program that implements plain infinite loop printing “Hello world” every second.
  • Here, getcontextis returning with both possible cases as we have mentioned earlier i.e.:
    1. after the initial call,
    2. when a thread switches to the context via setcontext.
  • Rest is self-explanatory. 

[Example 2]: Understanding Control Flow With makecontext & swapcontext Functions

  • Here, the makecontext function sets up an alternate thread of control in ctx. And when jump made with ctx by using swapcontext, execution will begin at assign, with respective arguments as specified.
  • When assign terminates, control will be switch to ctx.uc_link. Which is pointing to back & will be populated by swapcontext before jump/context-switch.
  • If the ctx.uc_link is made to 0, then the current execution context is considered as the main context, and the thread will exit when assign context gets over.
  • Before a call is made to makecontext, the application/developer needs to ensure that the context being modified has a pre-allocated stack. And argc matches the number of arguments of type int passed to func. Otherwise, the behavior is undefined.

Coroutine in C Language

  • Initially, I have created single file example. But then I realized it’s too much for a single file. Hence, I split implementation & usage examples into different files, which will make the example more comprehensible & easy to understand. ## Coroutine Implementation
  • So, here is the simplest coroutine in c language:

coroutine.h

  • Just ignore the coroutine APIs as of now.
  • The main thing to focus on here is the coroutine handler that has following field:
    • function : That holds the address of the actual coroutine function supplied by the user.
    • suspend_context : That used to suspend the coroutine function.
    • resume_context : That holds the context of actual coroutine function.
    • yield_value: To store the return value between intermediate suspension point & also final return value.
    • is_coro_finished : An indicator to check status on coroutine lifetime.

coroutine.c

  • The most used APIs for coroutine is coro_resume & coro_yield that drags the actual work of suspension & resumption.
  • If you already have consciously gone through the above Context Switching API Examples, then I don’t think there is much to explain for coro_resume & coro_yield. Its just coro_yield jumps to coro_resume & vice-versa. Except for the first call to coro_resume which jumps to _coro_entry_point.
  • coro_new function allocates memory for handler as well as stack & then populates the handler members. Again getcontext & makecontext should be clear by this point. If not then please re-read above section on Context Switching API Examples.
  • If you genuinely understand the above coroutine API implementation, then the obvious question would be why do we even need _coro_entry_point? Why can’t we directly jump to actual coroutine function?.
    • But then my argument will be “How do you ensure the lifetime of coroutine?”
    • Which technically means, number of call to coro_resume should be similar/valid to number of call to coro_yield plus one(for actual return).
    • Otherwise, you can not keep track of yields. And behavior will become undefined.
  • Nonetheless, _coro_entry_point function is needed otherwise there is no way by which you can deduce the coroutine execution finished completely. And next/subsequent call to coro_resume is not valid anymore.

Coroutine Lifetime

  • By the above implementation, using a coroutine handler, you should only be able to execute the coroutine function completely once throughout the program/application life.
  • If you want to call the coroutine function again, then you need to create a new coroutine handler. And rest of the process will remain the same.

Coroutine Usage Example

coroutine_example.c

  • Usecase is pretty straight forward:
    • First, you create a coroutine handler.
    • Then, you start/resume the actual coroutine function with the help of the same coroutine handler.
    • And, whenever your actual coroutine function encounters a call the coro_yield, it will suspend the execution & return the value passed in 2nd argument of coro_yield.
  • And when actual coroutine function execution finishes completely. The call to coro_resume will return -1 to indicate that the coroutine handler object is no more valid & the lifetime is expired.
  • So, you see coro_resume is a wrapper to our coroutine hello_world which executes hello_world in parts(obviously by context switching).

Compiling

  • I have tested this example in WSL with GCC 9.3.0 & Glibc 2.31.
$ gcc -I./ coroutine_example.c coroutine.c  -o myapp && ./myapp 
Hello 
World

Parting Words

You see, there is no magic if you understand how the CPU executes the code, given Glibc provided a rich set of context switching API. And, from the perspective of low-level developers, it’s merely a well-arranged & difficult to organize/maintain(if used raw) context switching function calls. 

My intention here was to put the foundation for C++20 Coroutine. Because I believe, if you see the code from CPU & compiler’s point of view, then everything becomes easy to reason about in C++.

See you next time with my C++20 Coroutine post!

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this