简体   繁体   English

如何获取Win32线程的名称?

[英]How to get the name of a Win32 Thread?

I know of the non-intuitive process to set the name of a thread under Windows (see " How to set name to a Win32 Thread? "). 我知道在Windows下设置线程名称的非直观过程(请参阅“ 如何将名称设置为Win32线程? ”)。 Is there a way to get the name of the thread? 有没有办法获得线程的名称? I don't see any Windows API that lets me do this ( http://msdn.microsoft.com/en-us/library/windows/desktop/ms684847(v=vs.85).aspx ). 我没有看到任何允许我这样做的Windows API( http://msdn.microsoft.com/en-us/library/windows/desktop/ms684847 ( v=vs.85 ) .aspx )。

Threads don't actually have names in Win32. 线程实际上在Win32中没有名称。 The process via RaiseException is just a "Secret Handshake" with the VS Debugger, who actually stores the TID => Name mapping. 通过RaiseException的过程只是VS Debugger的“秘密握手”,它实际上存储了TID => Name映射。 Windows itself has no notion of a thread "Name". Windows本身没有线程“名称”的概念。

There is no such WinAPI call since there exists no such thing as thread names. 没有这样的WinAPI调用,因为不存在线程名称这样的东西。

If you set a thread name then the debugger of your IDE will store it for you, which makes it easier to debug. 如果设置了线程名称,那么IDE的调试器将为您存储它,这使得调试更容易。 However the name is never really attached to the thread by a windows API call. 但是,该名称永远不会通过Windows API调用真正附加到该线程。

If you run your application without a debugger then setting a thread name has no effect, therefore you can't retrieve the name. 如果在没有调试器的情况下运行应用程序,则设置线程名称无效,因此无法检索名称。

Even if it would be accessible - I wouldn't write code that works only with a debugger attached. 即使它是可访问的 - 我也不会编写仅适用于附加调试器的代码。 Better store the name for yourself together with the handle. 更好地将名称与手柄一起存储起来。

Beginning with Windows 10, version 1607, you can now get the name of a thread using GetThreadDescription() , assuming SetThreadDescription() was used to set the name of the thread. 从Windows 10版本1607开始,您现在可以使用GetThreadDescription()获取线程的名称,假设使用SetThreadDescription()来设置线程的名称。

Here's an example: 这是一个例子:

HRESULT hr = GetThreadDescription(ThreadHandle, &data);
if (SUCCEEDED(hr))
{   
    wprintf(“%ls\m”, data);
    LocalFree(data);
}

Here's the documentation: 这是文档:

https://msdn.microsoft.com/en-us/library/windows/desktop/mt774972(v=vs.85).aspx https://msdn.microsoft.com/en-us/library/windows/desktop/mt774972(v=vs.85).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM