为Linux下线程加个名字。同样的Windows 也可以干。 chrome 的源码中有使用到这个trick,raise 一个Exception.
1 #include <sys/prctl.h>
2 void set_thread_name(const char *prefix)
3 {
4 static int index = 0;
5 char thname[16];
6 snprintf(thname, sizeof(thname), "%s%d", prefix, __sync_fetch_and_add(&index, 1));
7 prctl(PR_SET_NAME, (usigned long)thname, 0, 0, 0); //~ refer to `man prctl`
8 }
9
windows 版本 原文见: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)
{
}
}