进程PID、线程PID、线程TID区别

进程PID、线程PID、线程TID区别

概念

  • 进程PID: 进程开启后,在系统内唯一,不可重复的
  • 线程PID: Linux中POSIX线程库实现的线程其实也是一个进程(LWP: Light Weight Process),只是该进程与主进程(启动线程的进程)共享一些资源而已,比如代码段和数据段等。在系统中是唯一的,不可重复的
  • 线程TID: 创建一个线程后,线程有一个标识符,此标识符只有在该线程所属的进程的上下文才有意义,为pthread_t数据类型。在不同进程中,可能出现相同的情况。

注意:

  • 主线程PID等于线程所在的进程的PID
  • TID的数据类型为pthread_t,是一个结构体数据类型,所以可移植操作系统实现不能把它作为整数处理
  • 各系统如何表示线程TID:
  1. Linux3.2.0使用无符号长整型表示pthread_t数据类型
  2. Solaris10使用无符号整型(不是长整型)表示pthread_t数据类型
  3. FreeBSD8.0和Mac OS X10.6.8用一个pthread_t结构的指针表示pthread_t数据类型(注意:事实上,FreeBSD和Mac OS x不用,Mac OS X主线程ID与pthread_create创建新线程的ID不在相同的地址范围内)

代码示例

#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <thread>
#include <sys/syscall.h>

void thread_func() 
{
    //获取线程TID
    printf("child thread id=0x%x\n",pthread_self());
    //获取线程PID
    pid_t tid = syscall(SYS_gettid);
    printf("child thread pid=0x%x\n",tid);
    while(1)
    {   
        //printf("hello world\n");
    }   
}


int main() 
{
    // 获取当前进程的PID
    pid_t pid = getpid();
    printf("Process id=0x%x",pid);
    //获取主线程PID
    print
[banting@localhost test]$ ./test85
Process id=0x15374d
main thread tid=0x7b611740
main thread pid=0x15374d
child thread tid=0x7a608700
child thread pid=0x15374e
^C
[banting@localhost test]$
[banting@localhost monitor-device-mgr]$ clear
[banting@localhost monitor-device-mgr]$ ps -eLf | grep test85
banting  1390413 1088622 1390413  0    2 10:36 pts/9    00:00:00 ./test85
banting  1390413 1088622 1390414 99    2 10:36 pts/9    00:00:24 ./test85
[banting@localhost monitor-device-mgr]$ top -Hp 1390413
top - 10:37:05 up 21 days, 10:13, 22 users,  load average: 0.69, 0.26, 0.13
Threads:   2 total,   1 running,   1 sleeping,   0 stopped,   0 zombie
%Cpu(s): 25.1 us,  0.0 sy,  0.0 ni, 74.9 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem : 16268040 total,  2792808 free,  3112988 used, 10362244 buff/cache
KiB Swap:  8257532 total,  8254336 free,     3196 used. 12475696 avail Mem
   PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND                                                                                                                             
1390414 banting   20   0   22996   1096    912 R 99.9  0.0   1:02.86 WorkerThread                                                                                                                        
1390413 banting   20   0   22996   1096    912 S  0.0  0.0   0:00.00 MainThread     

总结:

  1. Process id=0x15374d :进程ID(1390413 banting 20 0 22996 1096 912 S 0.0 0.0 0:00.00 MainThread)
  2. child thread pid=0x15374e : 子线程(1390414 banting 20 0 22996 1096 912 R 99.9 0.0 1:02.86 WorkerThread)
  3. 主线程ID main thread pid=0x15374d 等于进程ID Process id=0x15374d
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值