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

原文链接: https://www.cnblogs.com/wangning-gogo/p/16594317.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++获取线程标识符id(线程号)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/190729

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午4:26
下一篇 2023年2月12日 下午4:26

相关推荐