【C++】线程局部存储

KeyWords: TLS,thread_local, __thread,C11,C++11

引用阅读1-cywosp的【每天进步一点点——Linux中的线程局部存储(一)】

引用阅读2-努力努力再努力r的【__thread】

引用阅读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

机器上实验的结果与官方提供的不考虑线程的输出顺序是一样的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值