一切源于需求,需要用到,所以来说说。
之前一直用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
#include
#include
#include
#define gettid() syscall(SYS_gettid)
#include
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一定是如上所示的连续的吗?
当然不一定!