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]#

posted @   gǒが油メo  阅读(6171)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示