您的位置:首页 > 大数据 > 人工智能

给线程取名

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

#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;

}



运行程序,查看线程,很容易就会看到自己创建的线程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息