-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathdemo2.cpp
More file actions
executable file
·67 lines (53 loc) · 1.44 KB
/
Copy pathdemo2.cpp
File metadata and controls
executable file
·67 lines (53 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdio.h>
#include <ucontext.h>
#include <unistd.h>
const int MAX_COUNT = 5;
static ucontext_t uc[4]; // 添加一个元素
static int count = 0;
void ping();
void pong();
void ping()
{
while (count < MAX_COUNT)
{
printf("ping %d\n", ++count);
// yield to pong
sleep(1);
swapcontext(&uc[1], &uc[2]); // 保存当前context于uc[1],切换至uc[2]的context运行
printf("ping -> end \n");
}
}
void pong()
{
while (count < MAX_COUNT)
{
printf("pong %d\n", ++count);
// yield to ping
sleep(1);
swapcontext(&uc[2], &uc[1]); // 保存当前context于uc[2],切换至uc[1]的context运行
printf("pong -> end \n");
}
}
char st1[8192];
char st2[8192];
int main(int argc, char *argv[])
{
// initialize context
printf("times %d \n", MAX_COUNT);
getcontext(&uc[1]);
getcontext(&uc[2]);
getcontext(&uc[3]);
printf("begin \n");
uc[1].uc_link = &uc[3]; // 上下文完毕之后,改成切换到uc[3]
uc[1].uc_stack.ss_sp = st1; // 设置新的堆栈
uc[1].uc_stack.ss_size = sizeof st1;
makecontext(&uc[1], ping, 0);
uc[2].uc_link = &uc[3]; // 上下文完毕之后,改成切换到uc[3]
uc[2].uc_stack.ss_sp = st2; // 设置新的堆栈
uc[2].uc_stack.ss_size = sizeof st2;
makecontext(&uc[2], pong, 0);
// start ping-pong
swapcontext(&uc[0], &uc[1]);
printf("end \n");
return 0;
}