参考文献:
C++11 thread_local 用法 | 拾荒志
https://murphypei.github.io/blog/2020/02/thread-local
你可曾听过网络编程中应用线程本地存储? - 知乎
https://zhuanlan.zhihu.com/p/103932878
C++11 thread_local用法 - 知乎
https://zhuanlan.zhihu.com/p/340201634
例子:
g++ testthread.cpp -lpthread
#include <iostream>
#include <thread>
void add(int n) {
thread_local int count = 0;
// static thread_local int count = 0; // 两种写法等价!
count += n;
// 休眠n秒,防止输出时数据交错(Mac会出现)
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout<<std::this_thread::get_id()<<":"<<count<<std::endl;
}
int main() {
std::thread td[2];
for (int i = 0; i < 2; i++) {
td[i] = std::thread(add, i+1);
}
for (int i = 0; i < 2; i++) {
td[i].join();
}
return 0;
}
#include <iostream>
#include <thread>
#include <mutex>
std::mutex cout_mutex; //方便多线程打印
thread_local int x = 1;
void thread_func(const std::string& thread_name) {
for (int i = 0; i < 3; ++i) {
x++;
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "thread[" << thread_name << "]: x = " << x << std::endl;
}
return;
}
int main() {
std::thread t1(thread_func, "t1");
std::thread t2(thread_func, "t2");
t1.join();
t2.join();
return 0;
}
输出:
thread[t2]: x = 2
thread[t2]: x = 3
thread[t2]: x = 4
thread[t1]: x = 2
thread[t1]: x = 3
thread[t1]: x = 4
可以看到虽然是局部变量,但是在每个线程的每次 for 循环中,使用的都是线程中的同一个变量,也侧面印证了 thread_local 变量会自动 static。
如果我们不加 thread_local,输出如下:
thread[t2]: x = 2
thread[t2]: x = 2
thread[t2]: x = 2
thread[t1]: x = 2
thread[t1]: x = 2
thread[t1]: x = 2
体现了局部变量的特征。