std::thread - naming your thread

后端 未结 5 2050
谎友^
谎友^ 2020-12-08 04:02

The new C++ has this std::thread type. Works like a charm. Now I would like to give each thread a name for more easy debugging (like java allows you to). With pthreads I wou

5条回答
  •  借酒劲吻你
    2020-12-08 04:30

    An attempt at making a wrapper to deal with many Linuxes as well as Windows. Please edit as needed.

    #ifdef _WIN32
    #include 
    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(uint32_t dwThreadID, const char* threadName)
    {
    
      // DWORD dwThreadID = ::GetThreadId( static_cast( t.native_handle() ) );
    
       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)
       {
       }
    }
    void SetThreadName( const char* threadName)
    {
        SetThreadName(GetCurrentThreadId(),threadName);
    }
    
    void SetThreadName( std::thread* thread, const char* threadName)
    {
        DWORD threadId = ::GetThreadId( static_cast( thread->native_handle() ) );
        SetThreadName(threadId,threadName);
    }
    
    #elif defined(__linux__)
    #include 
    void SetThreadName( const char* threadName)
    {
      prctl(PR_SET_NAME,threadName,0,0,0);
    }
    
    #else
    void SetThreadName(std::thread* thread, const char* threadName)
    {
       auto handle = thread->native_handle();
       pthread_setname_np(handle,threadName);
    }
    #endif
    

提交回复
热议问题