正在显示
2 个修改的文件
包含
66 行增加
和
0 行删除
trunk/research/arm/jmp_2flow.cpp
0 → 100644
1 | +/* | ||
2 | +# http://blog.csdn.net/win_lin/article/details/40948277 | ||
3 | +# for all supports setjmp and longjmp: | ||
4 | + g++ -g -O0 -o jmp_2flow jmp_2flow.cpp | ||
5 | +*/ | ||
6 | +#include <stdio.h> | ||
7 | +#include <stdlib.h> | ||
8 | +#include <setjmp.h> | ||
9 | + | ||
10 | +jmp_buf context_thread_0; | ||
11 | +jmp_buf context_thread_1; | ||
12 | + | ||
13 | +void thread0_functions() | ||
14 | +{ | ||
15 | + int ret = setjmp(context_thread_0); | ||
16 | + // when ret is 0, create thread, | ||
17 | + // when ret is not 0, longjmp to this thread. | ||
18 | + if (ret == 0) { | ||
19 | + return; | ||
20 | + } | ||
21 | + | ||
22 | + int age = 10000; | ||
23 | + const char* name = "winlin"; | ||
24 | + printf("[thread0] age=%d, name=%s\n", age, name); | ||
25 | + if (!setjmp(context_thread_0)) { | ||
26 | + printf("[thread0] switch to thread1\n"); | ||
27 | + longjmp(context_thread_1, 1); | ||
28 | + } | ||
29 | + | ||
30 | + // crash, for the stack is modified by thread1. | ||
31 | + // name = 0x2b67004009c8 <error: Cannot access memory at address 0x2b67004009c8> | ||
32 | + printf("[thread0] terminated, age=%d, name=%s\n", age, name); | ||
33 | + exit(0); | ||
34 | +} | ||
35 | + | ||
36 | +void thread1_functions() | ||
37 | +{ | ||
38 | + int ret = setjmp(context_thread_1); | ||
39 | + // when ret is 0, create thread, | ||
40 | + // when ret is not 0, longjmp to this thread. | ||
41 | + if (ret == 0) { | ||
42 | + return; | ||
43 | + } | ||
44 | + | ||
45 | + int age = 11111; | ||
46 | + printf("[thread1] age=%d\n", age); | ||
47 | + if (!setjmp(context_thread_1)) { | ||
48 | + printf("[thread1] switch to thread0\n"); | ||
49 | + longjmp(context_thread_0, 1); | ||
50 | + } | ||
51 | + | ||
52 | + printf("[thread1] terminated, age=%d\n", age); | ||
53 | + exit(0); | ||
54 | +} | ||
55 | + | ||
56 | +int main(int argc, char** argv) | ||
57 | +{ | ||
58 | + thread0_functions(); | ||
59 | + thread1_functions(); | ||
60 | + | ||
61 | + // kickstart | ||
62 | + longjmp(context_thread_0, 1); | ||
63 | + | ||
64 | + return 0; | ||
65 | +} |
-
请 注册 或 登录 后发表评论