How to: Set a Thread Name in Native Code
Visual Studio 2010
This topic applies to:
Edition | Visual Basic | C# | F# | C++ | Web Developer |
|---|---|---|---|---|---|
Express | ![]() | ![]() |
| Native only | ![]() |
Pro, Premium, and Ultimate | ![]() |
|
| Native only |
|
To set a thread name in your program, use the SetThreadName function, as shown in the following code example. Note that the thread name is copied to the thread so that the memory for the threadName parameter can be released.
//
// Usage: SetThreadName (-1, "MainThread");
//
#include <windows.h>
const DWORD MS_VC_EXCEPTION=0x406D1388;
#pragma pack(push,8)
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;
#pragma pack(pop)
void SetThreadName( DWORD dwThreadID, char* threadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
Slight variation
I've been using EXCEPTION_CONTINUE_EXECUTION, not EXCEPTION_EXECUTE_HANDLER, for years now. It seems to work perfectly, and whether coincidence or not, I've not seen the previous commenter's problem with needing a debugger active.
- 10/27/2010
- steveren
Note: Don't use outside debugger
For this to work in general you need to check ::IsDebuggerPresent() before throwing the exception. For some reason the runtime doesn't like to see that exception thrown outside a debugger.
Furthermore there are tools like profilers (for instance AQTime) which act as debuggers but don't allow the throw anyway. A command line option to your app can be used to turn on or off the thread naming call.
Furthermore there are tools like profilers (for instance AQTime) which act as debuggers but don't allow the throw anyway. A command line option to your app can be used to turn on or off the thread naming call.
- 10/7/2010
- Bengt Gustafsson

