Michael Kelley
Michael Kelley

Reputation: 3689

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

Upvotes: 18

Views: 14550

Answers (3)

Michael Kelley
Michael Kelley

Reputation: 3689

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:

PWSTR data;
HRESULT hr = GetThreadDescription(ThreadHandle, &data);
if (SUCCEEDED(hr))
{   
    wprintf(L"%ls\n", data);
    LocalFree(data);
}

Here's the documentation:

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

Upvotes: 21

Ana Betts
Ana Betts

Reputation: 74692

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

Upvotes: 20

Chris
Chris

Reputation: 3121

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.

Upvotes: 12

Related Questions