获取线程号 gettid()【原创】

author:张继飞

项目中寻找bug经常会用到gettid(),来获取线程号,判断问题出在哪个线程里面。对于gettid先来man一下。

GETTID(2)                  Linux Programmer's Manual                 GETTID(2)

NAME
       gettid - get thread identification

SYNOPSIS
       #include <sys/types.h>
       #include <linux/unistd.h>
       #include <errno.h>

       _syscall0(pid_t, gettid)
               /* Using syscall(2) may be preferable; see intro(2) */

       pid_t gettid(void);

DESCRIPTION
       gettid()  returns  the thread ID of the current process. This is equal to the process ID (as returned by
       getpid(2)), unless the process is part of a thread group (created by specifying the CLONE_THREAD flag to
       the  clone(2) system call). All processes in the same thread group have the same PID, but each one has a
       unique TID.

RETURN VALUE
       On success, returns the thread ID of the current process.

ERRORS
       This call is always successful.

CONFORMING TO
       gettid() is Linux specific and should not be used in programs that are intended to be portable.

SEE ALSO
       clone(2), fork(2), getpid(2)

Linux 2.4.20                      2003-02-01                         GETTID(2)、

 

应用中,使用上面的头文件可能会出现诸如这样的error: undefined reference to `gettid'

我们可以自已定义实现方法,如下:

#include <sys/syscall.h> /*此头必须带上*/

pid_t gettid()
{
     return syscall(SYS_gettid);  /*这才是内涵*/
}

然后使用的时候直接printf("\n%s Thread id : gettid() == %d\n",__FUNCTION__,gettid()); 便可查阅当前thread ID。

我的项目中thread ID都是顺序下来的,进程也即主线程ID为45,然后分别创建了4个子线程,其按照创建顺序,分配的ID分别为46,47,48,49。

下面说下使用命令查看thread ID。

# pgrep test   /*test为正在运行的application*/

45            /*此为进程PID也即主线程ID,二者相同*/

所有进程PID都能在/proc下看到,ls /proc 的话,所有数字都代表一个进程,下一步

# ls /proc/45/task/  
45  46  47  48  49  /* ok 该进程下的所有thread  ID都展现在我们眼前了*/

 

end

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值