其他人想必会有这样的感觉,早上酣畅淋漓的写完一段代码,心情特别舒适,可是却发现了异常,然后开始debug直到忘记了吃饭,好心情就一点点被消磨掉。这种情况在写多线程代码的时候更是常见,一个工作线程的任务被层层封装,然后才被扔到工作线程队列,我从哪里来是不知道的,甚至于连我在哪里都不知道,设置线程名称,就是为了解决“我在哪里”的问题。在debug时,线程有了名称,查bug的效率会得到提升。

  设置线程名称,只有短短的几行代码,windows已经做好了准备,只需要触发它。这么简单的东西其实没有必要写到博客里,但是最近我发现还是有不少人不知道、或者没想到去这么做的。

  以上是废话,以下才是重点:

#include <iostream>
#include <windows.h>
#include <process.h>
//2013.3.5
//cswuyg
//参考 chromium源码: src\base\threading\platform_thread_win.cc

// The information on how to set the thread name comes from
// a MSDN article: http://msdn2.microsoft.com/en-us/library/xcb2z8hs.aspx
const DWORD kVCThreadNameException = 0x406D1388;

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;

// This function has try handling, so it is separated out of its caller.
void SetNameInternal(DWORD thread_id, const char* name)
{
    //只在调试的时候生效 
    if (!::IsDebuggerPresent()) 
        return;
    THREADNAME_INFO info;
    info.dwType = 0x1000;
    info.szName = name;
    info.dwThreadID = thread_id;
    info.dwFlags = 0;

    __try
    {
        RaiseException(kVCThreadNameException, 0, sizeof(info)/sizeof(DWORD), reinterpret_cast<DWORD_PTR*>(&info));
    }
    __except(EXCEPTION_CONTINUE_EXECUTION) 
    {
    }
}

static unsigned int _stdcall Run(void* argv)
{
    while(true)
    {
        std::cout << "Thread " << (int)argv << std::endl;
        Sleep(5000);
    }
}

void testFunc()
{
    DWORD thread_id_1;
    HANDLE thread_handle_1 = (HANDLE)_beginthreadex( NULL, 0, Run, (void*)1, 0, (unsigned int*)&thread_id_1);
    SetNameInternal(thread_id_1, "My Thead Thread_1");
    DWORD thread_id_2;
    HANDLE thread_handle_2 = (HANDLE)_beginthreadex( NULL, 0, Run, (void*)2, 0, (unsigned int*)&thread_id_2);
    SetNameInternal(thread_id_2, "My Thead Thread_2");
}


int main()
{
    testFunc();
    system("pause");
    return 1;
}

  啥也不说了,代码很简单。

posted on 2013-05-30 21:52  烛秋  阅读(2458)  评论(0编辑  收藏  举报