深入理解 Linux的进程,线程,PID,LWP,TID,TGID(2)

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;
}

注意编译的时候要利用-l指定library参数。

# gcc threadTest.c -o threadTest -l pthread

执行程序,结果如下:

# ./threadTest the master thread's pthread id is 140154481125184 the master thread's Pid is 20992 The LWPID of master thread is: 20992 the pthread_1 id is 140154464352000 the thread_1's Pid is 20992 The LWPID/tid of thread_1 is: 20994 the pthread_2 id is 140154472744704 the thread_2's Pid is 20992 The LWPID/tid of thread_2 is: 20993

上述结果说明pthread id是pthread库提供的ID,在系统级别没有意义。pid都是线程组leader的进程ID,即20992。而lwp(tid)则是线程ID,分别是20993和20994。

同时利用ps来查看结果,注意ps默认只打印进程级别信息,需要用-L选项来查看线程基本信息。

# 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 20992 20992 20992 20992 20992 30481 20992 ./threadTest 20992 20993 20993 20992 20992 30481 20992 ./threadTest 20992 20994 20994 20992 20992 30481 20992 ./threadTest

从上述结果中可以看到:

PID=TGID: 20992

TID=LWP: 20993 or 20994

至于SID,30481是bash shell的进程ID。

Linux用户态命令查看线程 top

默认top显示的是task数量,即进程。

深入理解 Linux的进程,线程,PID,LWP,TID,TGID

可以利用敲"H",来切换成线程。如下,可以看到实际上有96个线程。也可以直接利用top -H命令来直接打印线程情况。

深入理解 Linux的进程,线程,PID,LWP,TID,TGID

ps

ps的-L选项可以看到线程,通常能打印出LWP和NLWP相关信息。如下命令即可查看线程信息:

ps -eLf

pidstat

pidstat -t [-p pid号] 可以打印出线程之间的关系。

htop

要在htop中启用线程查看,开启htop,然后按<F2>来进入htop的设置菜单。选择“设置”栏下面的“显示选项”,然后开启“树状视图”和“显示自定义线程名”选项。按<F10>退出设置。
注:MAC的F2按fn+F2。

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/12077.html