std::thread::get_id

< cpp‎ | thread‎ | thread

std::thread::id get_id() const noexcept;
(C++11 起)

返回一个 std::thread::id 值,它标识与 *this 关联的线程。

参数

(无)

返回值

标识与 *this 关联的线程的 std::thread::id 类型的值。若无关联的线程,则返回默认构造的 std::thread::id

示例

#include <chrono>
#include <iostream>
#include <thread>
 
void foo()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    std::thread t1(foo);
    std::thread::id t1_id = t1.get_id();
 
    std::thread t2(foo);
    std::thread::id t2_id = t2.get_id();
 
    std::cout << "t1 的 id: " << t1_id << '\n';
    std::cout << "t2 的 id: " << t2_id << '\n';
 
    t1.join();
    t2.join();
 
    std::cout << "合并后 t1 的 id: " << t1.get_id() << '\n';
    std::cout << "合并后 t2 的 id: " << t2.get_id() << '\n';
}

可能的输出:

t1 的 id: 140146221688576
t2 的 id: 140146213295872
合并后 t1 的 id: 不执行线程的 thread::id
合并后 t2 的 id: 不执行线程的 thread::id

参阅

表示线程的 id
(公开成员类)
检查线程是否可合并,即潜在运行于并行上下文之中
(公开成员函数)