KeyWords: TLS,thread_local, __thread,C11,C++11
引用阅读1-cywosp的【每天进步一点点——Linux中的线程局部存储(一)】
引用阅读3-whatday的【线程局部存储(TLS)】
引用阅读4-沪江塞外的【2020-09-17】
引用阅读5-cywosp的【每天进步一点点——Linux中的线程局部存储(二)】
thread_local - cppreference.com
Storage class specifiers - cppreference.com
Storage class specifiers, except for thread_local, are not allowed on explicit
specializations and explicit instantiations:
template <class T> struct S {
thread_local static int tlm;
};
template <> thread_local int S<float>::tlm = 0; // "static" does not appear here
除了thread_local,存储类标识符不允许被用在显示特例化和隐式实例化中.
C语言的实现:
TARS中使用的开源代码查询:
D:\005-02-代码\016-TARS\TARS\TarsFramework\TarsBenchmark\src\comm\transport.cpp【搜索 static __thread char buf[MAX_SENDBUF_SIZE]; 】
C++的实现thread_local(多处用到):
测试代码:
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
thread_local unsigned int rage = 1;
std::mutex cout_mutex;
void increase_rage(const std::string& thread_name)
{
++rage; // modifying outside a lock is okay; this is a thread-local variable
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "Rage counter for " << thread_name << ": " << rage << '\n';
}
int main()
{
std::thread a(increase_rage, "a"), b(increase_rage, "b");
{
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "Rage counter for main: " << rage << '\n';
}
a.join();
b.join();
}
我的机器上的执行结果:
root@muten-virtual-machine:/home/muten/C++11# g++ thread_local.cpp -lpthread
root@muten-virtual-machine:/home/muten/C++11# ./a.out
Rage counter for main: 1
Rage counter for b: 2
Rage counter for a: 2
官方提供的Possible output:
Rage counter for a: 2
Rage counter for main: 1
Rage counter for b: 2
机器上实验的结果与官方提供的不考虑线程的输出顺序是一样的.