在Linux中,我们可以通过如下命令查看多线程程序的执行情况:
top -H -p pid
例如:如下top显示界面:
如上图所示,PID为:12982的线程,cpu占用率达到320%,其实这个程序是一个多线程程序,那么我们想看它的子线程,那么如何查看呢?
通过如下命令即可:
top -H -p 12982
结果如下图:
通过上图,我们便可以看到该进程下面有多个子线程在运行,只不过占据着不同的 cpu 核心。
那么,我们如何在程序里去获得这些 PID 的值呢?
方法如下:
#include <stdio.h>
#include <sys/syscall.h>//Linux system call for thread id
#include <assert.h>
#include <pthread.h>
void *nbi(void *arg)
{
int i;
printf("child thread lwpid = %u\n", syscall(SYS_gettid));
printf("child thread tid = %u\n", pthread_self());
scanf("%d", i);//code dump
}
int main()
{
pthread_t tid;
int rc;
printf("main thread lwpid = %u\n", syscall(SYS_gettid));
printf("main thread tid = %u\n", pthread_self());
rc = pthread_create(&tid, NULL, nbi, NULL);
assert(0 == rc);
pthread_join(tid, NULL);
return 0;
}
请注意方法:syscall(SYS_gettid),这个方法所获取的lwpid,正是在top中显示出来的 PID.
更多参考:http://blog.csdn.net/happen23/article/details/41777749
文章的脚注信息由WordPress的wp-posturl插件自动生成


微信扫一扫,打赏作者吧~![[整理][转载]win下网卡抓包发包库Npcap使用](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2023/08/demo_1-1024x711.jpg&w=280&h=210&zc=1)
![[转载]基础数据char,int,double,string是线程安全的吗?](http://www.jyguagua.com/wp-content/themes/begin/img/random/7.jpg)
![[已解决]nc命令报错 close: Bad file descriptor](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2022/03/Snipaste_2022-03-18_20-16-48.png&w=280&h=210&zc=1)
![[整理]用c++编写的RDTSC性能计时器](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2020/12/rdtsc-assembly-example.jpg&w=280&h=210&zc=1)