重写muduo之获取线程tid代码

目录

1、概述

2、CurrentThread.h

3、 CurrentThread.cc


1、概述

我们的服务器程序不一定就只有1个Eventloop,我们可能有很多的Eventloop,每个Eventloop都有很多channel,自己channel上的事件要在自己的Eventloop线程上去处理,Eventloop在这里涉及到获取当前线程的ID 

下面获取的是961这个进程中的线程,第一列是线程ID 

2、CurrentThread.h

我们看到使用了全局变量, 所有线程共享的,加了__thread,或者是C++11的thread_local来定义的话,就是:虽然是全局变量,但是会在每一个线程存储一份拷贝,这个线程对这个变量的更改,别的线程是看不到的。每一个线程都有自己的t_cachedTid。

void cacheTid():因为tid的访问是系统调用,总是从用户空间切换到系统空间的话,会比较浪费效率,所以第一次访问,就把当前线程的Tid存储起来,后边如果再访问就从缓存取。

#pragma once

#include <unistd.h>
#include <sys/syscall.h>

namespace CurrentThread
{
    extern __thread int t_cachedTid;

    void cacheTid();

    inline int tid()//内联函数,只在当前文件起作用
    {
        if(__builtin_expect(t_cachedTid==0,0))//缓存中没有这个tid
        {
            cacheTid();
        }
        return t_cachedTid;
    }
}

3、 CurrentThread.cc

#include "CurrentThread.h"

namespace CurrentThread
{
    __thread int t_cachedTid=0;

    void cacheTid()
    {
        if(t_cachedTid==0)
        {
            //通过Linux系统调用,获取当前线程的tid值
            t_cachedTid=static_cast<pid_t>(::syscall(SYS_gettid));
        }
    }
}

 

  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值