我正在研究 C 编程中的上下文切换,并在 Internet 上找到了以下示例代码。我试图弄清楚是否只有makecontext()
函数才能触发执行某些操作的函数。其他函数如setcontext()
、getcontext()
和swapcontext()
用于设置上下文。
将makecontext()
函数及其参数附加到上下文,该函数是否始终坚持上下文,直到对其提交更改?
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ucontext.h>
4 #define MEM 64000
5
6 ucontext_t T1, T2, Main;
7 ucontext_t a;
8
9 int fn1()
10 {
11 printf("this is from 1\n");
12 setcontext(&Main);
13 }
14
15 void fn2()
16 {
17 printf("this is from 2\n");
18 setcontext(&a);
19 printf("finished 1\n");
20 }
21
22 void start()
23 {
24 getcontext(&a);
25 a.uc_link=0;
26 a.uc_stack.ss_sp=malloc(MEM);
27 a.uc_stack.ss_size=MEM;
28 a.uc_stack.ss_flags=0;
29 makecontext(&a, (void*)&fn1, 0);
30 }
31
32 int main(int argc, char *argv[])
33 {
34 start();
35 getcontext(&Main);
36 getcontext(&T1);
37 T1.uc_link=0;
38 T1.uc_stack.ss_sp=malloc(MEM);
39 T1.uc_stack.ss_size=MEM;
40 makecontext(&T1, (void*)&fn1, 0);
41 swapcontext(&Main, &T1);
42 getcontext(&T2);
43 T2.uc_link=0;
44 T2.uc_stack.ss_sp=malloc(MEM);
45 T2.uc_stack.ss_size=MEM;
46 T2.uc_stack.ss_flags=0;
47 makecontext(&T2, (void*)&fn2, 0);
48 swapcontext(&Main, &T2);
49 printf("completed\n");
50 exit(0);
51 }