C++使用std:thread创建线程,其底层实现还是采用了NTPL的thread库,所以可以调用thread库的pthread_setname_np函数设置线程名字。
#include <iostream>
#include <thread>
using namespace std;
void t1() //普通的函数,用来执行线程
{
for (int i = 0; i < 20; ++i)
{
cout << "t1111\n";
}
while(1);
}
void SetThreadName(std::thread* thread, const char* threadName)
{
auto handle = thread->native_handle();//获取原生句柄
pthread_setname_np(handle,threadName);
}
int main()
{
thread th1(t1); //实例化一个线程对象th1,使用函数t1构造,然后该线程就开始执行了(t1())
SetThreadName(&th1,"hello");
cout << "here is main\n\n";
th1.join();
return 0;
}
编译命令:
g++ g.cc -lpthread -std=c++11
运行:./a.out
ubuntu下查看线程方法:top,然后输入大写H。