參考文獻:
C++11 thread_local 用法 | 拾荒志
https://murphypei.github.io/blog/2020/02/thread-local
你可曾聽過網(wǎng)絡編程中應用線程本地存儲蒙兰? - 知乎
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秒朦肘,防止輸出時數(shù)據(jù)交錯(Mac會出現(xiàn))
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 循環(huán)中,使用的都是線程中的同一個變量垦页,也側(cè)面印證了 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
體現(xiàn)了局部變量的特征。