Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to name a CWinThread thread?

I have a C++ application (VS2008), and I start threads like this:

CWinThread *myThread= AfxBeginThread(myOp,0);

Now all I wan to do is name this thread, so I can identify it while debugging.

It sounds like a simple task, but I could not find the way to do it. Is this possible, and if so, how?

like image 240
DuduArbel Avatar asked Feb 15 '11 09:02

DuduArbel


1 Answers

This can be done relatively easily as documented on MSDN: How to set a Thread Name in Native Code.

Essentially you send the debugger a magic exception containing the name and the thread ID, and the debugger then keeps track of and displays the name you sent it.

The sample code from the MSDN article is included below:

//
// 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)
   {
   }
}
like image 114
David Heffernan Avatar answered Oct 20 '22 00:10

David Heffernan