给线程取名

来源:互联网 发布:淘宝等级如何查询 编辑:程序博客网 时间:2024/05/17 01:18

       有的时候,为了调试方便,快速定位问题,我们会为线程取名。由于程序比较简单,我直接贴代码:

#include <iostream>

#include <process.h>

using namespace std;

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;

void SetThreadName(DWORD thread_id, const char* name) {
    // The debugger needs to be around to catch the name in the exception.  If
    // there isn't a debugger, we are just needlessly throwing an exception.
    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) {
    }
}

unsigned __stdcall SecondThreadFunc(void* pArguments) {
    for (int i = 0; i < 100; i++) {
        cout << "线程打印\n";
        Sleep(1000);
    }
    _endthread();
    return 1;
}

void Func() {
    unsigned thread_id;
    HANDLE handle_thread = (HANDLE)_beginthreadex(0, 0, &SecondThreadFunc, nullptr, 0, &thread_id);
    SetThreadName(thread_id, "thread22222");
    WaitForSingleObject(handle_thread, INFINITE);
    cout << "线程结束\n";
    CloseHandle(handle_thread);
}

int main(int argc, TCHAR * argv[]) {

    Func();
    return 0;
}

运行程序,查看线程,很容易就会看到自己创建的线程

1 0
原创粉丝点击