How to set name to a Win32 Thread? How to set name to a Win32 Thread? multithreading multithreading

How to set name to a Win32 Thread?


Does this help ?How to: Set a Thread Name in Native Code

In managed code, it is as easy as setting the Name property of the corresponding Thread object.


http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.90).aspx

//// 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)  {  }}


Win32 threads do not have names. There is a Microsoft convention whereby applications raise special SEH exceptions containing a thread name. These exceptions can be intercepted by debuggers and used to indicate the thread name. A couple of the answers cover that.

However, that is all handled by the debugger. Threads themselves are nameless objects. So, if you want to associate names with your threads, you'll have to develop your own mechanism. Whilst you could use thread local storage that will only allow you to obtain the name from code executing in that thread. So a global map between thread ID and the name would seem like the most natural and useful approach.