- 区别pid,tid,tgid
案例代码:
#include <unistd.h>
#include <sys/syscall.h>
#include <stdio.h>
#include <pthread.h>
#define gettidv1() syscall(__NR_gettid) // new form
#define gettidv2() syscall(SYS_gettid) // traditional form
void *ThreadFunc1()
{
printf("the pthread_1 id is %ld\n", pthread_self());
printf("the thread_1's Pid is %d\n", getpid());
printf("The LWPID/tid of thread_1 is: %ld\n", (long int)gettidv1());
pause();
return 0;
}
void *ThreadFunc2()
{
printf("the pthread_2 id is %ld\n", pthread_self());
printf("the thread_2's Pid is %d\n", getpid());
printf("The LWPID/tid of thread_2 is: %ld\n", (long int)gettidv1());
pause();
return 0;
}
int main(int argc, char *argv[])
{
pid_t tid;
pthread_t pthread_id;
printf("the master thread's pthread id is %ld\n", pthread_self());
printf("the master thread's Pid is %d\n", getpid());
printf("The LWPID of master thread is: %ld\n", (long int)gettidv1());
// 创建2个线程
pthread_create(&pthread_id, NULL, ThreadFunc2, NULL);
pthread_create(&pthread_id, NULL, ThreadFunc1, NULL);
pause();
return 0;
}
打开两个窗口进行测试:
窗口1:~/Documents/work/code/albert$ ./threadTest
the master thread’s pthread id is 139914098607936
the master thread’s Pid is 47735
The LWPID of master thread is: 47735
the pthread_2 id is 139914090309376
the thread_2’s Pid is 47735
The LWPID/tid of thread_2 is: 47736
the pthread_1 id is 139914081916672
the thread_1’s Pid is 47735
The LWPID/tid of thread_1 is: 47737
窗口2:~/Documents/work/code/albert$ ps -eo pid,tid,lwp,tgid,pgrp,sid,tpgid,args -L | awk ‘{if(NR==1) print $0; if($8~/threadTest/) print $0}’
PID TID LWP TGID PGRP SID TPGID COMMAND
47735 47735 47735 47735 47735 31981 47735 ./threadTest
47735 47736 47736 47735 47735 31981 47735 ./threadTest
47735 47737 47737 47735 47735 31981 47735 ./threadTest