C++获取线程标识符id(线程号)
头文件:<thread>
方法1:获取指定线程的线程id std::thread::id
方法2:获取当前线程的线程id std::this_thread::get_id()
案例解析:
void foo()
{
while (1) {
std::cout << "std::this_thread::get_id is : " << std::this_thread::get_id() << std::endl;
sleep(1);
}
}
int main()
{
std::thread first(foo); // thread first
std::thread second(foo); // thread second
std::cout << "std::thread::id is : " << first.get_id() << std::endl;
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
return 0;
}
结果输出:
[root@localhost]# g++ main.cpp -o main -lpthread
[root@localhost]# ./main
std::thread::id is : 140445889021696
std::this_thread::get_id is : 140445889021696
std::this_thread::get_id is : 140445880628992
std::this_thread::get_id is : 140445889021696
std::this_thread::get_id is : 140445880628992
std::this_thread::get_id is : 140445889021696
std::this_thread::get_id is : 140445880628992
^C
[root@localhost]#
分类:
C/C++多线程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类