I am studying context switching in C programming and have found the following example code on the Internet. I am trying to figure out whether only
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ucontext.h>
4 #define MEM 64000
6 ucontext_t T1, T2, Main;
7 ucontext_t a;
9 int fn1()
11 printf("this is from 1\n");
15 void fn2()
17 printf("this is from 2\n");
19 printf("finished 1\n");
22 void start()
29 makecontext(&a, (void*)&fn1, 0);
32 int main(int argc, char *argv)
40 makecontext(&T1, (void*)&fn1, 0);
41 swapcontext(&Main, &T1);
47 makecontext(&T2, (void*)&fn2, 0);
48 swapcontext(&Main, &T2);
makecontext writes the function info into a context, and it will remain there until it is overwritten by something else.
getcontext overwites the entire context, so would overwrite any function written there by a previous call to
swapcontext completely overwrites the context pointed at by its first argument.
The basic idea is that a
u_context contains a snapshot of part of the process context at some time. It contains all the machine registers, stack info, and signal masks. It does NOT include any memory map or file descriptor state. The state in the
u_context is precisely all the state you need to manipulate in order to implement threads or coroutines.
swapcontext(¤t, &another) saves the current context in
current and switches to
another. At some later point, the code (runnning from
another context) may switch back to
current (with another call to
swapcontext) or it might switch to some third context.
When a context ends (the function set into it with
makecontext returns), if some context is pointed at by its
uc_link field, it will switch to that context. But if
uc_link is NULL, then the thread (and process if there's only one thread) will exit -- other contexts that are not running will just be abandoned.