Overview of this blog

  1. Intended Audience -> Read if you are unaware about point 3 and point 4.
  2. Why I am writing this blog ?
  3. Function decorator in C.
  4. Can we do golang like concurrent programming in C ?

Why I am writing this blog ?

After I became aware of golang’s concurrency, javascript async and python’s decorator I have always thought can we do similar things in C. So this is the product of that thought process. Of course It’s not decent at all, but If we have better preprocessing abilities in C, C can be a lot more powerful than it is now.

Decorating function in C

I don’t know a very neat way to wrap function but this helps.

#include <stdio.h>
#include <time.h> 

void print ( void * x ) {
  int y=*((int *)(x));
  printf("%d\n", y);
void time_your_function ( void (*f)(void *), void *param) {
	clock_t t; 
    t = clock(); 
	t = clock() - t;
	double time_taken = ((double)t)/CLOCKS_PER_SEC;
	printf("took %f seconds to execute \n", time_taken);

int main(){
	int a=9;
	void *x=&a;

In this way if you define your params to be passed as void * then you can decorate your function easily in a more general way.

Can we do golang like concurrent programming in C ?

I have been thinking on this for a long time, can we do golang like asynchronous programming in C. Enter the keyword “green thread”. So what is a green thread -> Green threads emulate multithreaded environments without relying on any native OS capabilities, and they are managed in user space instead of kernel space, enabling them to work in environments that do not have native thread support.Ref

#include <stdio.h>
#include <ucontext.h>
#include <unistd.h>
void func()
int main(int argc, const char *argv[]){
    ucontext_t curr;

    puts("Hello world");
    return 0;
typedef struct ucontext
      unsigned long int uc_flags;
      struct ucontext *uc_link;
      stack_t uc_stack;
      mcontext_t uc_mcontext;
      __sigset_t uc_sigmask;
      struct _fpstate __fpregs_mem;
    } ucontext_t;

So what is context ?
Context contains everything required to run a process. From register state to stack variables. Get context is used to save current context of process in variable provided in argument. Setcontext is used to set current context of the process to given save context. As you can see in the above code whenever set context is called it will restart the programme from line 3.

Can we initialise an empty context ?

Is there a working example out there ?

What is the above example about ? So using the above library you can run preemptible threads in a single threads like golang, of course you will not find all the beauiful syntax of message passing but on conceptual ground it is a good start.

That’s all folks.