在正常的开发中,有时候我们需要知道当前进程的每个线程的CPU使用情况,方便对每个线程进行分析,此时就需要在top指令中显示线程的使用情况。
在使用中要使用prctl为线程重命名,不然在top中显示的就是主进程的名字,就无法确认是那个线程了。
使用指令:
#top -Hp PID
PID为进程的PID,使用后可以只看此进程的CPU使用情况。
如下:
或者使用指令:
#top -H
或
#top
然后再输入H
即可看到所有进程的线程CPU使用情况。
下面代码为上下截图的示例代码:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/prctl.h>
void* thread11(void* arg)
{
printf("----->thread11\n");
prctl(PR_SET_NAME, "thread11");
while(1)
{
sleep(1);
}
}
void* thread12(void* arg)
{
printf("----->thread12\n");
prctl(PR_SET_NAME, "thread12");
while(1)
{
usleep(1);
}
}
void* thread13(void* arg)
{
printf("----->thread13\n");
prctl(PR_SET_NAME, "thread13");
while(1)
{
usleep(100);
}
}
int main()
{
pthread_t thread[3];
int s32Ret = 0;
s32Ret = pthread_create(&thread[0], NULL, thread11, NULL);
printf("pthread_create, ret:%d\n", s32Ret);
sleep(1);
s32Ret = pthread_create(&thread[1], NULL, thread12, NULL);
printf("pthread_create, ret:%d\n", s32Ret);
sleep(1);
s32Ret = pthread_create(&thread[0], NULL, thread13, NULL);
printf("pthread_create, ret:%d\n", s32Ret);
sleep(1);
while(1)
{
sleep(1);
}
return 0;
}