Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-80317

QThread: use SetThreadDescription to set the thread name when available

    XMLWordPrintable

Details

    • Suggestion
    • Resolution: Unresolved
    • Not Evaluated
    • None
    • 5.12.6
    • Core: Threads
    • None
    • Windows 10 version 1607 and newer.

    • Windows

    Description

      Currently QThread throws a 'magic' exception to set the thread name.
      This method only works if the debugger is already attached when the thread starts.

      Windows 10 version 1607 added a new API pair [SetThreadDescription()|https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreaddescription] and GetThreadDescription() to set and get thread names.

      A thread name set via this API is readable if the debugger is attached after the thread has started, and is also stored in xperf (WPA) and similar post-mortem debugging tools.

      Example code that could be inserted into void qt_set_thread_name(HANDLE threadId, LPCSTR threadName):

       

      // Find function pointer for Win10 1607 version
      // Kernel32 will definitely be loaded so directly ask for the handle
       typedef ::HRESULT(WINAPI* SetThreadDescription)(::HANDLE hThread, ::PCWSTR lpThreadDescription);
       auto set_thread_description_func = reinterpret_cast<SetThreadDescription>(::GetProcAddress(::GetModuleHandle(L"Kernel32.dll"), "SetThreadDescription"));
       if (set_thread_description_func)
       {
       // Convert to WCHAR
       const size_t WCHARBUFSIZE = 100; // Arbitrary limit, thread names should be short
       wchar_t wszDest[WCHARBUFSIZE] = {};
       MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, threadName, -1, wszDest, WCHARBUFSIZE);
       set_thread_description_func(::GetCurrentThread(), wszDest);
       return;
       }
      
      // Otherwise set name via magic exception...

       

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            thiago Thiago Macieira
            rthompson Richard Thompson
            Votes:
            3 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:

              Gerrit Reviews

                There are no open Gerrit changes