Created
January 18, 2022 03:45
-
-
Save kougazhang/144327e704d9a972a547e8993675c9ae to your computer and use it in GitHub Desktop.
#thread_local
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 参考:https://www.cnblogs.com/pop-lar/p/5123014.html | |
// 从 foo 的输出可以看出: | |
// 声明为 thread_local 的本地变量在线程中是持续存在的,不同于普通临时变量的生命周期, | |
// 它具有 static 变量一样的初始化特征和生命周期,虽然他并没有被声明为 static。 | |
#include <thread> | |
thread_local int g_n = 1; | |
void f() { | |
g_n++; | |
printf("id=%zu, g_n=%d\n", std::hash<std::thread::id>{}(std::this_thread::get_id()), g_n); | |
} | |
void foo() { | |
thread_local int i=0; | |
printf("id=%zu, i=%d\n", std::hash<std::thread::id>{}(std::this_thread::get_id()), i); | |
i++; | |
} | |
void f2() { | |
foo(); | |
foo(); | |
foo(); | |
} | |
int main() { | |
g_n++; | |
f(); | |
std::thread t1(f); | |
std::thread t2(f); | |
t1.join(); | |
t2.join(); | |
f2(); | |
std::thread t4(f2); | |
std::thread t5(f2); | |
t4.join(); | |
t5.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment