通过Linux的top和ps命令中,默认看到最多的是pid (process ID),也许你也能看到lwp (thread ID)和tgid (thread group ID for the thread group leader)等等,而在Linux库函数和系统调用里也许你注意到了pthread id和tid等等。还有更多的ID,比如pgrp (process group ID), sid (session ID for the session leader)和 tpgid (tty process group ID for the process group leader)。
Linux下的各种ID:
- pid:进程ID。
- lwp:线程ID。在用户态的命令(比如ps)中常用的显示方式。
- tid:线程ID,等于lwp。tid在系统提供的接口函数中更常用,比如syscall(SYS_gettid)和syscall(__NR_gettid)。
- tgid:线程组ID,也就是线程组leader的进程ID,等于pid。
- pgid:进程组ID,也就是进程组leader的进程ID。
- pthread id:pthread库提供的ID,生效范围不在系统级别,可以忽略。
- sid: session ID for thesession leader。
- tpgid: tty process group ID for the process group leader。
pthread_self它返回一个 pthread_t 类型的变量,指代的是调用 pthread_self 函数的线程的 “ID”。这个“ID”是 pthread 库给每个线程定义的进程内唯一标识,是 pthread 库维持的。由于每个进程有自己独立的内存空间,故此“ID”的作用域是进程级而非系统级(内核不认识)。
下面是一个测试程序:
#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;
}
编译命令如下:
gcc test.c -o test -l pthread
测试结果如下:
该测试程序创建了两个线程。两个线程的PID是一样的,TID不一样。使用ps命令可以查看到PID。
使用ps -eLf可以查看到更详细的信息。