/
sample13_cls.cpp
105 lines (89 loc) · 2.29 KB
/
sample13_cls.cpp
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/************************************************
* libgo sample13
************************************************
* 线程有TLS(thread local storage),
* libgo的协程也有CLS(coroutine local storage)
* 同样支持TLS的三种使用场景:
1.块作用域(函数内)
2.全局作用域
3.类静态成员变量
* 不仅如此, 还支持非静态成员变量
* 声明一个cls变量使用宏: co_cls
* Eg:
int& var = co_cls(int);
或
co_cls_ref(int) var = co_cls(int);
* 块作用域中推荐使用第一种写法, 免掉了一次隐士转换, 更便于使用
* 第一种写法一定注意不要忘记引用符&
*
* 全局作用域\类成员变量只能使用第二种写法, 并且会有编译warning,
* 请勿开启-Werror选项!
*
* co_cls_ref(int)定义了一个可以隐式转换成int&的模板类,
* 如果此处不是int而是自定义类, 要访问类的成员或函数,
* 需要手动转换一次:
* Eg:
co_cls_ref(MyClass) ref = co_cls(MyClass);
MyClass & var = ref;
var.xxx();
* co_cls宏还可以传入任意数量的初始化参数:
* Eg:
int& var = co_cls(int, 10);
************************************************/
#include <unistd.h>
#include <iostream>
#include <libgo/libgo.h>
#include "win_exit.h"
using namespace std;
struct A {
A() { cout << "A construct" << endl; }
~A() { cout << "A destruct" << endl; }
int i = 0;
};
void foo() {
A& a = co_cls(A);
cout << "foo -> " << a.i << endl;
a.i++;
}
void foo3() {
for (int i = 0; i < 3; i++)
foo();
}
struct B {
static co_cls_ref(int) a;
};
co_cls_ref(int) B::a = co_cls(int);
void bar() {
B::a += 10;
cout << "bar -> " << B::a << endl;
}
auto gCls = co_cls(int);
void car() {
cout << "car -> " << gCls << endl;
gCls++;
}
void oneLine() {
int &a = co_cls(int, 0), &b = co_cls(int, 10);
int &c = co_cls(int, 20);
cout << "oneLine -> "<< "a=" << a << ", b=" << b << ", c=" << c << endl;
}
void test() {
cout << " ---- function ---- " << endl;
go foo3;
foo();
foo();
cout << " ---- static member ---- " << endl;
go bar;
bar();
bar();
cout << " ---- global ---- " << endl;
go car;
car();
car();
oneLine();
co_sched.Stop();
}
int main() {
go test;
co_sched.Start();
}