在进行多线程调试时,不知道哪个线程起来没起来,如果不设置独立的名字,则没法区分。因此考虑给每个线程设置一个名字,这样就可以方便直观查看了。
1. prctl() (只能给当前线程设置名称)
#include <sys/prctl.h>
iErr = prctl(PR_SET_NAME, “Hello_project”);
第一个参数是操作类型,指定PR_SET_NAME,即设置进程名
- PR_SET_NAME:设置当前线程的名字
- PR_GET_NAME:获得当前线程的名字
第二个参数是进程名字符串,长度至多16字节
prctl 缺点
prctl()只能设置/获取当前线程的名字
注意:只能设置本线程的名称,传入参数线程名超出长度,会自动截断
2、pthread_setname_np
#include <pthread.h>
pthread_setname_np(stThreadId, pstThread->pcThreadName);
由于prctl的缺点,所以pthread_setname_np()和pthread_getname_np应运而生,能设置指定线程的名称。
函数外(线程外)设置名称
std::thread t3(function_3);
pthread_setname_np(t3.native_handle(),"t3_thread");
函数内(线程内)设置名称
#include <pthread.h>
void function_3() {
pthread_setname_np(pthread_self(),"t3_threadGo");
while (1) {
sleep(1);
std::cout <<__FUNCTION__<<" i am live"<<std::endl;
}
}
std::thread t3(function_3);
注意:
pthread_setname_np传入参数线程名超出长度,不会自动截断,而是会返回错误码ERANGE(因为是非pthread标准实现,不同操作系统可能表现不一样)。
测试代码
代码文件:multithreads.cpp
编译指令:g++ --std=c++11 -o multiThread -pthread multithreads.cpp
执行:./multiThread
查到多线程:top -H -p $(ps -aux|grep “multiThread”|grep -v "grep"|awk '{print $2}')
代码:
#include <iostream>
#include <thread>
#include <unistd.h>
#include <sys/prctl.h>
#include <pthread.h>
void function_1() {
prctl(PR_SET_NAME,"t1-inner-set");
while (1) {
sleep(1);
std::cout <<__FUNCTION__<<" i am live"<<std::endl;
}
}
void function_2() {
while (1) {
sleep(1);
std::cout <<__FUNCTION__<<" i am live"<<std::endl;
}
}
void function_3() {
pthread_setname_np(pthread_self(),"t3_inner-ptset");
while (1) {
sleep(1);
std::cout <<__FUNCTION__<<" i am live"<<std::endl;
}
}
int main() {
std::thread t1(function_1);
std::thread t2(function_2);
pthread_setname_np(t2.native_handle(),"t2_outer_set");
std::thread t3(function_3);
t1.join();
t2.join();
t3.join();
return 0;
}
结果
top -H -p $(ps -aux|grep multiThread|grep -v "grep"|awk '{print $2}')或者使用ps -T -p <pid>查看:
参考
https://blog.csdn.net/bad_good_man/article/details/48787031