C++11——多线程编程13 如何获取线程ID

翻译来自:https://thispointer.com/c11-how-to-get-a-thread-id/

在本文中,我们将讨论如何在不同场景下获取线程 ID。

每个线程都有一个唯一的 ID 与之关联。c++11 提供了一个类型来存储这个 id,即

std::thread::id

std::thread::id 的对象是可比较的,标准也提供了 std::hash() 的可复制和默认实现。因此, std::thread::id 对象可以用作 map 和 unordered_map 中的键。

std::thread::get_id()

std::thread 提供了一个成员函数 get_id() 即

std::thread::id get_id () const noexcept ;

它返回关联对象的线程 ID。

让我们使用这个函数来获取线程 id,即

从分离的线程对象中获取线程 ID

让我们创建一个线程,即

// 开始线程

std::thread dThObj ( threadFunction ) ;

从线程对象中分离线程即

// Detached the thread

dThObj.detach();

现在线程对象没有与它的 id 相关联的线程。因此,分离线程对象上的 get_id() 将返回默认构造值,即

// 使用 get_id() 成员函数从线程对象中获取线程 ID

std::thread::id dThreadID = dThObj.get_id();

// 分离线程的 get_id() 函数将仅返回默认构造的 thread::id

assert(dThreadID == std::thread::id());

在线程函数中获取当前线程 ID

在当前由某个线程执行的函数内部,我们可以通过以下方式访问当前线程对象,

std::this_thread

因此,要在线程函数中获取当前线程 ID,我们可以使用 this_thread 调用 get_id(),即

// 获取正在执行此函数的线程的线程 ID

std::thread::id threadID = std::this_thread:: get_id () ;

#include

#include

#include

#include

using namespace std::chrono_literals;

void threadFunction()

{

std::cout << "Func Start" << std::endl;

// 获取正在执行此函数的线程的线程 ID

std::thread::id threadID = std::this_thread::get_id();

std::cout << "Inside Thread :: Thread ID : " << threadID << "\n";

std::cout << "Func End" << std::endl;

}

int main()

{

// 开始线程

std::thread th(threadFunction);

// 使用 get_id() 成员函数从线程对象中获取线程 ID

std::thread::id threadID = th.get_id();

// 加入线程,如果它是可连接的

if (th.joinable())

th.join();

std::cout << "Thread from Main : " << threadID << std::endl;

/** 从分离的线程中获取线程 ID ****/

// 开始线程

std::thread dThObj(threadFunction);

// 分离线程

dThObj.detach();

// 使用 get_id() 成员函数从线程对象中获取线程 ID

std::thread::id dThreadID = dThObj.get_id();

// 分离线程的 get_id() 函数将仅返回默认构造的 thread::id

assert(dThreadID == std::thread::id());

std::this_thread::sleep_for(2s);

std::cout << "Thread from Main : " << dThreadID << std::endl;

return 0;

}

Copyright © 2022 星辰幻想游戏活动专区 All Rights Reserved.