如何获取进程的线程id?------说说gettid与pthread_self的区别

       一切源于需求,需要用到,所以来说说。

 

       之前一直用pthread_self来获取线程id, 这个id通常臭大臭大的。让我纳闷的是,翻遍了所有资料,没有办法通过linux命令来获取线程id, 我不信这个邪。

       当然, 我也查到了, 可以用 ps -Tp pid或者top -Hp pid的方式来获取线程id,  我用了这两个命令,但获取不到如上的线程id. 后来我才明白, 这两个命令确实可以获取到线程id,  但不是上述那个臭大臭大的id, 其实, 这就涉及到gettid与pthread_self的区别了。

       gettid获取的是内核中的真实线程id,  而pthread_self获取的是posix线程id, 不一样的。上述命令获取的线程id与gettid对应, 跟pthread_self没有毛关系。

       pthread_self不说了, 来看看gettid:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
#include <pthread.h>

void* threadFunc(void* p)
{
    printf("threadFunc is %d\n",  gettid());

    int i = 0;
    while (1)
    {
        sleep(1);
    }

        return NULL;
    }

int main ()
{
    printf("main thread id is %d\n", gettid());

    pthread_t id;
    pthread_create (&id, NULL, threadFunc, NULL);
    pthread_create (&id, NULL, threadFunc, NULL);
    pthread_create (&id, NULL, threadFunc, NULL);
    pthread_create (&id, NULL, threadFunc, NULL);
    pthread_create (&id, NULL, threadFunc, NULL);
    pthread_create (&id, NULL, threadFunc, NULL);

    int i = 0;
    while (1)
    {
        sleep(1);
    }

    return 0;
}

         编译:g++ test.cpp -lpthread

         运行起来, 然后查看一下:

ubuntu@VM-0-15-ubuntu:~$ ps -aux |grep a.out
ubuntu   26810  0.0  0.0  55692   696 pts/3    Sl+  20:12   0:00 ./a.out
ubuntu   26908  0.0  0.1  13228   972 pts/4    S+   20:13   0:00 grep a.out
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ ps -Tp 26810
  PID  SPID TTY          TIME CMD
26810 26810 pts/3    00:00:00 a.out
26810 26811 pts/3    00:00:00 a.out
26810 26812 pts/3    00:00:00 a.out
26810 26813 pts/3    00:00:00 a.out
26810 26814 pts/3    00:00:00 a.out
26810 26815 pts/3    00:00:00 a.out
26810 26816 pts/3    00:00:00 a.out
ubuntu@VM-0-15-ubuntu:~$ 

       看到没: 主线程 + 6个子线程。 第二列就是线程id.  进程id和主线程id是相等的。

 

       看到这里, 有个疑问, 快速启动多个a.out进程, 如果进程id紧紧挨在一起, 那么线程id是不是就重叠了呢?

       我快速开启4个a.out进程, 来看看:

ubuntu@VM-0-15-ubuntu:~$ ps -aux | grep a.out 
ubuntu   27224  0.0  0.0  55692   752 pts/6    Sl+  20:18   0:00 ./a.out
ubuntu   27232  0.0  0.0  55692   700 pts/5    Sl+  20:18   0:00 ./a.out
ubuntu   27239  0.0  0.0  55692   692 pts/4    Sl+  20:18   0:00 ./a.out
ubuntu   27247  0.0  0.0  55692   692 pts/3    Sl+  20:18   0:00 ./a.out

         可以看到, 进程id并没有紧挨在一起, 给线程id留了空隙, 有点意思。

 

         最后思考一个问题:进程的线程id一定是如上所示的连续的吗?

         当然不一定!

 

      

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值