How to get the name of a Win32 Thread?

若如初见. 提交于 2020-01-29 04:32:54

问题


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?"). 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).


回答1:


There is no such WinAPI call since there exists no such thing as thread names.

If you set a thread name then the debugger of your IDE will store it for you, which makes it easier to debug. However the name is never really attached to the thread by a windows API call.

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.




回答2:


Threads don't actually have names in Win32. The process via RaiseException is just a "Secret Handshake" with the VS Debugger, who actually stores the TID => Name mapping. Windows itself has no notion of a thread "Name".




回答3:


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.

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://stackoverflow.com/questions/9366722/how-to-get-the-name-of-a-win32-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!