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