-
-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
Copy paththread-local.cpp
64 lines (55 loc) · 1.51 KB
/
thread-local.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
/*
g++ -std=c++11 -g -O0 thread-local.cpp -o thread-local
*/
#include <stdio.h>
// @see https://linux.die.net/man/3/pthread_create
#include <pthread.h>
// Global thread local int variable.
thread_local int tl_g_nn = 0;
// Global thread local variable object.
class MyClass
{
public:
int tl_nn;
MyClass(int nn) {
tl_nn = nn;
}
};
thread_local MyClass g_obj(0);
thread_local MyClass* gp_obj = new MyClass(0);
thread_local MyClass* gp_obj2 = NULL;
MyClass* get_gp_obj2()
{
if (!gp_obj2) {
gp_obj2 = new MyClass(0);
}
return gp_obj2;
}
void* pfn(void* arg)
{
int tid = (int)(long long)arg;
tl_g_nn += tid;
g_obj.tl_nn += tid;
gp_obj->tl_nn += tid;
get_gp_obj2()->tl_nn += tid;
printf("PFN%d: tl_g_nn(%p)=%d, g_obj(%p)=%d, gp_obj(%p,%p)=%d, gp_obj2(%p,%p)=%d\n", tid,
&tl_g_nn, tl_g_nn, &g_obj, g_obj.tl_nn, &gp_obj, gp_obj, gp_obj->tl_nn,
&gp_obj2, gp_obj2, get_gp_obj2()->tl_nn);
return NULL;
}
int main(int argc, char** argv)
{
pthread_t trd = NULL, trd2 = NULL;
pthread_create(&trd, NULL, pfn, (void*)1);
pthread_create(&trd2, NULL, pfn, (void*)2);
pthread_join(trd, NULL);
pthread_join(trd2, NULL);
tl_g_nn += 100;
g_obj.tl_nn += 100;
gp_obj->tl_nn += 100;
get_gp_obj2()->tl_nn += 100;
printf("MAIN: tl_g_nn(%p)=%d, g_obj(%p)=%d, gp_obj(%p,%p)=%d, gp_obj2(%p,%p)=%d\n",
&tl_g_nn, tl_g_nn, &g_obj, g_obj.tl_nn, &gp_obj, gp_obj, gp_obj->tl_nn,
&gp_obj2, gp_obj2, get_gp_obj2()->tl_nn);
return 0;
}