Linux获取线程id的方法学习

如何确认两段代码是不是在同一个线程中执行的呢?

通过查看资料,发现一种比较简单的方法就是在代码中使用printf将当前线程的id打印出来。
而这也分成两种情况:
1. 如果是pthread,则使用,
#include <pthread.h>

pthread_t pthread_self(void);

2. 如果不是pthread,即是由内核创建的线程,则使用,
#include <sys/types.h>

pid_t gettid(void);

获取线程所在的进程的id,方法如下:
#include <sys/types.h>
#include <unistd.h>

pid_t getpid(void);
pid_t getppid(void);

所以,我们在代码中使用如下的语句打印:
printf("\ntid=%lu, pid=%lu\n", gettid(), getpid());
这样就能获取当前代码所在的线程和进程了。

根据打印出来的进程的pid,获取进程名的方法是:
ls -lh /proc/pid/exe
lrwxrwxrwx 1 root root 0 Jan  1 20:48 /proc/pid/exe -> ...
sh-3.2#

查看thread id的方法有:
1. sh-3.2# ps -efL | grep process,
ps命令指定-L命令选项可以用来查看进程下所包含的所有线程。

2. sh-3.2# ls -l /proc/pid/task/
查看进程下当前有哪些task,这些task指的就是线程。

测试所遇到的实际状况:
1. 运行后发现两个线程虽然是同属于一个进程,但是使用如上两种方法查看线程时只能看到其中一个线程。
猜测是另一个线程已经退出了?有空时可以再确认一下。

2. 调用gettid()会出现编译错误,其原因是gettid是一个系统调用,在glibc中没有对应的库函数。

用户如果有需要,可以直接调用gettid所对应的系统调用。




一般用gettid()函数就可以得到,但gittid在默认配置下会链接失败

这时就要靠系统调用出马了

[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. #include <sys/syscall.h>//Linux system call for thread id  
  3. #include <assert.h>  
  4. #include <pthread.h>  
  5.   
  6. void *nbi(void *arg)  
  7. {  
  8.         int i;  
  9.         printf("child thread lwpid = %u\n", syscall(SYS_gettid));  
  10.         printf("child thread tid = %u\n", pthread_self());  
  11.         scanf("%d", i);//code dump  
  12. }  
  13. int main()  
  14. {  
  15.         pthread_t tid;  
  16.         int rc;  
  17.         printf("main thread lwpid = %u\n", syscall(SYS_gettid));  
  18.         printf("main thread tid = %u\n", pthread_self());  
  19.         rc = pthread_create(&tid, NULL, nbi, NULL);  
  20.         assert(0 == rc);  
  21.         pthread_join(tid, NULL);  
  22.   
  23.         return 0;  
  24. }  

运行结果:

root@rubic:~/test/thread# ./a.out
main thread lwpid = 825
main thread tid = 3076090112
child thread lwpid = 826
child thread tid = 3076086592
12
Segmentation fault (core dumped)


猜你喜欢

转载自blog.csdn.net/qq_31186123/article/details/79353190