16

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

Community
  • 1
  • 1
Michael Kelley
  • 3,579
  • 4
  • 37
  • 41
  • 1
    You can get the thread's start function name if that helps you in any way. – Nawaz Feb 20 '12 at 19:26
  • @Nawaz How would you do that? – CS. Aug 09 '12 at 11:57
  • 1
    @CS.: You've to use these API : [SymInitialize](http://msdn.microsoft.com/en-us/library/windows/desktop/ms681351%28v=vs.85%29.aspx) and [SymFromAddr](http://msdn.microsoft.com/en-us/library/windows/desktop/ms681323%28v=vs.85%29.aspx). I've used them, see this topic : [Get StartAddress of win32 thread from another process](http://stackoverflow.com/questions/8679406/get-startaddress-of-win32-thread-from-another-process) – Nawaz Aug 09 '12 at 12:29

3 Answers3

18

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

antiduh
  • 11,853
  • 4
  • 43
  • 66
Michael Kelley
  • 3,579
  • 4
  • 37
  • 41
18

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

Ana Betts
  • 73,868
  • 16
  • 141
  • 209
12

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.

Chris
  • 3,113
  • 26
  • 33
  • 1
    are you saying that there's absolutely no way to get the thread name that you've set in the debugger ? I'd like to put some debug check in my code to make sure it's called from the right thread, using the thread name – 0x26res Nov 16 '12 at 12:00
  • The thread 0x66c has exited with code 0 (0x0) -> I thought, maybe the 0x66c is something like a name ? – Andre Nov 04 '15 at 07:20