Give a name to a boost thread?

后端 未结 2 469
再見小時候
再見小時候 2020-12-08 16:24

Is it possible to give a name to a boost::thread so that the debuggers tables and the crash logs can be more readable? How?

2条回答
  •  自闭症患者
    2020-12-08 16:56

    I'm using boost 1.50.0 on Win32 + VS2010 and thread::native_handle contains number which I didn't manage to pair to anything in system. On the other hand, the thread::get_id() method returns directly windows thread ID in form of a hexadecimal string. Notice that the value returned is platform specific, though. The following code does work under Boost 1.50.0 + Win32 + VS2010. Parts of code reused from msdn

    const DWORD MS_VC_EXCEPTION = 0x406D1388;
    #pragma pack(push, 8)
    typedef struct THREADNAME_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 threadId, const char* threadName) {
        THREADNAME_INFO info;
        info.dwType = 0x1000;
        info.szName = threadName;
        info.dwThreadID = threadId;
        info.dwFlags = 0;
        __try {
            RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
        }
        __except(EXCEPTION_EXECUTE_HANDLER) {
        }
    }
    void SetThreadName(boost::thread::id threadId, std::string threadName) {
        // convert string to char*
        const char* cchar = threadName.c_str();
        // convert HEX string to DWORD
        unsigned int dwThreadId;
        std::stringstream ss;
        ss << std::hex << threadId;
        ss >> dwThreadId;
        // set thread name
        _SetThreadName((DWORD)dwThreadId, cchar);
    }
    

    Call like this:

    boost::thread* thr = new boost::thread(boost::bind(...));
    SetThreadName(thr->get_id(), "MyName");
    

提交回复
热议问题