std::thread - nombrando tu hilo

std::thread - nombrando tu hilo

Una forma portátil de hacer esto es mantener un mapa de nombres, codificado por la ID del hilo, obtenido de thread::get_id() . Alternativamente, como se sugiere en los comentarios, podría usar un thread_local variable, si solo necesita acceder al nombre desde dentro del hilo.

Si no necesita portabilidad, puede obtener el pthread_t subyacente de thread::native_handle() y haz cualquier travesura específica de plataforma que te guste con eso. Tenga en cuenta que el _np en las funciones de nombres de subprocesos significa "no posix", por lo que no se garantiza que estén disponibles en todas las implementaciones de pthreads.


Un intento de hacer un envoltorio para manejar muchos Linux además de Windows. Edite según sea necesario.

#ifdef _WIN32
#include <windows.h>
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<HANDLE>( 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<HANDLE>( thread->native_handle() ) );
    SetThreadName(threadId,threadName);
}

#elif defined(__linux__)
#include <sys/prctl.h>
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

Puedes usar std::thread::native_handle para obtener el subproceso definido de implementación subyacente. No hay una función estándar para eso de forma nativa.

Puede encontrar un ejemplo aquí.