ACCU Home page ACCU Conference Page
Search Contact us ACCU at Flickr ACCU at GitHib ACCU at Facebook ACCU at Linked-in ACCU at Twitter Skip Navigation

Blogs: SetThreadName for Windows native programs

Posted by: Roger M Orr on 21 April 2007
[21-04-2007] How to name your threads when debugging C++ code on Windows
When I gave my presentation on debugging at ACCU I had several people asking me about how to name threads when debugging under Windows.

I originally found the technique described in a presentation about Visual Studio but it has since surfaced on MSDN as well -
http://msdn2.microsoft.com/en-us/library/xcb2z8hs(vs.71).aspx

The method is to generate a special runtime exception which allows the program to pass the name for the thread to the debugger.

Note that this only works with some windows debuggers, and obviously won't work if you attach the debugger to the program after the threads have started up.

I find this very useful when debugging programs with a lot of threads - I hope you will too!
Does anyone know similar techniques for other systems - gdb on Linux for example?


/**
 * SetThreadName
 *
 * Provide a text name for threads in the debugger.
 * Usage: SetThreadName (-1, "MainThread");
 */
void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName )
{
   typedef struct tagTHREADNAME_INFO
   {
      DWORD dwType; // must be 0x1000
      LPCSTR szName; // pointer to name (in user addr space)
      DWORD dwThreadID; // thread ID (-1=caller thread)
      DWORD dwFlags; // reserved for future use, must be zero
   } THREADNAME_INFO;

   THREADNAME_INFO info;
   info.dwType = 0x1000;
   info.szName = szThreadName;
   info.dwThreadID = dwThreadID;
   info.dwFlags = 0;

   __try
   {
      RaiseException( 0x406D1388, 0,
                      sizeof(info)/sizeof(DWORD),
                      (DWORD*)&info );
   }
   __except(EXCEPTION_CONTINUE_EXECUTION)
   {
   }
}