线程私有数据__thread

        之前的一篇文章 线程私有数据 是依赖于 pthread 库实现的,而今天介绍的这个则是 gcc 提供的标识符:__thread,它只能用于修饰 POD 类型,不能修饰复合类型,如struct, class。否则会出现编译错误如:

 代码参考 muduo 库里的一个参数:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <thread>
#include <sys/syscall.h>

namespace CurrentThread
{
    __thread int tCachedTid = 0;

    void cacheTid()
    {
        if(tCachedTid == 0)
        {
            printf("first time get tid\n");
            tCachedTid = (int)syscall(SYS_gettid);
        }
    }

    inline int tid()
    {
        if(tCachedTid == 0)
        {
            cacheTid();
        }

        return tCachedTid;
    }
}

class CThreadProc
{
public:
    CThreadProc()
    {

    }
    ~CThreadProc()
    {

    }

    void operator()()
    {
        int count = 0;
        while (1)
        {
            printf("child thread id(%lu)\n", CurrentThread::tid());
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            if(count++ == 100)         
            {
                break;
            }
        }
    }
};

int main()
{
    CThreadProc threacProc;
    std::thread t(threacProc);

    CThreadProc threacProc2;
    std::thread t2(threacProc2);

    t.join();
    t2.join();

    return 0;
}

变量 tCachedTid 是缓存了调用线程的线程id,当有线程调用 CurrentThread::tid() 时,第一次会调用系统调用,然后线程id缓存在了 tCachedTid,此线程再调用 CurrentThread::tid() 时,即从缓存数据里直接取,避免每次都调用系统调用,提高效率。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值