Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set name to a Win32 Thread?

Tags:

How do I set a name to a Win32 thread. I did'nt find any Win32 API to achieve the same. Basically I want to add the Thread Name in the Log file. Is TLS (Thread Local Storage) the only way to do it?

like image 430
Canopus Avatar asked May 25 '09 08:05

Canopus


People also ask

How do I name a thread in Windows?

There are two ways to set a thread name. The first is via the SetThreadDescription function. The second is by throwing a particular exception while the Visual Studio debugger is attached to the process.

How do you name a thread?

You can give a name to a thread by using setName() method of Thread class. You can also retrieve the name of a thread using getName() method of a Thread class. These two methods are public and final.

How do I create a thread in Win32?

You can also create a thread by calling the CreateRemoteThread function. This function is used by debugger processes to create a thread that runs in the address space of the process being debugged.

Is Win32 thread a library?

The Win32 thread library is a kernel-level library available on Windows systems. The Java thread API allows thread creation and management directly in Java programs.


2 Answers

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.

like image 53
Gishu Avatar answered Oct 23 '22 04:10

Gishu


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)
  {
  }
}
like image 24
fazhang Avatar answered Oct 23 '22 04:10

fazhang