C++11 的 thread_local

线程一般没有自己的全局变量,C++11 引入了 thread_local 解决了这个问题。

示例

#include <iostream>
#include <string>
#include <thread>
#include <mutex>

#include <iostream>
#include <thread>
using namespace std;

thread_local int i = 0;

int func(int val){
    i = val;
    i = i + 2;
    std::cout << i;
}

int func2(){
    std::cout << i;
}

int main(){
    i = 9;
    std::thread t1(func,1);
    std::thread t2(func,2);
    std::thread t3(func,3);
    std::thread t4(func2);

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    std::cout << i << std::endl;
    return 0;
} 

结果打印 53409。线程 t1,t2,t3,t4 是 4 个子线程,在每个线程中都独享一份 i,i 的初始值为 0,所以运算都是在这个基础上进行,打印出 5340。

参考

http://trickness.github.io/morden%20c++/2015/09/26/C++11&14-thread_local/

http://en.cppreference.com/w/cpp/language/storage_duration

转载于:https://my.oschina.net/lvyi/blog/826151

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值