How to: Set a Thread Name in Native Code


The new home for Visual Studio documentation is Visual Studio 2017 Documentation on

The latest version of this topic can be found at How to: Set a Thread Name in Native Code.

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 ((DWORD)-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.  
#pragma pack(pop)  
void SetThreadName(DWORD dwThreadID, const char* threadName) {  
    info.dwType = 0x1000;  
    info.szName = threadName;  
    info.dwThreadID = dwThreadID;  
    info.dwFlags = 0;  
#pragma warning(push)  
#pragma warning(disable: 6320 6322)  
        RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);  
#pragma warning(pop)  

Debug Multithreaded Applications
Viewing Data in the Debugger
How to: Set a Thread Name in Managed Code