使用prctl的PR_SET_NAME选项功能可以为线程命名,测试代码如下:
#include <stdio.h>
#include <pthread.h>
#include <sys/prctl.h>
#include <unistd.h>
void *func1(void *arg)
{
prctl(PR_SET_NAME, "func1");
pause();
}
void *func2(void *arg)
{
prctl(PR_SET_NAME, "func2");
pause();
}
int main()
{
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, func1, NULL);
pthread_create(&tid2, NULL, func2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
}
代码很简单,启动程序后,可以通过top -Hp pid 查看该程序的状态,可以看到输出如下:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
45731 xxxxx 20 0 26712 504 388 S 0.0 0.0 0:00.00 prctl
45733 xxxxx 20 0 26712 504 388 S 0.0 0.0 0:00.00 func1
45734 xxxxx 20 0 26712 504 388 S 0.0 0.0 0:00.00 func2
在top的输出中,有三个线程,其中有两个的名字是通过prctl设置的。在/proc/pid/task/tid/目录下的stat文件和status文件,也可以看到相应的名字,方便查看线程状态。